diff --git a/ocr/arabic/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/arabic/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..a7458adf9 --- /dev/null +++ b/ocr/arabic/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-04-26 +description: تعلم كيفية تنزيل نموذج HuggingFace باستخدام Python واستخراج النص من الصورة + باستخدام Python مع تحسين دقة OCR باستخدام Python عبر Aspose OCR Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: ar +og_description: حمّل نموذج HuggingFace للبايثون وعزّز خط أنابيب OCR الخاص بك. اتبع + هذا الدليل لاستخراج النص من صورة باستخدام بايثون وتحسين دقة OCR بالبايثون. +og_title: تحميل نموذج HuggingFace بايثون – دليل شامل لتحسين OCR +tags: +- OCR +- HuggingFace +- Python +- AI +title: تحميل نموذج HuggingFace بايثون – دليل خطوة بخطوة لتعزيز OCR +url: /ar/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحميل نموذج HuggingFace بايثون – دليل تحسين OCR الكامل + +هل حاولت **تحميل نموذج HuggingFace بايثون** وشعرت ببعض الضياع؟ لست وحدك. في العديد من المشاريع، تكون العقبة الأكبر هي الحصول على نموذج جيد على جهازك ثم جعل نتائج OCR مفيدة فعلاً. + +في هذا الدليل سنستعرض مثالًا عمليًا يوضح لك بالضبط كيفية **تحميل نموذج HuggingFace بايثون**، استخراج النص من صورة باستخدام **extract text from image python**، ثم **improve OCR accuracy python** باستخدام معالج ما بعد الذكاء الاصطناعي من Aspose. في النهاية ستحصل على سكريبت جاهز للتنفيذ يحول صورة فاتورة مشوشة إلى نص نظيف وقابل للقراءة—بدون سحر، فقط خطوات واضحة. + +## ما الذي ستحتاجه + +- Python 3.9+ (الكود يعمل على 3.11 أيضًا) +- اتصال إنترنت لتحميل النموذج مرة واحدة +- حزمة `asposeocrcloud` (`pip install asposeocrcloud`) +- صورة نموذجية (مثلاً `sample_invoice.png`) موجودة في مجلد تتحكم فيه + +هذا كل شيء—بدون أطر عمل ثقيلة، دون تعريفات خاصة بـ GPU ما لم ترغب في تسريع العملية. + +الآن، لنغوص في التنفيذ الفعلي. + +![سير عمل تحميل نموذج HuggingFace بايثون](image.png "مخطط تحميل نموذج HuggingFace بايثون") + +## الخطوة 1: إعداد محرك OCR واختيار اللغة +*(هنا نبدأ بـ **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**لماذا هذا مهم:** +محرك OCR هو خط الدفاع الأول؛ اختيار حزمة اللغة المناسبة يقلل من أخطاء التعرف على الأحرف فورًا، وهو جزء أساسي من **improve OCR accuracy python**. + +## الخطوة 2: تكوين نموذج AsposeAI – التحميل من HuggingFace +*(هنا نقوم فعليًا بـ **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**ماذا يحدث خلف الكواليس؟** +عندما تكون `allow_auto_download` مُفعلة، يتواصل SDK مع HuggingFace، يجلب نموذج `Qwen2.5‑3B‑Instruct‑GGUF`، ويخزنه في المجلد الذي حددته. هذا هو جوهر **download huggingface model python**—الـ SDK يتولى العبء الثقيل، لذا لا تحتاج إلى كتابة أوامر `git clone` أو `wget` بنفسك. + +*نصيحة احترافية:* احتفظ بـ `directory_model_path` على SSD للحصول على أوقات تحميل أسرع؛ النموذج حجمه ~3 GB حتى بصيغة `int8`. + +## الخطوة 3: ربط محرك الذكاء الاصطناعي بمحرك OCR +*(ربط الجزأين حتى نتمكن من **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**لماذا نربطهما؟** +محرك OCR يزودنا بنص خام قد يحتوي على أخطاء إملائية، أسطر مكسورة، أو علامات ترقيم غير صحيحة. يعمل محرك الذكاء الاصطناعي كمحرر ذكي، ينظف هذه المشكلات—وهو بالضبط ما تحتاجه لـ **improve OCR accuracy python**. + +## الخطوة 4: تشغيل OCR على صورتك +*(اللحظة التي نـ **extract text from image python** فيها أخيرًا.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +الـ `ocr_result` الآن يحتوي على خاصية `text` التي تضم الأحرف الخام التي رآها المحرك. في الواقع ستلاحظ بعض العثرات—قد يتحول “Invoice” إلى “Inv0ice” أو يظهر انقطاع سطر في وسط جملة. + +## الخطوة 5: التنظيف باستخدام معالج ما بعد الذكاء الاصطناعي +*(هذه الخطوة تُحسّن مباشرةً **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +نموذج الذكاء الاصطناعي يعيد كتابة النص، مطبقًا تصحيحات واعية للغة. لأننا استخدمنا نموذجًا مُدربًا على التعليمات من HuggingFace، يكون الناتج عادةً سلسًا وجاهزًا للمعالجة اللاحقة. + +## الخطوة 6: عرض النتيجة قبل وبعد +*(فحص سريع لمعرفة مدى **extract text from image python** و **improve OCR accuracy python**.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### النتيجة المتوقعة + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +لاحظ كيف صحّح الذكاء الاصطناعي “Inv0ice” إلى “Invoice” وأزال أي فواصل سطر عشوائية. هذا هو النتيجة الملموسة لـ **improve OCR accuracy python** باستخدام نموذج HuggingFace تم تحميله. + +## الأسئلة المتكررة (FAQ) + +### هل أحتاج إلى GPU لتشغيل النموذج؟ +لا. إعداد `gpu_layers=20` يخبر الـ SDK باستخدام ما يصل إلى 20 طبقة GPU إذا كان هناك GPU متوافق؛ وإلا سيتراجع إلى CPU. على لابتوب حديث، مسار الـ CPU لا يزال يعالج بضع مئات من الرموز في الثانية—مناسب لمعالجة الفواتير بين الحين والآخر. + +### ماذا لو فشل تحميل النموذج؟ +تأكد أن بيئتك تستطيع الوصول إلى `https://huggingface.co`. إذا كنت خلف بروكسي مؤسسي، اضبط متغيرات البيئة `HTTP_PROXY` و `HTTPS_PROXY`. سيعيد الـ SDK المحاولة تلقائيًا، ويمكنك أيضًا تنفيذ `git lfs pull` يدويًا للمستودع داخل `directory_model_path`. + +### هل يمكنني استبدال النموذج بآخر أصغر؟ +بالطبع. فقط استبدل `hugging_face_repo_id` بمستودع آخر (مثلاً `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) واضبط `hugging_face_quantization` وفقًا لذلك. النماذج الأصغر تُحمَّل أسرع وتستهلك ذاكرة أقل، رغم أنك قد تفقد بعض جودة التصحيح. + +### كيف يساعدني هذا في **extract text from image python** في مجالات أخرى؟ +تعمل نفس السلسلة على الإيصالات، جوازات السفر، أو الملاحظات المكتوبة يدويًا. التغيير الوحيد هو حزمة اللغة (`ocr.Language.FRENCH`، إلخ) وربما نموذج مخصص لمجال معين من HuggingFace. + +## مكافأة: أتمتة معالجة ملفات متعددة + +إذا كان لديك مجلد مليء بالصور، غلف استدعاء OCR في حلقة بسيطة: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +هذه الإضافة الصغيرة تسمح لك بـ **download huggingface model python** مرة واحدة، ثم معالجة مئات الملفات دفعيًا—ممتاز لتوسيع خط أنابيب أتمتة المستندات الخاص بك. + +## الخاتمة + +لقد استعرضنا مثالًا كاملاً من البداية إلى النهاية يوضح لك كيفية **download HuggingFace model python**، **extract text from image python**، و **improve OCR accuracy python** باستخدام OCR Cloud من Aspose ومعالج ما بعد الذكاء الاصطناعي. السكريبت جاهز للتنفيذ، والمفاهيم مشروحة، ورأيت النتيجة قبل وبعد لتتأكد من عمله. + +ما الخطوة التالية؟ جرّب استبدال نموذج HuggingFace بنموذج آخر، جرب حزم لغات مختلفة، أو أدخل النص المنقح في خط أنابيب NLP لاحق (مثل استخراج الكيانات لعناصر الفاتورة). السماء هي الحد، والأساس الذي بنيته الآن صلب. + +هل لديك أسئلة أو صورة معقدة لا يزال OCR يخطئ فيها؟ اترك تعليقًا أدناه، ولنحل المشكلة معًا. برمجة سعيدة! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/arabic/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..c709b20e4 --- /dev/null +++ b/ocr/arabic/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-04-26 +description: قم بتنزيل نموذج OCR بسرعة باستخدام Aspose OCR Python. تعلّم كيفية تعيين + دليل النموذج، وتكوين مسار النموذج، وكيفية تنزيل النموذج في بضع أسطر. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: ar +og_description: قم بتنزيل نموذج OCR في ثوانٍ باستخدام Aspose OCR Python. يوضح هذا + الدليل كيفية تعيين دليل النموذج، وتكوين مسار النموذج، وكيفية تنزيل النموذج بأمان. +og_title: تحميل نموذج OCR – دليل Aspose OCR الكامل للبايثون +tags: +- OCR +- Python +- Aspose +title: تنزيل نموذج OCR باستخدام Aspose OCR Python – دليل خطوة بخطوة +url: /ar/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – دليل Aspose OCR الكامل للبايثون + +هل تساءلت يوماً كيف **download ocr model** باستخدام Aspose OCR في بايثون دون البحث في وثائق لا تنتهي؟ لست وحدك. يواجه العديد من المطورين مشكلة عندما لا يكون النموذج موجوداً محلياً وتظهر رسالة خطأ غامضة من الـ SDK. الخبر السار؟ الحل يتطلب بضع أسطر فقط، وستكون النموذج جاهزاً للاستخدام في دقائق. + +في هذا الدرس سنستعرض كل ما تحتاج معرفته: من استيراد الفئات الصحيحة، إلى **set model directory**، إلى **how to download model** فعلياً، وأخيراً التحقق من المسار. بنهاية الدرس ستتمكن من تشغيل OCR على أي صورة باستدعاء دالة واحدة، وستفهم خيارات **configure model path** التي تحافظ على تنظيم مشروعك. لا إطالة، مجرد مثال عملي قابل للتنفيذ لمستخدمي **aspose ocr python**. + +## ما ستتعلمه + +- كيفية استيراد فئات Aspose OCR Cloud بشكل صحيح. +- الخطوات الدقيقة لـ **download ocr model** تلقائيًا. +- طرق **set model directory** و **configure model path** لبناءات قابلة لإعادة الإنتاج. +- كيفية التحقق من أن النموذج مُهيأ وأين يقع على القرص. +- الأخطاء الشائعة (الأذونات، المجلدات المفقودة) والحلول السريعة. + +### المتطلبات المسبقة + +- Python 3.8+ مثبت على جهازك. +- حزمة `asposeocrcloud` (`pip install asposeocrcloud`). +- صلاحية كتابة إلى المجلد الذي تريد تخزين النموذج فيه (مثال: `C:\models` أو `~/ocr_models`). + +--- + +## الخطوة 1: استيراد فئات Aspose OCR Cloud + +أول شيء تحتاجه هو جملة الاستيراد الصحيحة. هذه الجملة تجلب الفئات التي تدير إعداد النموذج وعمليات OCR. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*لماذا هذا مهم:* `AsposeAI` هو المحرك الذي سيقوم بتشغيل OCR، بينما `AsposeAIModelConfig` يخبر المحرك **where** يبحث عن النموذج و**whether** يجب أن يجلبه تلقائيًا. تخطي هذه الخطوة أو استيراد الوحدة الخاطئة سيتسبب في حدوث `ModuleNotFoundError` قبل أن تصل إلى جزء التحميل. + +--- + +## الخطوة 2: تعريف إعداد النموذج (Set Model Directory & Configure Model Path) + +الآن نخبر Aspose أين يتم حفظ ملفات النموذج. هنا تقوم بـ **set model directory** و **configure model path**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**نصائح وملاحظات** + +- **المسارات المطلقة** تجنب الالتباس عندما يُشغل السكريبت من دليل عمل مختلف. +- على Linux/macOS قد تستخدم `"/home/you/ocr_models"`؛ على Windows، أضف البادئة `r` لتعامل مع الشرطات المائلة عكسياً حرفيًا. +- ضبط `allow_auto_download="true"` هو المفتاح لـ **how to download model** دون كتابة كود إضافي. + +--- + +## الخطوة 3: إنشاء كائن AsposeAI باستخدام الإعداد + +بعد إعداد التكوين، قم بإنشاء محرك OCR. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*لماذا هذا مهم:* الآن يحمل كائن `ocr_ai` الإعداد الذي عرّفناه. إذا لم يكن النموذج موجودًا، فإن الاستدعاء التالي سيفعل التحميل تلقائيًا—وهذا جوهر **how to download model** بطريقة بدون تدخل يدوي. + +--- + +## الخطوة 4: تفعيل تحميل النموذج (إذا لزم الأمر) + +قبل أن تتمكن من تشغيل OCR، عليك التأكد من أن النموذج موجود فعليًا على القرص. طريقة `is_initialized()` تتحقق وتُجبر التهيئة في آن واحد. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**ماذا يحدث خلف الكواليس؟** + +- الاستدعاء الأول لـ `is_initialized()` يُعيد `False` لأن مجلد النموذج فارغ. +- الـ `print` يُعلم المستخدم بأن التحميل على وشك البدء. +- الاستدعاء الثاني يجبر Aspose على جلب النموذج من مستودع Hugging Face الذي حددته مسبقًا. +- بمجرد اكتمال التحميل، تُعيد الطريقة `True` في الفحوصات اللاحقة. + +**حالة خاصة:** إذا كان اتصالك يمنع الوصول إلى Hugging Face، ستظهر استثناء. في هذه الحالة، قم بتحميل ملف ZIP للنموذج يدويًا، فك ضغطه داخل `directory_model_path`، ثم أعد تشغيل السكريبت. + +--- + +## الخطوة 5: إظهار المسار المحلي حيث يتوفر النموذج الآن + +بعد انتهاء التحميل، ربما تريد معرفة أين تم وضع الملفات. هذا يساعد في تصحيح الأخطاء وإعداد خطوط CI. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +الناتج النموذجي يكون كالتالي: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +الآن قد نجحت في **download ocr model**، وضبطت الدليل، وتأكدت من المسار. + +--- + +## نظرة بصرية عامة + +فيما يلي مخطط بسيط يوضح التدفق من الإعداد إلى نموذج جاهز للاستخدام. + +![مخطط تدفق download ocr model يُظهر الإعداد، التحميل التلقائي، والمسار المحلي](/images/download-ocr-model-flow.png) + +*النص البديل يتضمن الكلمة المفتاحية الأساسية لتحسين SEO.* + +--- + +## الاختلافات الشائعة وكيفية التعامل معها + +### 1. استخدام مستودع نموذج مختلف + +إذا كنت تحتاج نموذجًا غير `openai/gpt2`، فقط استبدل قيمة `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +تأكد من أن المستودع عام أو أن لديك الرمز المميز (token) اللازم في بيئتك. + +### 2. تعطيل التحميل التلقائي + +أحيانًا تريد التحكم في التحميل يدويًا (مثلاً في بيئات معزولة). اضبط `allow_auto_download` إلى `"false"` واستدعِ سكريبت تحميل مخصص قبل التهيئة: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. تغيير دليل النموذج أثناء التشغيل + +يمكنك إعادة ضبط المسار دون إنشاء كائن `AsposeAI` جديد: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## نصائح احترافية للاستخدام في الإنتاج + +- **تخزين النموذج مؤقتًا:** احتفظ بالمجلد على قرص شبكة مشترك إذا كانت عدة خدمات تحتاج إلى نفس النموذج. هذا يجنب التحميلات المتكررة. +- **تثبيت نسخة محددة:** قد يتم تحديث مستودع Hugging Face. لتثبيت نسخة معينة، أضف `@v1.0.0` إلى معرف المستودع (`"openai/gpt2@v1.0.0"`). +- **الأذونات:** تأكد من أن المستخدم الذي يشغل السكريبت يمتلك صلاحيات قراءة/كتابة على `directory_model_path`. على Linux، عادةً ما يكفي `chmod 755`. +- **التسجيل (Logging):** استبدل عبارات `print` البسيطة بوحدة `logging` في بايثون للحصول على مراقبة أفضل في التطبيقات الكبيرة. + +--- + +## مثال كامل جاهز للنسخ واللصق + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**الناتج المتوقع** (التشغيل الأول سيقوم بالتحميل، التشغيلات اللاحقة ستتخطى التحميل): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +شغّل السكريبت مرة أخرى؛ سترى سطر المسار فقط لأن النموذج مُخزن بالفعل. + +--- + +## الخلاصة + +لقد غطينا العملية الكاملة لـ **download ocr model** باستخدام Aspose OCR للبايثون، وأظهرنا كيفية **set model directory** وشرحنا تفاصيل **configure model path**. ببضع أسطر من الكود يمكنك أتمتة التحميل، تجنب الخطوات اليدوية، والحفاظ على قابلية إعادة إنتاج خط أنابيب OCR الخاص بك. + +بعد ذلك، قد ترغب في استكشاف استدعاء OCR الفعلي (`ocr_ai.recognize_image(...)`) أو تجربة نموذج Hugging Face مختلف لتحسين الدقة. مهما كان المسار الذي تختاره، فإن الأساس الذي بنيناه هنا—إعداد واضح، تحميل تلقائي، والتحقق من المسار—سيجعل أي تكامل مستقبلي سهلًا. + +هل لديك أسئلة حول حالات الحافة، أو تريد مشاركة طريقة تعديل دليل النموذج للنشر السحابي؟ اترك تعليقًا أدناه، وتمنياتنا لك ببرمجة سعيدة! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/arabic/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..a0f3c613b --- /dev/null +++ b/ocr/arabic/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-04-26 +description: كيفية ما بعد معالجة نتائج التعرف الضوئي على الأحرف واستخراج النص مع الإحداثيات. + تعلّم حلاً خطوة بخطوة باستخدام الإخراج المُنظم وتصحيح الذكاء الاصطناعي. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: ar +og_description: كيفية ما بعد معالجة نتائج OCR واستخراج النص مع الإحداثيات. اتبع هذا + الدليل الشامل للحصول على سير عمل موثوق. +og_title: كيفية ما بعد معالجة OCR – دليل كامل +tags: +- OCR +- Python +- AI +- Text Extraction +title: كيفية ما بعد معالجة OCR – استخراج النص مع الإحداثيات في بايثون +url: /ar/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية ما بعد معالجة OCR – استخراج النص مع الإحداثيات في بايثون + +هل احتجت يومًا إلى **how to post‑process OCR** لأن المخرجات الأولية كانت صاخبة أو غير محاذاة؟ لست وحدك. في العديد من المشاريع الواقعية—مسح الفواتير، رقمنة الإيصالات، أو حتى تعزيز تجارب الواقع المعزز—يُعطيك محرك OCR كلمات خام، لكن لا يزال عليك تنظيفها وتتبع مكان كل كلمة على الصفحة. هنا يبرز دور وضع الإخراج المُنظم مع معالج ما بعد المعالجة المدفوع بالذكاء الاصطناعي. + +> **نصيحة احترافية:** إذا كنت تستخدم مكتبة OCR مختلفة، ابحث عن وضع “structured” أو “layout”؛ المفاهيم تبقى نفسها. + +--- + +## المتطلبات المسبقة + +قبل أن نبدأ، تأكد من وجود ما يلي: + +| المتطلب | لماذا يهم | +|-------------|----------------| +| Python 3.9+ | الصياغة الحديثة وتلميحات الأنواع | +| `ocr` library that supports `OutputMode.STRUCTURED` (e.g., a fictional `myocr`) | ضرورية لبيانات الصناديق المحيطة | +| An AI post‑processing module (could be OpenAI, HuggingFace, or a custom model) | تحسن الدقة بعد OCR | +| An image file (`input.png`) in your working directory | المصدر الذي سنقرأه | + +إذا كان أي من هذه غير مألوف، ما عليك سوى تثبيت الحزم الوهمية باستخدام `pip install myocr ai‑postproc`. يحتوي الكود أدناه أيضًا على نماذج احتياطية لتتمكن من اختبار التدفق دون المكتبات الحقيقية. + +--- + +## الخطوة 1: تمكين وضع الإخراج المُنظم لمحرك OCR + +الأول الذي نفعله هو إخبار محرك OCR بأن يعطينا أكثر من مجرد نص عادي. الإخراج المُنظم يُعيد كل كلمة مع صندوقها المحيط ودرجة الثقة، وهو أمر أساسي لـ **extract text with coordinates** لاحقًا. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*لماذا يهم هذا:* بدون وضع مُنظم ستحصل فقط على سلسلة طويلة، وستفقد المعلومات المكانية التي تحتاجها لتراكب النص على الصور أو لتغذية تحليل التخطيط اللاحق. + +--- + +## الخطوة 2: التعرف على الصورة واستخلاص الكلمات والصناديق ومستوى الثقة + +الآن نُدخل الصورة إلى المحرك. النتيجة هي كائن يحتوي على قائمة من كائنات الكلمات، كل منها يُظهر `text`، `x`، `y`، `width`، `height`، و `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*حالة حافة:* إذا كانت الصورة فارغة أو غير قابلة للقراءة، سيكون `structured_result.words` قائمة فارغة. من الممارسات الجيدة التحقق من ذلك ومعالجته بلطف. + +--- + +## الخطوة 3: تشغيل ما بعد معالجة AI مع الحفاظ على المواقع + +حتى أفضل محركات OCR ترتكب أخطاء—مثل الخلط بين “O” و “0” أو فقدان الحركات. يمكن لنموذج AI مدرب على نصوص محددة المجال تصحيح هذه الأخطاء. الأهم أننا نحافظ على الإحداثيات الأصلية بحيث يبقى التخطيط المكاني سليمًا. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*لماذا نحافظ على الإحداثيات:* العديد من المهام اللاحقة (مثل توليد PDF، وضع علامات AR) تعتمد على التحديد الدقيق للموقع. يتعامل AI فقط مع حقل `text`، ويترك `x`، `y`، `width`، `height` دون تغيير. + +--- + +## الخطوة 4: التكرار على الكلمات المصححة وعرض نصها مع الإحداثيات + +أخيرًا، نمر على الكلمات المصححة ونطبع كل كلمة مع زاويةها العلوية اليسرى `(x, y)`. هذا يحقق هدف **extract text with coordinates**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**الناتج المتوقع (مثال):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +كل سطر يُظهر الكلمة المصححة وموقعها الدقيق على الصورة الأصلية. + +--- + +## مثال كامل يعمل + +فيما يلي سكريبت واحد يجمع كل شيء معًا. يمكنك نسخه، تعديل عبارات الاستيراد لتتناسب مع مكتباتك الفعلية، وتشغيله مباشرة. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**تشغيل السكريبت** + +```bash +python ocr_postprocess_demo.py +``` + +إذا كانت المكتبات الحقيقية مثبتة، سيعالج السكريبت ملف `input.png` الخاص بك. وإلا، سيسمح لك تنفيذ النموذج الاحتياطي برؤية التدفق المتوقع والناتج دون أي تبعيات خارجية. + +--- + +## الأسئلة المتكررة (FAQ) + +| السؤال | الجواب | +|----------|--------| +| *هل يعمل هذا مع Tesseract؟* | لا يوفّر Tesseract وضعًا منظمًا بشكل افتراضي، لكن الأغلفة مثل `pytesseract.image_to_data` تُعيد الصناديق المحيطة التي يمكنك تمريرها إلى نفس معالج AI. | +| *ماذا لو احتجت الزاوية السفلية اليمنى بدلاً من العليا اليسرى؟* | كل كائن كلمة يوفر أيضًا `width` و `height`. احسب `x2 = x + width` و `y2 = y + height` للحصول على الزاوية المقابلة. | +| *هل يمكنني معالجة عدة صور دفعة واحدة؟* | بالتأكيد. ضع الخطوات داخل حلقة `for image_path in Path("folder").glob("*.png"):` وجمع النتائج لكل ملف. | +| *كيف أختار نموذج AI للتصحيح؟* | للنص العام، نموذج GPT‑2 صغير مُدرب على أخطاء OCR يعمل. للبيانات المتخصصة (مثل الوصفات الطبية)، درّب نموذج تسلسل‑إلى‑تسلسل على بيانات مزدوجة (ضجيج‑نظيفة). | +| *هل درجة الثقة مفيدة بعد تصحيح AI؟* | يمكنك الاحتفاظ بالثقة الأصلية للتصحيح، لكن قد يُخرج AI درجة ثقته الخاصة إذا كان النموذج يدعم ذلك. | + +--- + +## الحالات الحدية وأفضل الممارسات + +1. **صور فارغة أو تالفة** – تحقق دائمًا من أن `structured_result.words` غير فارغ قبل المتابعة. +2. **نصوص غير لاتينية** – تأكد من تكوين محرك OCR للغة المستهدفة؛ يجب أن يكون معالج AI مدربًا على نفس النص. +3. **الأداء** – تصحيح AI قد يكون مكلفًا. خزن النتائج مؤقتًا إذا كنت ستعيد استخدام نفس الصورة، أو نفّذ خطوة AI بشكل غير متزامن. +4. **نظام الإحداثيات** – قد تستخدم مكتبات OCR أصولًا مختلفة (أعلى‑يسار مقابل أسفل‑يسار). عدّل وفقًا لذلك عند وضع النص على ملفات PDF أو القماش. + +--- + +## الخلاصة + +أصبح لديك الآن وصفة شاملة من البداية إلى النهاية لـ **how to post‑process OCR** واستخراج النص مع الإحداثيات بشكل موثوق. من خلال تمكين الإخراج المُنظم، تمرير النتيجة عبر طبقة تصحيح AI، والحفاظ على الصناديق المحيطة الأصلية، يمكنك تحويل مسحات OCR الصاخبة إلى نص نظيف ومُدرك مكانيًا جاهز للمهام اللاحقة مثل توليد PDF، أتمتة إدخال البيانات، أو تراكب الواقع المعزز. + +هل أنت مستعد للخطوة التالية؟ جرّب استبدال نموذج AI الاحتياطي بـ استدعاء OpenAI `gpt‑4o‑mini`، أو دمج خط الأنابيب في FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/arabic/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..3db89698d --- /dev/null +++ b/ocr/arabic/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-26 +description: كيفية التعرف على الصور بسرعة باستخدام بايثون. تعلم خط أنابيب التعرف على + الصور، المعالجة الدفعية، وأتمتة التعرف على الصور باستخدام الذكاء الاصطناعي. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: ar +og_description: كيفية التعرف على الصور بسرعة باستخدام بايثون. يشرح هذا الدليل خط أنابيب + التعرف على الصور، والتجميع، والأتمتة باستخدام الذكاء الاصطناعي. +og_title: كيفية التعرف على الصور – أتمتة خط أنابيب التعرف على الصور +tags: +- image-processing +- python +- ai +title: كيفية التعرف على الصور – أتمتة خط أنابيب التعرف على الصور +url: /ar/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيف تتعرف على الصور – أتمتة خط أنابيب التعرف على الصور + +هل تساءلت يومًا **كيف تتعرف على الصور** دون كتابة آلاف الأسطر من الشيفرة؟ لست وحدك—الكثير من المطورين يواجهون نفس المشكلة عندما يحتاجون لأول مرة إلى معالجة العشرات أو المئات من الصور. الخبر السار؟ بخطوات بسيطة يمكنك إنشاء خط أنابيب كامل للتعرف على الصور يقوم بالتجميع، التنفيذ، والتنظيف تلقائيًا. + +في هذا الدليل سنستعرض مثالًا كاملاً قابلاً للتنفيذ يوضح **كيفية تجميع الصور**، إمداد كل صورة إلى محرك ذكاء اصطناعي، معالجة النتائج، وأخيرًا تحرير الموارد. في النهاية ستحصل على سكريبت مستقل يمكنك إدراجه في أي مشروع، سواء كنت تبني مُصنِّفًا للصور، نظام مراقبة جودة، أو مولد مجموعة بيانات بحثية. + +## ما ستتعلمه + +- **كيفية التعرف على الصور** باستخدام محرك ذكاء اصطناعي تجريبي (النمط هو نفسه للخدمات الحقيقية مثل TensorFlow، PyTorch، أو واجهات برمجة التطبيقات السحابية). +- كيفية بناء **خط أنابيب للتعرف على الصور** يتعامل مع التجميع بفعالية. +- أفضل طريقة لـ **أتمتة التعرف على الصور** لتجنب الحاجة إلى حلقة يدوية على الملفات في كل مرة. +- نصائح لتوسيع الخط وإطلاق الموارد بأمان. + +> **المتطلبات المسبقة:** Python 3.8+، إلمام أساسي بالدوال والحلقات، وبعض ملفات الصور (أو مساراتها) التي تريد معالجتها. لا توجد مكتبات خارجية مطلوبة للمثال الأساسي، لكن سنذكر أين يمكنك توصيل SDKs حقيقية للذكاء الاصطناعي. + +![مخطط يوضح كيفية التعرف على الصور في خط أنابيب معالجة دفعات](pipeline.png "مخطط كيفية التعرف على الصور") + +## الخطوة 1: تجميع صورك – كيفية تجميع الصور بفعالية + +قبل أن يبدأ الذكاء الاصطناعي بأي عمل ثقيل، تحتاج إلى مجموعة من الصور لتغذيتها. فكر في ذلك كقائمة البقالة؛ سيختار المحرك كل عنصر من القائمة واحدًا تلو الآخر. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**لماذا التجميع؟** +التجميع يقلل من كمية الشيفرة المتكررة التي تكتبها ويجعل إضافة التوازي لاحقًا أمرًا بسيطًا. إذا احتجت يومًا لمعالجة 10 000 صورة، ستغير فقط مصدر `image_batch`—وبقية الخط ستظل كما هي. + +## الخطوة 2: تشغيل خط أنابيب التعرف على الصور (التعرف على الصور باستخدام الذكاء الاصطناعي) + +الآن نربط التجميع بالمُعرّف الفعلي. في سيناريو واقعي قد تستدعي `torchvision.models` أو نقطة نهاية سحابية؛ هنا نحاكي السلوك لكي يبقى الدليل مستقلًا. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**شرح:** +- `engine.recognize_image` هو قلب **خط أنابيب التعرف على الصور**؛ يمكن أن يكون استدعاءً لنموذج تعلم عميق أو واجهة برمجة تطبيقات REST. +- `postprocessor.run` يوضح **أتمتة التعرف على الصور** عن طريق تحويل التنبؤات الخام إلى قاموس منظم يمكنك تخزينه أو بثه. +- نجمع كل قاموس `corrected` في `recognized_results` لتكون الخطوات اللاحقة (مثل إدخال قاعدة البيانات) سهلة التنفيذ. + +## الخطوة 3: ما بعد المعالجة والتخزين – أتمتة نتائج التعرف على الصور + +بعد حصولك على قائمة مرتبة من التنبؤات، عادةً ما تريد حفظها. المثال أدناه يكتب ملف CSV؛ يمكنك استبداله بقاعدة بيانات أو طابور رسائل إذا رغبت. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**لماذا CSV؟** +ملف CSV قابل للقراءة عالميًا—Excel، pandas، وحتى المحررات النصية البسيطة يمكنها فتحه. إذا احتجت لاحقًا إلى **أتمتة التعرف على الصور** على نطاق واسع، استبدل كتلة الكتابة بإدخال جماعي إلى بحيرة البيانات الخاصة بك. + +## الخطوة 4: التنظيف – تحرير موارد الذكاء الاصطناعي بأمان + +العديد من SDKs للذكاء الاصطناعي تخصّص ذاكرة GPU أو تنشئ خيوط عمل. نسيان تحريرها قد يسبب تسربًا للذاكرة وتعطلات غير مرغوبة. رغم أن كائناتنا التجريبية لا تحتاج ذلك، سنظهر النمط الصحيح. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +تشغيل السكريبت يطبع رسالة تأكيد ودية، تُخبرك بأن الخط انتهى بنجاح. + +## السكريبت الكامل القابل للتنفيذ + +بجمع كل الأجزاء معًا، إليك البرنامج الكامل جاهزًا للنسخ واللصق: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### النتيجة المتوقعة + +عند تشغيل السكريبت (مع افتراض وجود المسارات الثلاثة الوهمية)، ستحصل على ما يشبه: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +وسيحتوي الملف `recognition_results.csv` المُنشأ على: + +| الصورة | التصنيف | الثقة | +|---------------------|---------|-------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## الخلاصة + +أصبح لديك الآن مثال شامل من البداية إلى النهاية لـ **كيفية التعرف على الصور** باستخدام Python، متضمنًا **خط أنابيب للتعرف على الصور**، معالجة التجميع، وأتمتة ما بعد المعالجة. النمط قابل للتوسيع: استبدل الفئات التجريبية بنموذج حقيقي، وزد `image_batch`، وستحصل على حل جاهز للإنتاج. + +هل ترغب في التعمق أكثر؟ جرّب الخطوات التالية: + +- استبدل `MockEngine` بنموذج TensorFlow أو PyTorch للحصول على تنبؤات حقيقية. +- قم بتوازي الحلقة باستخدام `concurrent.futures.ThreadPoolExecutor` لتسريع الدفعات الكبيرة. +- اربط كاتب CSV بدلو تخزين سحابي لتتمكن من **أتمتة التعرف على الصور** عبر عمال موزعين. + +لا تتردد في التجربة، وكسر الأشياء، ثم إصلاحها—فهذه هي الطريقة لتصبح خبيرًا حقيقيًا في خطوط أنابيب التعرف على الصور. إذا واجهت أي صعوبات أو كان لديك أفكار لتحسين المحتوى، اترك تعليقًا أدناه. برمجة سعيدة! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/arabic/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..2e67a247c --- /dev/null +++ b/ocr/arabic/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-04-26 +description: قُم بإخفاء أرقام بطاقات الائتمان بسرعة باستخدام معالجة ما بعد التعرف + الضوئي على الأحرف AsposeAI. تعلّم الامتثال لمعيار PCI، وإخفاء باستخدام التعبيرات + النمطية، وتنظيف البيانات في دليل خطوة بخطوة. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: ar +og_description: إخفاء أرقام بطاقات الائتمان في نتائج OCR باستخدام AsposeAI. يغطي هذا + الدليل الالتزام بمعايير PCI، وإخفاء باستخدام التعبيرات النمطية، وتنظيف البيانات. +og_title: إخفاء أرقام بطاقات الائتمان – دليل كامل لمعالجة ما بعد التعرف الضوئي على + الحروف باستخدام بايثون +tags: +- OCR +- Python +- security +title: إخفاء أرقام بطاقات الائتمان في مخرجات OCR – دليل بايثون الكامل +url: /ar/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إخفاء أرقام بطاقات الائتمان – دليل بايثون كامل + +هل احتجت يومًا إلى **إخفاء أرقام بطاقات الائتمان** في نص يأتي مباشرةً من محرك OCR؟ لست وحدك. في الصناعات المنظمة، كشف رقم PAN الكامل (Primary Account Number) يمكن أن يضعك في مشكلة مع مدققي الامتثال PCI. الخبر السار؟ باستخدام بضع أسطر من بايثون و post‑processing hook الخاص بـ AsposeAI، يمكنك إخفاء الثمانية أرقام الوسطى تلقائيًا والبقاء في الجانب الآمن. + +في هذا الدرس سنستعرض سيناريو واقعي: تشغيل OCR على صورة إيصال، ثم تطبيق دالة **معالجة ما بعد OCR** مخصصة تقوم بتنظيف أي بيانات PCI. في النهاية ستحصل على مقطع شفرة قابل لإعادة الاستخدام يمكنك إدراجه في أي سير عمل AsposeAI، بالإضافة إلى مجموعة من النصائح العملية للتعامل مع الحالات الخاصة وتوسيع الحل. + +## ما ستتعلمه + +- كيفية تسجيل معالج ما بعد مخصص مع **AsposeAI**. +- لماذا نهج **إخفاء باستخدام التعبير النمطي** سريع وموثوق. +- أساسيات **الامتثال PCI** المتعلقة بتنظيف البيانات. +- طرق توسيع النمط لتعدد صيغ البطاقات أو الأرقام الدولية. +- المخرجات المتوقعة وكيفية التحقق من أن الإخفاء تم بنجاح. + +> **المتطلبات المسبقة** – يجب أن يكون لديك بيئة Python 3 تعمل، وحزمة Aspose.AI for OCR مثبتة (`pip install aspose-ocr`)، وصورة نموذجية (مثلاً `receipt.png`) تحتوي على رقم بطاقة ائتمان. لا توجد خدمات خارجية أخرى مطلوبة. + +--- + +## الخطوة 1: تعريف معالج ما بعد يُخفي أرقام بطاقات الائتمان + +جوهر الحل يكمن في دالة صغيرة تستقبل نتيجة OCR، وتنفذ روتين **إخفاء باستخدام التعبير النمطي**، وتعيد النص المنقّى. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**لماذا يعمل هذا:** +- التعبير النمطي `(\d{4})\d{8}(\d{4})` يطابق بالضبط 16 رقمًا متتاليًا، وهو الصيغة الشائعة لفيزا، ماستركارد، والعديد غيرها. +- من خلال التقاط الأربعة أرقام الأولى والأخيرة (`\1` و`\2`) نحافظ على معلومات كافية للتصحيح مع الالتزام بقواعد **PCI compliance** التي تحظر تخزين PAN الكامل. +- الاستبدال `\1****\2` يخفي الثمانية أرقام الوسطى الحساسة، محولًا `1234567812345678` إلى `1234****5678`. + +**نصيحة احترافية:** إذا كنت بحاجة لدعم أرقام American Express ذات 15 رقمًا، أضف نمطًا ثانيًا مثل `r'(\d{4})\d{6}(\d{5})'` وقم بتنفيذ كلا الاستبدالين بالتتابع. + +--- + +## الخطوة 2: تهيئة محرك AsposeAI + +قبل أن نتمكن من إرفاق معالج ما بعدنا، نحتاج إلى نسخة من محرك OCR. يجمع AsposeAI نموذج OCR وواجهة API بسيطة للمعالجة المخصصة. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**لماذا نهيئ هنا؟** +إنشاء كائن `AsposeAI` مرة واحدة وإعادة استخدامه عبر صور متعددة يقلل من الحمل الزائد. كما يقوم المحرك بتخزين نماذج اللغة في الذاكرة المؤقتة، مما يسرّع الاستدعاءات اللاحقة—مفيد عند مسح دفعات من الإيصالات. + +--- + +## الخطوة 3: تسجيل دالة الإخفاء المخصصة + +يوفر AsposeAI طريقة `set_post_processor` التي تسمح لك بربط أي callable. نمرر دالة `mask_pci` الخاصة بنا مع قاموس إعدادات اختياري (حالياً فارغ). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**ماذا يحدث خلف الكواليس؟** +عند استدعاء `run_postprocessor` لاحقًا، سيقوم AsposeAI بتمرير نتيجة OCR الخام إلى `mask_pci`. تستقبل الدالة كائنًا خفيفًا (`data`) يحتوي على النص المعترف به، وتعيد سلسلة جديدة. يضمن هذا التصميم بقاء نواة OCR دون تعديل مع السماح لك بفرض سياسات **تنظيف البيانات** في مكان واحد. + +--- + +## الخطوة 4: تشغيل OCR على صورة الإيصال + +الآن بعد أن علم المحرك كيفية تنظيف المخرجات، نمرره صورة. من أجل هذا الدرس نفترض أنك تمتلك كائن `engine` مُعد مسبقًا بالإعدادات الصحيحة للغة والدقة. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**نصيحة:** إذا لم يكن لديك كائن مُعد مسبقًا، يمكنك إنشائه باستخدام: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +نداء `recognize_image` يُعيد كائنًا يحتوي على الخاصية `text` التي تحمل السلسلة الخام غير المخبأة. + +--- + +## الخطوة 5: تطبيق معالج ما بعد المسجل + +مع وجود بيانات OCR الخام، نمررها إلى كائن AI. يقوم المحرك تلقائيًا بتنفيذ الدالة `mask_pci` التي سجلناها مسبقًا. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**لماذا نستخدم `run_postprocessor` بدلاً من استدعاء الدالة يدويًا؟** +يساعد ذلك في الحفاظ على تناسق سير العمل، خاصةً عندما يكون لديك عدة معالجات ما بعد (مثل التدقيق الإملائي، اكتشاف اللغة). يقوم AsposeAI بترتيبها وفقًا لتسجيلك، مما يضمن مخرجات حتمية. + +--- + +## الخطوة 6: التحقق من المخرجات المنقاة + +أخيرًا، لنطبع النص المنقّى ونؤكد أن أي أرقام بطاقات ائتمان تم إخفاؤها بشكل صحيح. + +```python +print(final_result.text) +``` + +**المخرجات المتوقعة** (مقتطف): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +إذا لم يحتوي الإيصال على رقم بطاقة، يبقى النص دون تغيير—لا شيء لإخفائه، ولا داعي للقلق. + +--- + +## معالجة الحالات الخاصة والاختلافات الشائعة + +### عدة أرقام بطاقات في مستند واحد +إذا كان الإيصال يحتوي على أكثر من PAN (مثلاً بطاقة ولاء بالإضافة إلى بطاقة دفع)، يعمل التعبير النمطي عالميًا، ويخفي جميع التطابقات تلقائيًا. لا حاجة إلى كود إضافي. + +### تنسيق غير قياسي +أحيانًا يضيف OCR مسافات أو شرطات (`1234 5678 1234 5678` أو `1234-5678-1234-5678`). قم بتوسيع النمط لتجاهل تلك الأحرف: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +الإضافة `[ -]?` تسمح بوجود مسافات أو شرطات اختيارية بين مجموعات الأرقام. + +### بطاقات دولية +لـ PAN بطول 19 رقمًا المستخدمة في بعض المناطق، يمكنك توسيع النمط: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +تذكر فقط أن **PCI compliance** لا يزال يتطلب إخفاء الأرقام الوسطى، بغض النظر عن الطول. + +### تسجيل القيم المخفية (اختياري) +إذا كنت بحاجة إلى سجلات تدقيق، مرّر علمًا عبر `custom_settings` وعدّل الدالة: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +ثم سجّل باستخدام: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## مثال كامل جاهز للنسخ واللصق + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +تشغيل هذا السكريبت على إيصال يحتوي على `4111111111111111` سيُنتج: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +هذا هو سير العمل الكامل—من OCR الخام إلى **تنظيف البيانات**—مُغلف ببضع أسطر نظيفة من بايثون. + +--- + +## الخلاصة + +لقد أظهرنا لك الآن كيفية **إخفاء أرقام بطاقات الائتمان** في نتائج OCR باستخدام post‑processing hook الخاص بـ AsposeAI، روتين تعبير نمطي مختصر، ومجموعة من النصائح العملية للـ **PCI compliance**. الحل مستقل تمامًا، يعمل مع أي صورة يستطيع محرك OCR قراءتها، ويمكن توسيعه لتغطية صيغ بطاقات أكثر تعقيدًا أو متطلبات التسجيل. + +هل أنت مستعد للخطوة التالية؟ جرّب ربط هذا الإخفاء مع دالة **إدخال قاعدة بيانات** تخزن الأربعة أرقام الأخيرة فقط للمرجعية، أو دمج **معالج دفعات** يمسح مجلدًا كاملاً من الإيصالات طوال الليل. يمكنك أيضًا استكشاف مهام **معالجة ما بعد OCR** أخرى مثل توحيد العناوين أو اكتشاف اللغة—كل منها يتبع نفس النمط الذي استخدمناه هنا. + +هل لديك أسئلة حول الحالات الخاصة، الأداء، أو كيفية تعديل الكود لمكتبة OCR مختلفة؟ اترك تعليقًا أدناه، ولنستمر في النقاش. برمجة سعيدة، وابق آمنًا! + +![Diagram illustrating how mask credit card numbers works in an OCR pipeline](https://example.com/images/ocr-mask-flow.png "Diagram of OCR post‑processing masking flow") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/arabic/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..2cf89a456 --- /dev/null +++ b/ocr/arabic/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-04-26 +description: تعلم كيفية قياس زمن الاستدلال في بايثون، وتحميل نموذج GGUF من Hugging + Face، وتحسين استخدام وحدة معالجة الرسومات للحصول على نتائج أسرع. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: ar +og_description: قِس زمن الاستدلال في بايثون بتحميل نموذج GGUF من Hugging Face وضبط + طبقات GPU لتحقيق الأداء الأمثل. +og_title: قياس زمن الاستدلال – تحميل نموذج GGUF وتحسين وحدة معالجة الرسومات +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: قياس زمن الاستدلال – تحميل نموذج GGUF وتحسين وحدة معالجة الرسومات +url: /ar/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# قياس زمن الاستدلال – تحميل نموذج GGUF وتحسين GPU + +هل احتجت يومًا إلى **قياس زمن الاستدلال** لنموذج لغة كبير لكن لم تعرف من أين تبدأ؟ لست وحدك—العديد من المطورين يواجهون نفس المشكلة عندما يقومون أول مرة بسحب ملف GGUF من Hugging Face ويحاولون تشغيله على إعداد مختلط CPU/GPU. + +في هذا الدليل سنستعرض **كيفية تحميل نموذج GGUF**، وضبطه لـ Hugging Face، و**قياس زمن الاستدلال** باستخدام مقتطف Python بسيط. سنوضح أيضًا كيفية **تحسين استدلال GPU** لتكون عملياتك سريعة قدر الإمكان. لا إطالة، مجرد حل عملي من البداية إلى النهاية يمكنك نسخه ولصقه اليوم. + +## ما ستتعلمه + +- كيفية **تهيئة نموذج HuggingFace** باستخدام `AsposeAIModelConfig`. +- الخطوات الدقيقة **لتحميل نموذج GGUF** (بتكميم `fp16`) من مستودع Hugging Face. +- نمط قابل لإعادة الاستخدام **لتوقيت كود Python** حول استدعاء الاستدلال. +- نصائح **لتحسين استدلال GPU** عن طريق تعديل `gpu_layers`. +- النتيجة المتوقعة وكيفية التحقق من صحة التوقيت. + +### المتطلبات المسبقة + +| المتطلب | لماذا يهم | +|-------------|----------------| +| Python 3.9+ | صsyntax حديث وتلميحات نوع. | +| حزمة `asposeai` (أو SDK المكافئ) | توفر `AsposeAI` و `AsposeAIModelConfig`. | +| الوصول إلى مستودع Hugging Face `bartowski/Qwen2.5-3B-Instruct-GGUF` | نموذج GGUF الذي سنحمّله. | +| GPU بسعة ذاكرة VRAM لا تقل عن 8 GB (اختياري لكن يُنصح به) | يتيح خطوة **تحسين استدلال GPU**. | + +إذا لم تقم بتثبيت SDK بعد، نفّذ: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![measure inference time diagram](https://example.com/measure-inference-time.png){alt="مخطط قياس زمن الاستدلال"} + +## الخطوة 1: تحميل نموذج GGUF – تهيئة نموذج HuggingFace + +أول شيء تحتاجه هو كائن تهيئة صحيح يخبر Aspose AI من أين يجلب النموذج وكيف يتعامل معه. هنا نقوم **بتحميل نموذج GGUF** و**تهيئة معلمات نموذج huggingface**. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**لماذا هذا مهم:** +- `hugging_face_repo_id` يشير إلى ملف GGUF المحدد على Hub. +- `fp16` يقلل من عرض نطاق الذاكرة مع الحفاظ على معظم دقة النموذج. +- `gpu_layers` هو المفتاح الذي تضبطه عندما تريد **تحسين استدلال GPU**؛ المزيد من الطبقات على الـ GPU عادةً ما يعني زمن استجابة أسرع، بشرط توفر ذاكرة كافية. + +## الخطوة 2: إنشاء كائن Aspose AI + +بعد وصف النموذج، نقوم بإنشاء كائن `AsposeAI`. هذه الخطوة بسيطة، لكنها حيث يقوم SDK فعليًا بتحميل ملف GGUF (إذا لم يكن مخزنًا مؤقتًا) وتحضير بيئة التشغيل. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**نصيحة احترافية:** التشغيل الأول سيستغرق بضع ثوانٍ إضافية لأن النموذج يتم تحميله وتجميعه للـ GPU. التشغيلات اللاحقة ستكون سريعة كالبرق. + +## الخطوة 3: تشغيل الاستدلال و**قياس زمن الاستدلال** + +هذا هو جوهر الدرس: تغليف استدعاء الاستدلال بـ `time.time()` ل**قياس زمن الاستدلال**. نُدخل أيضًا نتيجة OCR صغيرة لتكون العينة مكتفية ذاتيًا. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**ما يجب أن تراه:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +إذا كان الرقم مرتفعًا، فربما تكون معظم الطبقات تعمل على الـ CPU. هذا يقودنا إلى الخطوة التالية. + +## الخطوة 4: **تحسين استدلال GPU** – ضبط `gpu_layers` + +أحيانًا يكون الإعداد الافتراضي `gpu_layers=40` إما مفرطًا (مسببًا OOM) أو متحفظًا جدًا (مُهدرًا للأداء). إليك حلقة سريعة يمكنك استخدامها للعثور على النقطة المثالية: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**لماذا يعمل هذا:** +- كل استدعاء يعيد بناء بيئة التشغيل بتخصيص GPU مختلف، مما يتيح لك رؤية فرق الزمن فورًا. +- الحلقة تُظهر أيضًا **time python code** بطريقة قابلة لإعادة الاستخدام، يمكنك تعديلها لاختبارات أداء أخرى. + +الناتج النموذجي على RTX 3080 بسعة 16 GB قد يبدو هكذا: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +من ذلك، ستختار `gpu_layers=40` كنقطة مثالية لهذا العتاد. + +## مثال كامل يعمل + +بجمع كل ما سبق، إليك سكريبت واحد يمكنك وضعه في ملف (`measure_inference.py`) وتشغيله: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +شغّله باستخدام: + +```bash +python measure_inference.py +``` + +ستلاحظ زمن استجابة أقل من ثانية على GPU جيد، مما يؤكد أنك نجحت في **قياس زمن الاستدلال** و**تحسين استدلال GPU**. + +--- + +## الأسئلة المتكررة (FAQs) + +**س: هل يعمل هذا مع صيغ تكميم أخرى؟** +ج: بالتأكيد. استبدل `hugging_face_quantization="int8"` (أو `q4_0`، إلخ) في التهيئة وأعد تشغيل الاختبار. توقع تبادل بين استهلاك الذاكرة ودقة طفيفة. + +**س: ماذا لو لم يكن لدي GPU؟** +ج: اضبط `gpu_layers=0`. سيعود الكود بالكامل إلى الـ CPU، وستظل قادرًا على **قياس زمن الاستدلال**—لكن توقع أرقام أعلى. + +**س: هل يمكن توقيت جزء النموذج فقط، مستثنيًا ما بعد المعالجة؟** +ج: نعم. استدعِ `ai_engine.run_model(...)` (أو الطريقة المكافئة) مباشرةً ولفّ ذلك الاستدعاء بـ `time.time()`. نمط **time python code** يبقى كما هو. + +--- + +## الخلاصة + +أصبح لديك الآن حل كامل قابل للنسخ واللصق **لقياس زمن الاستدلال** لنموذج GGUF، **تحميل نموذج gguf** من Hugging Face، وضبط إعدادات **تحسين استدلال GPU**. عبر تعديل `gpu_layers` وتجربة صيغ التكميم، يمكنك استخراج كل ملي ثانية من الأداء. + +الخطوات التالية قد تشمل: + +- دمج منطق التوقيت هذا في خط أنابيب CI للكشف عن الانحدارات. +- استكشاف الاستدلال على دفعات لتحسين الإنتاجية. +- ربط النموذج بخط أنابيب OCR حقيقي بدلاً من النص الوهمي المستخدم هنا. + +برمجة سعيدة، ولتظل أرقام latency منخفضة دائمًا! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/arabic/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..47ee8c21c --- /dev/null +++ b/ocr/arabic/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-26 +description: التعرف على النص المكتوب بخط اليد باستخدام محرك OCR في بايثون. تعلم كيفية + استخراج النص من الصورة، وتفعيل وضع الخط اليدوي، وقراءة الملاحظات المكتوبة بخط اليد + بسرعة. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: ar +og_description: التعرف على النص المكتوب بخط اليد باستخدام بايثون. يوضح هذا الدرس كيفية + استخراج النص من الصورة، وتفعيل وضع الخط اليدوي، وقراءة الملاحظات المكتوبة بخط اليد + باستخدام محرك OCR بسيط. +og_title: التعرف على النص المكتوب بخط اليد في بايثون – دليل OCR الكامل +tags: +- OCR +- Python +- Handwriting Recognition +title: التعرف على النص المكتوب بخط اليد في بايثون – دليل محرك OCR +url: /ar/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# التعرف على النص المكتوب بخط اليد في بايثون – دليل محرك OCR + +هل احتجت يومًا إلى **التعرف على النص المكتوب بخط اليد** لكن شعرت بالحيرة عند سؤال “من أين أبدأ؟”؟ لست وحدك. سواءً كنت تقوم برقمنة ملاحظات الاجتماعات أو استخراج البيانات من نموذج ممسوح ضوئيًا، فإن الحصول على نتيجة OCR موثوقة قد يبدو كمطاردة وحيد القرن. + +خبر سار: ببضع أسطر فقط من بايثون يمكنك **استخراج النص من صورة**، **تفعيل وضع الخط اليدوي**، وأخيرًا **قراءة الملاحظات المكتوبة بخط اليد** دون الحاجة للبحث عن مكتبات غامضة. في هذا الدليل سنستعرض العملية بالكامل، من إعداد على نمط **create OCR engine python** إلى طباعة النتيجة على الشاشة. + +## ما ستتعلمه + +- كيفية إنشاء مثيل **create OCR engine python** باستخدام حزمة `ocr`. +- أي إعداد لغة يوفّر لك دعمًا مدمجًا للخط اليدوي. +- النداء الدقيق لتفعيل **turn on handwritten mode** حتى يعرف المحرك أنك تتعامل مع الخط المتصل. +- كيفية إمداد صورة ملاحظة و**التعرف على النص المكتوب بخط اليد** منها. +- نصائح للتعامل مع صيغ الصور المختلفة، استكشاف الأخطاء الشائعة، وتوسيع الحل. + +بدون إطالة، دون “انظر إلى الوثائق” المميتة—فقط سكريبت كامل قابل للتنفيذ يمكنك نسخه ولصقه واختباره اليوم. + +## المتطلبات المسبقة + +قبل أن نبدأ، تأكد من أن لديك: + +1. Python 3.8+ مثبت (الكود يستخدم f‑strings). +2. مكتبة `ocr` الافتراضية (`pip install ocr‑engine` – استبدلها باسم الحزمة الفعلية التي تستخدمها). +3. ملف صورة واضح لملاحظة مكتوبة بخط اليد (JPEG، PNG، أو TIFF). +4. قليل من الفضول—كل ما تبقى مغطى أدناه. + +> **نصيحة احترافية:** إذا كانت صورتك مشوشة، قم بخطوة تمهيد سريعة باستخدام Pillow (مثال: `Image.open(...).convert('L')`) قبل إرسالها إلى محرك OCR. غالبًا ما يحسن ذلك الدقة. + +## كيفية التعرف على النص المكتوب بخط اليد باستخدام بايثون + +فيما يلي السكريبت الكامل الذي **creates OCR engine python** كائنات، يضبطها للخط اليدوي، ويطبع السلسلة المستخرجة. احفظه باسم `handwriting_ocr.py` وشغّله من الطرفية. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### النتيجة المتوقعة + +عند تشغيل السكريبت بنجاح، سترى شيئًا مشابهًا لـ: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +إذا لم يتمكن محرك OCR من اكتشاف أي أحرف، سيكون حقل `text` سلسلة فارغة. في هذه الحالة، تحقق مرة أخرى من جودة الصورة أو جرّب مسحًا بدقة أعلى. + +## شرح خطوة بخطوة + +### الخطوة 1 – مثيل **create OCR engine python** + +فئة `OcrEngine` هي نقطة الدخول. فكر فيها كدفتر ملاحظات فارغ—لا يحدث شيء حتى تخبره بأي لغة تتوقعها وما إذا كنت تتعامل مع الخط اليدوي. + +### الخطوة 2 – اختر لغة تدعم الخط اليدوي + +`ocr.Language.EXTENDED_LATIN` ليست مجرد “إنجليزية”. إنها تجمع مجموعة من الخطوط المستندة إلى اللاتينية، وتضم نماذج مدربة على عينات من الخط المتصل. تخطي هذه الخطوة غالبًا ما يؤدي إلى مخرجات مشوشة لأن المحرك ي default إلى نموذج النص المطبوع. + +### الخطوة 3 – **turn on handwritten mode** + +استدعاء `enable_handwritten_mode(True)` يغيّر علامة داخلية. ثم يتحول المحرك إلى شبكته العصبية التي تم ضبطها للتباعد غير المنتظم وعرض الضربات المتغيرة التي تراها في ملاحظات العالم الحقيقي. نسيان هذا السطر خطأ شائع؛ سيتعامل المحرك مع خربشاتك كضوضاء. + +### الخطوة 4 – قدم الصورة و**recognize handwritten text** + +`recognize_image` يقوم بالعمل الشاق: يسبق معالجة البت ماب، يمرره عبر نموذج الخط اليدوي، ويعيد كائنًا يحتوي على الخاصية `text`. يمكنك أيضًا فحص `handwritten_result.confidence` إذا كنت بحاجة إلى مقياس جودة. + +### الخطوة 5 – اطبع النتيجة و**read handwritten notes** + +`print(handwritten_result.text)` هو أبسط طريقة للتحقق من أنك نجحت في **extract text from image**. في بيئة الإنتاج ربما تخزن السلسلة في قاعدة بيانات أو تمررها إلى خدمة أخرى. + +## معالجة الحالات الحدية والاختلافات الشائعة + +| الحالة | ما الذي يجب فعله | +|-----------|------------| +| **الصورة مائلة** | استخدم Pillow لتدوير الصورة (`Image.rotate(angle)`) قبل استدعاء `recognize_image`. | +| **تباين منخفض** | حوّل إلى تدرج الرمادي وطبق العتبة التكيفية (`Image.point(lambda p: p > 128 and 255)`). | +| **صفحات متعددة** | تكرار عبر قائمة مسارات الملفات وربط النتائج. | +| **خطوط غير لاتينية** | استبدل `EXTENDED_LATIN` بـ `ocr.Language.CHINESE` (أو ما يناسب) واحتفظ بـ `enable_handwritten_mode(True)`. | +| **مخاوف الأداء** | أعد استخدام نفس مثيل `ocr_engine` عبر العديد من الصور؛ تهيئته في كل مرة يضيف عبئًا. | + +### نصيحة احترافية حول استهلاك الذاكرة + +إذا كنت تعالج مئات الملاحظات دفعة واحدة، استدعِ `ocr_engine.dispose()` بعد الانتهاء. يحرّر ذلك الموارد الأصلية التي قد يحتفظ بها غلاف بايثون. + +## ملخص بصري سريع + +![مثال على التعرف على النص المكتوب بخط اليد](https://example.com/handwritten-note.png "مثال على التعرف على النص المكتوب بخط اليد") + +*الصورة أعلاه تُظهر ملاحظة مكتوبة بخط اليد نموذجية يمكن لسكريبتنا تحويلها إلى نص عادي.* + +## مثال كامل يعمل (سكريبت ملف واحد) + +لمن يحب بساطة النسخ‑اللصق، إليكم كل شيء مرة أخرى دون التعليقات التوضيحية: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +شغّله باستخدام: + +```bash +python handwriting_ocr.py +``` + +يجب الآن أن ترى ناتج **recognize handwritten text** في وحدة التحكم. + +## الخلاصة + +لقد غطينا الآن كل ما تحتاجه لـ **recognize handwritten text** في بايثون—بدءًا من استدعاء **create OCR engine python** جديد، اختيار اللغة المناسبة، **turn on handwritten mode**، وأخيرًا **extract text from image** إلى **read handwritten notes**. + +في سكريبت واحد مستقل يمكنك الانتقال من صورة ضبابية لرسمة اجتماع إلى نص نظيف قابل للبحث. بعد ذلك، فكر في إمداد الناتج إلى خط أنابيب للغة الطبيعية، تخزينه في فهرس قابل للبحث، أو حتى إعادته إلى خدمة تفريغ لتوليد التعليق الصوتي. + +### إلى أين تتجه من هنا؟ + +- **معالجة دفعات:** غلف السكريبت في حلقة للتعامل مع مجلد من المسحات. +- **تصفية الثقة:** استخدم `result.confidence` لتجاهل القراءات منخفضة الجودة. +- **مكتبات بديلة:** إذا لم يكن `ocr` مناسبًا تمامًا، استكشف `pytesseract` مع `--psm 13` لوضع الخط اليدوي. +- **دمج واجهة المستخدم:** اجمع مع Flask أو FastAPI لتقديم خدمة رفع عبر الويب. + +هل لديك أسئلة حول صيغة صورة معينة أو تحتاج مساعدة في ضبط النموذج؟ اترك تعليقًا أدناه، وبرمجة سعيدة! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/chinese/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..176d8f936 --- /dev/null +++ b/ocr/chinese/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-04-26 +description: 学习如何使用 Python 下载 HuggingFace 模型、使用 Python 从图像中提取文本,并通过 Aspose OCR Cloud + 提升 OCR 准确率。 +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: zh +og_description: 下载 huggingface 模型 Python 并提升您的 OCR 流程。按照本指南使用 Python 从图像中提取文本并提高 OCR + 准确率。 +og_title: 下载 HuggingFace 模型 Python – 完整的 OCR 增强教程 +tags: +- OCR +- HuggingFace +- Python +- AI +title: 下载 HuggingFace 模型(Python)——一步步 OCR 提升指南 +url: /zh/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – 完整 OCR 增强教程 + +有没有尝试过 **download HuggingFace model python**,却感到有点迷茫?你并不是唯一的。 在许多项目中,最大的瓶颈是把一个好的模型下载到本地机器上,然后让 OCR 结果真正有用。 + +在本指南中,我们将通过一个动手示例,完整展示如何 **download HuggingFace model python**,使用 **extract text from image python** 从图片中提取文字,并通过 Aspose 的 AI 后处理器 **improve OCR accuracy python**。完成后,你将拥有一个可直接运行的脚本,能够将噪声较大的发票图片转换为干净、可读的文本——没有魔法,只有清晰的步骤。 + +## 您需要的条件 + +- Python 3.9+(代码在 3.11 上同样可用) +- 用于一次性模型下载的网络连接 +- `asposeocrcloud` 包(`pip install asposeocrcloud`) +- 放置在你可控制文件夹中的示例图片(例如 `sample_invoice.png`) + +就这些——无需重量级框架,也不需要 GPU 专用驱动,除非你想加速处理。 + +现在,让我们深入实际实现。 + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## 第一步:设置 OCR 引擎并选择语言 +*(这里我们开始 **extract text from image python**。)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**为什么这很重要:** +OCR 引擎是第一道防线;选择正确的语言包可以立即减少字符识别错误,这也是 **improve OCR accuracy python** 的核心部分。 + +## 第二步:配置 AsposeAI 模型 – 从 HuggingFace 下载 +*(这里我们实际执行 **download HuggingFace model python**。)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**What’s happening under the hood?** +当 `allow_auto_download` 为 true 时,SDK 会访问 HuggingFace,获取 `Qwen2.5‑3B‑Instruct‑GGUF` 模型,并将其存储在你指定的文件夹中。这就是 **download huggingface model python** 的核心——SDK 负责繁重的下载工作,你无需自己编写 `git clone` 或 `wget` 命令。 + +*Pro tip:* 将 `directory_model_path` 放在 SSD 上以获得更快的加载时间;即使是 `int8` 形式,模型也约为 3 GB。 + +## 第三步:将 AI 引擎绑定到 OCR 引擎 +*(将两部分链接起来,以便我们可以 **improve OCR accuracy python**。)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Why bind them?** +OCR 引擎提供原始文本,可能包含拼写错误、断行或错误的标点。AI 引擎充当智能编辑器,清理这些问题——正是你需要的 **improve OCR accuracy python**。 + +## 第四步:在图像上运行 OCR +*(这就是我们最终 **extract text from image python** 的时刻。)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` 现在包含一个 `text` 属性,保存引擎看到的原始字符。实际使用时你会注意到一些小问题——比如 “Invoice” 被识别为 “Inv0ice”,或句子中间出现换行。 + +## 第五步:使用 AI 后处理器进行清理 +*(此步骤直接 **improve OCR accuracy python**。)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +AI 模型会重新写入文本,应用语言感知的修正。由于我们使用了来自 HuggingFace 的指令微调模型,输出通常流畅且可直接用于下游处理。 + +## 第六步:展示前后对比 +*(快速检查我们 **extract text from image python** 和 **improve OCR accuracy python** 的效果。)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### 预期输出 + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +请注意,AI 将 “Inv0ice” 修正为 “Invoice”,并平滑了零散的换行。这就是使用下载的 HuggingFace 模型 **improve OCR accuracy python** 的直观结果。 + +## 常见问题 (FAQ) + +### 我需要 GPU 来运行模型吗? +不需要。`gpu_layers=20` 设置表示如果检测到兼容的 GPU,SDK 将使用最多 20 层 GPU 加速;否则会回退到 CPU。在现代笔记本电脑上,CPU 仍能每秒处理数百个 token,足以应付偶尔的发票解析。 + +### 如果模型下载失败怎么办? +确保你的环境能够访问 `https://huggingface.co`。如果在公司代理后面,设置 `HTTP_PROXY` 和 `HTTPS_PROXY` 环境变量。SDK 会自动重试,你也可以手动 `git lfs pull` 将仓库拉取到 `directory_model_path`。 + +### 我可以换成更小的模型吗? +完全可以。只需将 `hugging_face_repo_id` 替换为其他仓库(例如 `TinyLlama/TinyLlama-1.1B-Chat-v0.1`),并相应调整 `hugging_face_quantization`。更小的模型下载更快、占用更少内存,但可能会略微降低纠错质量。 + +### 这如何帮助我在其他领域 **extract text from image python**? +相同的流水线同样适用于收据、护照或手写笔记。唯一需要更改的是语言包(如 `ocr.Language.FRENCH` 等)以及可能的领域特定微调模型。 + +## 额外内容:自动化处理多个文件 + +如果你有一个装满图片的文件夹,可以将 OCR 调用包装在一个简单的循环中: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +这个小改动让你只需 **download huggingface model python** 一次,即可批量处理数十个文件——非常适合扩展文档自动化流水线。 + +## 结论 + +我们刚刚完整演示了一个端到端的示例,展示了如何 **download HuggingFace model python**、**extract text from image python**,以及使用 Aspose OCR Cloud 和 AI 后处理器 **improve OCR accuracy python**。脚本已准备好运行,概念已解释清楚,你也看到了前后对比的输出,证明它可行。 + +接下来可以尝试换用其他 HuggingFace 模型,实验不同的语言包,或将清理后的文本输送到下游 NLP 流程(例如发票行项目的实体抽取)。可能性无限,而你刚搭建的基础已经相当稳固。 + +有问题或遇到仍然让 OCR 卡顿的难题图片?在下方留言,我们一起排查。祝编码愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/chinese/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..22bd383bd --- /dev/null +++ b/ocr/chinese/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-04-26 +description: 使用 Aspose OCR Python 快速下载 OCR 模型。了解如何设置模型目录、配置模型路径,以及如何在几行代码中下载模型。 +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: zh +og_description: 使用 Aspose OCR Python 在几秒钟内下载 OCR 模型。本指南展示了如何设置模型目录、配置模型路径以及安全下载模型。 +og_title: 下载 OCR 模型 – 完整的 Aspose OCR Python 教程 +tags: +- OCR +- Python +- Aspose +title: 使用 Aspose OCR Python 下载 OCR 模型 – 步骤指南 +url: /zh/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – 完整的 Aspose OCR Python 教程 + +有没有想过如何在 Python 中使用 Aspose OCR **download ocr model** 而不必在无尽的文档中搜索?你并不是唯一的。许多开发者在模型本地不存在且 SDK 抛出神秘错误时卡住了。好消息是?只需几行代码,几分钟内即可准备好模型。 + +在本教程中,我们将逐步讲解您需要了解的所有内容:从导入正确的类,到 **set model directory**,再到实际的 **how to download model**,最后验证路径。完成后,您将能够只用一次函数调用对任何图像进行 OCR,并且了解保持项目整洁的 **configure model path** 选项。没有冗余,只提供适用于 **aspose ocr python** 用户的实用可运行示例。 + +## 您将学习的内容 + +- 如何正确导入 Aspose OCR Cloud 类。 +- 自动 **download ocr model** 的确切步骤。 +- **set model directory** 与 **configure model path** 的使用方法,以实现可复现的构建。 +- 如何验证模型是否已初始化以及它在磁盘上的位置。 +- 常见陷阱(权限、缺失目录)及快速解决方案。 + +### 前置条件 + +- 已在机器上安装 Python 3.8+。 +- `asposeocrcloud` 包(`pip install asposeocrcloud`)。 +- 对存放模型的文件夹具有写入权限(例如 `C:\models` 或 `~/ocr_models`)。 + +--- + +## 步骤 1:导入 Aspose OCR Cloud 类 + +您首先需要的是正确的导入语句。这会引入管理模型配置和 OCR 操作的类。 + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Why this matters:* `AsposeAI` 是运行 OCR 的引擎,而 `AsposeAIModelConfig` 告诉引擎 **where** 查找模型以及 **whether** 自动获取模型。跳过此步骤或导入错误的模块会在下载之前抛出 `ModuleNotFoundError`。 + +--- + +## 步骤 2:定义模型配置(Set Model Directory 与 Configure Model Path) + +现在我们告诉 Aspose 将模型文件保存在哪里。这就是您 **set model directory** 和 **configure model path** 的位置。 + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**提示与注意事项** + +- **Absolute paths** 可避免脚本在不同工作目录下运行时产生混淆。 +- 在 Linux/macOS 上可以使用 `"/home/you/ocr_models"`;在 Windows 上,前缀 `r` 可让反斜杠按字面含义解析。 +- 将 `allow_auto_download="true"` 设置为关键,以实现 **how to download model** 而无需额外代码。 + +--- + +## 步骤 3:使用配置创建 AsposeAI 实例 + +配置准备好后,实例化 OCR 引擎。 + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Why this matters:* `ocr_ai` 对象现在持有我们刚定义的配置。如果模型不存在,下一次调用将自动触发下载——这正是 **how to download model** 的核心,无需手动干预。 + +--- + +## 步骤 4:触发模型下载(如有需要) + +在运行 OCR 之前,需要确保模型已经在磁盘上。`is_initialized()` 方法既检查又强制初始化。 + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**What happens under the hood?** + +- 第一次调用 `is_initialized()` 返回 `False`,因为模型文件夹为空。 +- `print` 提示用户下载即将开始。 +- 第二次调用强制 Aspose 从您之前指定的 Hugging Face 仓库获取模型。 +- 下载完成后,后续检查将返回 `True`。 + +**Edge case:** 如果网络阻止访问 Hugging Face,您会看到异常。此时,请手动下载模型 zip,解压到 `directory_model_path`,然后重新运行脚本。 + +--- + +## 步骤 5:报告模型当前所在的本地路径 + +下载完成后,您可能想知道文件落在了哪里。这有助于调试和 CI 流水线的设置。 + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +典型输出如下: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +现在您已经成功 **download ocr model**,设置了目录,并确认了路径。 + +--- + +## 可视化概览 + +下面是一张简易图示,展示了从配置到可直接使用的模型的流程。 + +![download ocr model flow diagram showing configuration, automatic download, and local path](/images/download-ocr-model-flow.png) + +*Alt 文本包含主要的 SEO 关键字。* + +--- + +## 常见变体及处理方法 + +### 1. 使用不同的模型仓库 + +如果需要的模型不是 `openai/gpt2`,只需替换 `hugging_face_repo_id` 的值: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +确保仓库是公开的,或已在环境中设置必要的 token。 + +### 2. 禁用自动下载 + +有时您希望自行控制下载(例如在 air‑gapped 环境中)。将 `allow_auto_download` 设置为 `"false"`,并在初始化前调用自定义下载脚本: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. 运行时更改模型目录 + +无需重新创建 `AsposeAI` 对象,即可重新配置路径: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## 生产使用的专业提示 + +- **Cache the model**:如果多个服务需要相同模型,可将目录放在共享网络驱动器上,避免重复下载。 +- **Version pinning**:Hugging Face 仓库可能会更新。要锁定特定版本,可在仓库 ID 后追加 `@v1.0.0`(`"openai/gpt2@v1.0.0"`)。 +- **Permissions**:确保运行脚本的用户对 `directory_model_path` 具有读写权限。Linux 上通常使用 `chmod 755` 即可。 +- **Logging**:将简单的 `print` 替换为 Python 的 `logging` 模块,以在大型应用中获得更好的可观测性。 + +--- + +## 完整可运行示例(复制‑粘贴即可) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Expected output**(首次运行会下载,后续运行会跳过下载): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +再次运行脚本;您只会看到路径行,因为模型已经被缓存。 + +--- + +## 结论 + +我们刚刚完整演示了使用 Aspose OCR Python **download ocr model** 的全过程,展示了如何 **set model directory**,并解释了 **configure model path** 的细微差别。只需几行代码即可自动化下载,省去手动步骤,并保持 OCR 流水线的可复现性。 + +接下来,您可能想探索实际的 OCR 调用(`ocr_ai.recognize_image(...)`)或尝试不同的 Hugging Face 模型以提升准确率。无论哪种方式,您在此构建的基础——清晰的配置、自动下载以及路径验证——都将使未来的任何集成轻而易举。 + +有关于边缘情况的疑问,或想分享您在云部署中如何调整模型目录的经验?在下方留言吧,祝编码愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/chinese/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..381571b59 --- /dev/null +++ b/ocr/chinese/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-04-26 +description: 如何后处理 OCR 结果并提取带坐标的文本。学习使用结构化输出和 AI 校正的分步解决方案。 +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: zh +og_description: 如何对 OCR 结果进行后处理并提取带坐标的文本。请遵循本全面教程,以获得可靠的工作流程。 +og_title: 如何后处理 OCR — 完整指南 +tags: +- OCR +- Python +- AI +- Text Extraction +title: 如何后处理 OCR —— 在 Python 中提取带坐标的文本 +url: /zh/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何后处理 OCR – 在 Python 中提取带坐标的文本 + +是否曾经需要**后处理 OCR**结果,因为原始输出噪声大或对齐不准确?你并不孤单。在许多真实项目中——发票扫描、收据数字化,甚至增强现实体验的增强——OCR 引擎会给出原始单词,但你仍需清理它们并记录每个单词在页面上的位置。这时结构化输出模式结合 AI 驱动的后处理器就显得尤为重要。 + +在本教程中,我们将演示一个完整、可直接运行的 Python 流程,**从图像中提取带坐标的文本**,执行基于 AI 的纠正步骤,并打印每个单词及其 (x, y) 位置。没有缺失的导入,没有模糊的“参考文档”快捷方式——只是一套可以直接放入项目的自包含解决方案。 + +> **专业提示:** 如果你使用的是其他 OCR 库,请寻找“structured”或“layout”模式;概念是相同的。 + +--- + +## 前置条件 + +在开始之前,请确保你具备以下条件: + +| 要求 | 为什么重要 | +|------|------------| +| Python 3.9+ | 现代语法和类型提示 | +| 支持 `OutputMode.STRUCTURED` 的 `ocr` 库(例如虚构的 `myocr`) | 用于获取边界框数据 | +| AI 后处理模块(可以是 OpenAI、HuggingFace 或自定义模型) | 在 OCR 之后提升准确性 | +| 工作目录下的图像文件(`input.png`) | 我们将读取的源文件 | + +如果这些听起来陌生,只需使用 `pip install myocr ai‑postproc` 安装占位包。下面的代码还包含了回退存根,方便在没有真实库的情况下测试流程。 + +--- + +## 步骤 1:为 OCR 引擎启用结构化输出模式 + +首先,我们告诉 OCR 引擎返回的不仅仅是纯文本。结构化输出会为每个单词返回其边界框和置信度,这对后续的**提取带坐标的文本**至关重要。 + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*为什么重要:* 如果不使用结构化模式,你只能得到一长串字符串,空间位置信息会丢失,无法在图像上叠加文本或进行后续布局分析。 + +--- + +## 步骤 2:识别图像并捕获单词、框体和置信度 + +接下来将图像送入引擎。返回的对象包含一个单词对象列表,每个对象提供 `text`、`x`、`y`、`width`、`height` 和 `confidence`。 + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*边缘情况:* 如果图像为空或无法读取,`structured_result.words` 将是空列表。最好检查并优雅地处理这种情况。 + +--- + +## 步骤 3:在保留位置信息的同时运行基于 AI 的后处理 + +即使是最好的 OCR 引擎也会出错——比如 “O” 与 “0” 的混淆或缺失变音符。针对特定领域文本训练的 AI 模型可以纠正这些错误。关键是我们保留原始坐标,使空间布局保持完整。 + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*为什么要保留坐标:* 许多下游任务(例如 PDF 生成、AR 标注)依赖精确的放置。AI 只会修改 `text` 字段,`x`、`y`、`width`、`height` 保持不变。 + +--- + +## 步骤 4:遍历纠正后的单词并显示其文本与坐标 + +最后,我们遍历纠正后的单词,并打印每个单词及其左上角 `(x, y)`。这正好实现了**提取带坐标的文本**的目标。 + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**预期输出(示例):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +每行显示纠正后的单词及其在原始图像上的精确位置。 + +--- + +## 完整可运行示例 + +下面是一段把所有步骤串联起来的脚本。复制粘贴后,根据实际使用的库调整导入语句,即可直接运行。 + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**运行脚本** + +```bash +python ocr_postprocess_demo.py +``` + +如果已安装真实库,脚本会处理你的 `input.png`。否则,存根实现让你在没有外部依赖的情况下看到预期的流程和输出。 + +--- + +## 常见问题 (FAQ) + +| 问题 | 回答 | +|------|------| +| *这能与 Tesseract 配合使用吗?* | Tesseract 本身没有直接的结构化模式,但像 `pytesseract.image_to_data` 这样的包装器会返回边界框,你可以将其喂入相同的 AI 后处理器。 | +| *如果我需要右下角坐标而不是左上角怎么办?* | 每个单词对象同样提供 `width` 和 `height`。计算 `x2 = x + width`、`y2 = y + height` 即可得到对角坐标。 | +| *我可以批量处理多张图像吗?* | 当然。将步骤包装在 `for image_path in Path("folder").glob("*.png"):` 循环中,并为每个文件收集结果。 | +| *如何选择用于纠正的 AI 模型?* | 对于通用文本,使用在 OCR 错误上微调的轻量级 GPT‑2 即可。对于特定领域(如医疗处方),在噪声‑干净配对数据上训练序列到序列模型。 | +| *在 AI 纠正后置信度还有用吗?* | 你仍可以保留原始置信度用于调试,但如果模型支持,AI 可能会输出自己的置信度。 | + +--- + +## 边缘情况与最佳实践 + +1. **空图像或损坏图像** – 在继续之前始终检查 `structured_result.words` 是否非空。 +2. **非拉丁脚本** – 确保 OCR 引擎已为目标语言配置;AI 后处理器也必须在相同脚本上训练。 +3. **性能** – AI 纠正可能耗时。若会重复使用同一图像,可缓存结果,或将 AI 步骤异步化。 +4. **坐标系** – OCR 库可能使用不同的原点(左上 vs. 左下)。在将结果叠加到 PDF 或画布时相应调整。 + +--- + +## 结论 + +现在,你已经掌握了一套完整的 **后处理 OCR** 并可靠 **提取带坐标的文本** 的方案。通过启用结构化输出、将结果送入 AI 校正层并保留原始边界框,你可以将嘈杂的 OCR 扫描转化为干净、具空间感知的文本,供 PDF 生成、数据录入自动化或增强现实叠加等下游任务使用。 + +准备好迈出下一步了吗?尝试将存根 AI 替换为 OpenAI `gpt‑4o‑mini` 调用,或将整个流水线集成到 FastAPI 中。 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/chinese/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..9224b99a9 --- /dev/null +++ b/ocr/chinese/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-04-26 +description: 如何使用 Python 快速识别图像。学习图像识别流水线、批处理,并使用 AI 自动化图像识别。 +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: zh +og_description: 如何使用 Python 快速识别图像。本指南将介绍图像识别流水线、批处理以及使用 AI 的自动化。 +og_title: 如何识别图像——自动化图像识别流程 +tags: +- image-processing +- python +- ai +title: 如何识别图像——自动化图像识别流程 +url: /zh/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何识别图像 – 自动化图像识别流水线 + +是否曾想过 **如何识别图像** 而不需要编写上千行代码?你并不孤单——很多开发者在第一次需要处理数十甚至数百张图片时都会遇到同样的障碍。好消息是,只需几个简洁的步骤,你就可以搭建一个完整的图像识别流水线,自动完成批处理、运行以及清理工作。 + +在本教程中,我们将演示一个完整且可直接运行的示例,展示 **如何批量处理图像**、将每张图像送入 AI 引擎、后处理结果,最后释放资源。完成后,你将拥有一个可直接嵌入任何项目的独立脚本,无论是构建照片标签系统、质量检测系统,还是研究数据集生成器。 + +## 你将学到 + +- 使用模拟 AI 引擎 **识别图像**(真实服务如 TensorFlow、PyTorch 或云 API 的使用方式相同)。 +- 如何构建 **图像识别流水线**,高效处理批量数据。 +- 最佳的 **自动化图像识别** 方法,让你不必每次手动遍历文件。 +- 扩展流水线规模并安全释放资源的技巧。 + +> **先决条件:** Python 3.8+、对函数和循环有基本了解,以及若干待处理的图像文件(或路径)。核心示例不依赖外部库,但我们会指出可以接入真实 AI SDK 的位置。 + +![批处理流水线中如何识别图像的示意图](pipeline.png "如何识别图像示意图") + +## 步骤 1:批量处理你的图像 – 如何高效批量处理图像 + +在 AI 开始任何重活之前,你需要先准备好一批图像供其使用。可以把这看作是你的购物清单;引擎随后会逐项取出。 + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**为什么要批量?** +批量处理可以减少你需要编写的样板代码,并且为以后加入并行化提供了便利。如果你需要处理 10 000 张图片,只需更改 `image_batch` 的来源——流水线的其余部分保持不变。 + +## 步骤 2:运行图像识别流水线(使用 AI 识别图像) + +现在我们把批次接入实际的识别器。真实场景中你可能会调用 `torchvision.models` 或云端接口;这里我们使用模拟行为,使教程保持自包含。 + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**说明:** +- `engine.recognize_image` 是 **图像识别流水线** 的核心;它可以是对深度学习模型的调用,也可以是对 REST API 的请求。 +- `postprocessor.run` 展示了 **自动化图像识别**,通过将原始预测规范化为干净的字典,便于存储或流式传输。 +- 我们将每个 `corrected` 字典收集到 `recognized_results` 中,使后续步骤(例如写入数据库)更加直接。 + +## 步骤 3:后处理并存储 – 自动化图像识别结果 + +得到整洁的预测列表后,通常需要将其持久化。下面的示例将结果写入 CSV 文件;你也可以替换为数据库或消息队列。 + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**为什么使用 CSV?** +CSV 具有通用可读性——Excel、pandas,甚至纯文本编辑器都能打开。如果以后需要 **大规模自动化图像识别**,只需将写入块替换为对数据湖的批量插入即可。 + +## 步骤 4:清理 – 安全释放 AI 资源 + +许多 AI SDK 会分配 GPU 内存或启动工作线程。忘记释放会导致内存泄漏和崩溃。虽然我们的模拟对象不需要此操作,但我们仍会演示正确的模式。 + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +运行脚本后会打印友好的确认信息,表明流水线已顺利结束。 + +## 完整可运行脚本 + +将所有部分组合起来,下面是完整的、可直接复制粘贴的程序: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### 预期输出 + +运行脚本(假设三个占位路径均存在)后,你会看到类似如下的输出: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +生成的 `recognition_results.csv` 内容如下: + +| 图像 | 标签 | 置信度 | +|---------------------|--------|--------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## 结论 + +现在你拥有一个完整的 **如何识别图像** 的端到端示例,涵盖 **图像识别流水线**、批量处理以及自动化后处理。该模式易于扩展:用真实模型替换模拟类,提供更大的 `image_batch`,即可得到生产级解决方案。 + +想进一步提升?可以尝试以下步骤: + +- 用 TensorFlow 或 PyTorch 模型替换 `MockEngine`,获得真实预测。 +- 使用 `concurrent.futures.ThreadPoolExecutor` 并行化循环,加速大批量处理。 +- 将 CSV 写入器接入云存储桶,实现 **跨分布式工作节点的自动化图像识别**。 + +尽情实验、敢于出错并修复它们——这才是掌握图像识别流水线的真正途径。如果遇到问题或有改进建议,欢迎在下方留言。祝编码愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/chinese/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..4d997427d --- /dev/null +++ b/ocr/chinese/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2026-04-26 +description: 使用 AsposeAI OCR 后处理快速掩码信用卡号码。通过一步步教程了解 PCI 合规、正则表达式掩码和数据清理。 +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: zh +og_description: 使用 AsposeAI 在 OCR 结果中掩码信用卡号码。本教程涵盖 PCI 合规、正则表达式掩码和数据清理。 +og_title: 掩码信用卡号码 – 完整的 Python OCR 后处理指南 +tags: +- OCR +- Python +- security +title: 在 OCR 输出中掩码信用卡号码 – 完整 Python 指南 +url: /zh/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 掩码信用卡号码 – 完整 Python 指南 + +是否曾需要在直接来自 OCR 引擎的文本中 **掩码信用卡号码**?你并不是唯一遇到这种情况的人。在受监管的行业中,暴露完整的 PAN(Primary Account Number)会让你在 PCI 合规审计中陷入麻烦。好消息是?只需几行 Python 代码和 AsposeAI 的后处理钩子,你就可以自动隐藏中间的八位数字,确保安全。 + +在本教程中,我们将演示一个真实场景:对收据图片进行 OCR,然后应用自定义 **OCR 后处理** 函数对任何 PCI 数据进行清理。完成后,你将拥有一个可复用的代码片段,能够直接嵌入任何 AsposeAI 工作流,并提供一系列处理边缘情况和扩展方案的实用技巧。 + +## 你将学习 + +- 如何使用 **AsposeAI** 注册自定义后处理器。 +- 为什么 **正则表达式掩码** 方法既快速又可靠。 +- 与数据清理相关的 **PCI 合规** 基础知识。 +- 如何扩展模式以支持多种卡片格式或国际卡号。 +- 预期输出以及如何验证掩码是否生效。 + +> **先决条件** – 你需要一个可用的 Python 3 环境,已安装 Aspose.AI for OCR 包(`pip install aspose-ocr`),以及一张包含信用卡号码的示例图片(例如 `receipt.png`)。不需要其他外部服务。 + +--- + +## 步骤 1:定义一个掩码信用卡号码的后处理器 + +解决方案的核心是一个小函数,它接收 OCR 结果,执行 **正则表达式掩码** 逻辑,并返回清理后的文本。 + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**为什么这样有效:** +- 正则 `(\d{4})\d{8}(\d{4})` 精确匹配 16 位连续数字,这是 Visa、MasterCard 等常见卡片的格式。 +- 通过捕获前四位和后四位(`\1` 和 `\2`),我们在保留足够调试信息的同时,遵守 **PCI 合规** 中禁止存储完整 PAN 的规定。 +- 替换模式 `\1****\2` 隐藏敏感的中间八位数字,将 `1234567812345678` 变为 `1234****5678`。 + +> **专业提示:** 如果需要支持 15 位的美国运通卡号,可添加第二个模式,例如 `r'(\d{4})\d{6}(\d{5})'`,并顺序执行两次替换。 + +--- + +## 步骤 2:初始化 AsposeAI 引擎 + +在我们能够挂载后处理器之前,需要先创建 OCR 引擎实例。AsposeAI 捆绑了 OCR 模型并提供了简易的自定义处理 API。 + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**为何在此初始化?** +一次性创建 `AsposeAI` 对象并在多张图片间复用,可降低开销。引擎还会缓存语言模型,加速后续调用——在批量扫描收据时尤为便利。 + +--- + +## 步骤 3:注册自定义掩码函数 + +AsposeAI 提供 `set_post_processor` 方法,允许你接入任意可调用对象。我们将 `mask_pci` 函数连同可选的设置字典(此处为空)一起传入。 + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**内部发生了什么?** +当稍后调用 `run_postprocessor` 时,AsposeAI 会把原始 OCR 结果交给 `mask_pci`。该函数接收一个轻量对象(`data`),其中包含识别出的文本,返回一个新的字符串。此设计保持核心 OCR 不受影响,同时让你在单一位置强制执行 **数据清理** 策略。 + +--- + +## 步骤 4:对收据图片运行 OCR + +现在引擎已经知道如何清理输出,我们把图片喂进去。为简化教程,假设你已经拥有配置好语言和分辨率的 `engine` 对象。 + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**提示:** 如果还没有预配置对象,可以使用以下方式创建: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +`recognize_image` 调用返回一个对象,其 `text` 属性保存原始、未掩码的字符串。 + +--- + +## 步骤 5:应用已注册的后处理器 + +拿到原始 OCR 数据后,我们将其交给 AI 实例。引擎会自动运行我们之前注册的 `mask_pci` 函数。 + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**为何使用 `run_postprocessor` 而不是手动调用函数?** +这样可以保持工作流的一致性,尤其当你拥有多个后处理器(例如拼写检查、语言检测)时。AsposeAI 会按照注册顺序排队执行,确保输出可预测。 + +--- + +## 步骤 6:验证清理后的输出 + +最后,打印清理后的文本并确认所有信用卡号码已被正确掩码。 + +```python +print(final_result.text) +``` + +**预期输出**(摘录): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +如果收据中没有卡号,文本保持不变——无需掩码,也无需担心。 + +--- + +## 处理边缘情况和常见变体 + +### 文档中出现多个卡号 +如果收据包含多个 PAN(例如会员卡加付款卡),正则会全局匹配,自动掩码所有匹配项,无需额外代码。 + +### 非标准格式 +OCR 有时会插入空格或短横线(`1234 5678 1234 5678` 或 `1234-5678-1234-5678`)。可扩展模式以忽略这些字符: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +新增的 `[ -]?` 允许在数字块之间出现可选的空格或连字符。 + +### 国际卡号 +对于某些地区使用的 19 位 PAN,可将模式放宽为: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +只需记住,**PCI 合规** 仍要求对中间位进行掩码,无论长度如何。 + +### 记录掩码值(可选) +如果需要审计日志,可通过 `custom_settings` 传入标志并调整函数: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +随后使用以下方式注册: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## 完整可运行示例(复制粘贴即用) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +在包含 `4111111111111111` 的收据上运行此脚本,将得到: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +这就是完整的流水线——从原始 OCR 到 **数据清理**,全部用几行简洁的 Python 实现。 + +--- + +## 结论 + +我们已经演示了如何使用 AsposeAI 的后处理钩子、简洁的正则表达式以及一系列 **PCI 合规** 的最佳实践,在 OCR 结果中 **掩码信用卡号码**。该方案完全自包含,适用于任何 OCR 引擎可读取的图像,并可扩展以覆盖更复杂的卡片格式或日志需求。 + +准备好下一步了吗?尝试将此掩码与 **数据库插入** 逻辑结合,仅存储后四位作参考,或集成 **批处理器**,在夜间扫描整个收据文件夹。你也可以探索其他 **OCR 后处理** 任务,如地址标准化或语言检测——它们都遵循我们这里使用的相同模式。 + +对边缘情况、性能或如何将代码迁移到其他 OCR 库有疑问?在下方留言,让我们继续讨论。祝编码愉快,保持安全! + +![掩码信用卡号码在 OCR 流程中的工作示意图](https://example.com/images/ocr-mask-flow.png "OCR 后处理掩码流程图") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/chinese/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..6a5328244 --- /dev/null +++ b/ocr/chinese/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-04-26 +description: 学习如何在 Python 中测量推理时间,加载来自 Hugging Face 的 GGUF 模型,并优化 GPU 使用以获得更快的结果。 +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: zh +og_description: 通过从 Hugging Face 加载 GGUF 模型并调优 GPU 层,以在 Python 中测量推理时间,实现最佳性能。 +og_title: 测量推理时间 – 加载 GGUF 模型并优化 GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: 测量推理时间 – 加载 GGUF 模型并优化 GPU +url: /zh/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 测量推理时间 – 加载 GGUF 模型并优化 GPU + +是否曾需要 **测量推理时间**,但不知从何入手?你并不孤单——许多开发者在首次从 Hugging Face 拉取 GGUF 文件并尝试在 CPU/GPU 混合环境下运行时,都会遇到同样的难题。 + +在本指南中,我们将演示 **如何加载 GGUF 模型**、为 Hugging Face 配置模型,并使用简洁的 Python 代码片段 **测量推理时间**。同时,我们还会展示如何 **优化推理 GPU** 使用,使你的运行速度达到最佳。没有冗余,只提供可直接复制粘贴的实用端到端解决方案。 + +## 你将学到 + +- 如何使用 `AsposeAIModelConfig` **配置 HuggingFace 模型**。 +- 从 Hugging Face Hub **加载 GGUF 模型**(`fp16` 量化)的完整步骤。 +- 用于 **计时 Python 代码** 的可复用模式,围绕推理调用进行计时。 +- 通过调整 `gpu_layers` **优化推理 GPU** 的技巧。 +- 预期输出以及如何验证计时结果的合理性。 + +### 前置条件 + +| 要求 | 为什么重要 | +|------|------------| +| Python 3.9+ | 支持现代语法和类型提示。 | +| `asposeai` 包(或等效 SDK) | 提供 `AsposeAI` 和 `AsposeAIModelConfig`。 | +| 访问 Hugging Face 仓库 `bartowski/Qwen2.5-3B-Instruct-GGUF` | 我们将要加载的 GGUF 模型。 | +| 至少 8 GB VRAM 的 GPU(可选但推荐) | 启用 **优化推理 GPU** 步骤。 | + +如果尚未安装 SDK,请运行: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![measure inference time diagram](https://example.com/measure-inference-time.png){alt="测量推理时间示意图"} + +## 步骤 1:加载 GGUF 模型 – 配置 HuggingFace 模型 + +首先需要一个配置对象,告诉 Aspose AI 从哪里获取模型以及如何处理它。这一步我们 **加载 GGUF 模型** 并 **配置 huggingface 模型** 参数。 + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**为什么重要:** +- `hugging_face_repo_id` 指向 Hub 上的具体 GGUF 文件。 +- `fp16` 在保持模型大部分精度的同时降低内存带宽。 +- `gpu_layers` 是在 **优化推理 GPU** 时调节的关键参数;在 GPU 上放置更多层通常能提升延迟表现,前提是显存足够。 + +## 步骤 2:创建 Aspose AI 实例 + +模型配置完成后,我们实例化 `AsposeAI` 对象。此步骤相对直接,但正是在这里 SDK 会下载 GGUF 文件(如果本地没有缓存)并准备运行时环境。 + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**小技巧:** 第一次运行会稍慢一些,因为模型需要下载并为 GPU 编译。后续运行则会非常迅速。 + +## 步骤 3:运行推理并 **测量推理时间** + +下面是教程的核心:使用 `time.time()` 包裹推理调用,以 **测量推理时间**。我们还会提供一个极小的 OCR 结果作为示例,使示例保持自包含。 + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**你应该看到的结果:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +如果数值偏高,说明大多数层仍在 CPU 上运行。接下来我们将进行 **优化推理 GPU**。 + +## 步骤 4:**优化推理 GPU** – 调整 `gpu_layers` + +默认的 `gpu_layers=40` 有时会过于激进(导致 OOM)或过于保守(性能未发挥)。下面的循环可以帮助你找到最佳平衡点: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**为什么有效:** +- 每次调用都会使用不同的 GPU 分配重新构建运行时,让你即时看到延迟的权衡。 +- 该循环同样演示了 **计时 Python 代码** 的可复用方式,便于在其他性能测试中使用。 + +在 16 GB RTX 3080 上的典型输出可能如下: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +据此,你可以选取 `gpu_layers=40` 作为该硬件的最优设置。 + +## 完整可运行示例 + +将所有内容整合后,以下脚本可直接保存为 `measure_inference.py` 并运行: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +运行方式: + +```bash +python measure_inference.py +``` + +在一块合适的 GPU 上,你应能看到亚秒级的延迟,证明已经成功 **测量推理时间** 并 **优化推理 GPU**。 + +--- + +## 常见问题 (FAQs) + +**Q: 这能用于其他量化格式吗?** +A: 完全可以。只需在配置中将 `hugging_face_quantization="int8"`(或 `q4_0` 等)替换后重新运行基准。会出现典型的权衡:更低的内存占用换取轻微的精度下降。 + +**Q: 如果没有 GPU 怎么办?** +A: 将 `gpu_layers=0`。代码会完全回退到 CPU,仍然可以 **测量推理时间**——只不过数值会更高。 + +**Q: 能只计时模型前向传播,而不包括后处理吗?** +A: 可以。直接调用 `ai_engine.run_model(...)`(或等效方法),并用 `time.time()` 包裹该调用。**计时 Python 代码** 的模式保持不变。 + +--- + +## 结论 + +现在,你拥有了一套完整的、可复制粘贴的解决方案,能够 **测量推理时间**、从 Hugging Face **加载 gguf 模型**,并微调 **优化推理 GPU** 设置。通过调整 `gpu_layers` 并尝试不同的量化方式,你可以挤出每毫秒的性能。 + +接下来,你可以: + +- 将此计时代码集成到 CI 流水线,以捕获回归。 +- 探索批量推理以进一步提升吞吐量。 +- 将模型与真实的 OCR 流程结合,而非本文使用的示例文本。 + +祝编码愉快,愿你的延迟始终保持低位! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/chinese/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..9a17c9194 --- /dev/null +++ b/ocr/chinese/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-04-26 +description: 使用 Python 的 OCR 引擎识别手写文本。了解如何从图像中提取文字,开启手写模式,并快速读取手写笔记。 +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: zh +og_description: 使用 Python 识别手写文本。本教程展示如何从图像中提取文本,开启手写模式,并使用简易 OCR 引擎读取手写笔记。 +og_title: 在 Python 中识别手写文本 – 完整 OCR 指南 +tags: +- OCR +- Python +- Handwriting Recognition +title: 在 Python 中识别手写文本 – OCR 引擎教程 +url: /zh/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中识别手写文本 – OCR 引擎教程 + +是否曾经需要**识别手写文本**却卡在“从哪里开始?”的困惑中?你并不孤单。无论是将会议草稿数字化,还是从扫描表单中提取数据,获得可靠的 OCR 结果常常像在追逐独角兽一样困难。 + +好消息是:只需几行 Python 代码,你就可以**从图像中提取文本**,**开启手写模式**,并最终**读取手写笔记**,无需寻找晦涩的库。在本指南中,我们将完整演示整个流程,从**create OCR engine python** 风格的设置到在屏幕上打印结果。 + +## 你将学到 + +- 如何使用 `ocr` 包**创建 OCR engine python**实例。 +- 哪种语言设置提供内置的手写支持。 +- 用于**开启手写模式**的确切调用,以便引擎知道你在处理连笔文字。 +- 如何提供笔记图片并**识别手写文本**。 +- 处理不同图像格式、排查常见问题以及扩展解决方案的技巧。 + +没有废话,也没有“查看文档”之类的死路——只有一个完整、可运行的脚本,你可以直接复制粘贴并立即测试。 + +## 前置条件 + +在深入之前,请确保你已经: + +1. 安装了 Python 3.8+(代码使用 f‑strings)。 +2. 安装了假设的 `ocr` 库(`pip install ocr‑engine` – 替换为你实际使用的包名)。 +3. 准备了一张清晰的手写笔记图像文件(支持 JPEG、PNG 或 TIFF)。 +4. 有一点点好奇心——其余内容在下文中都有说明。 + +> **专业提示:** 如果你的图像噪声较大,在发送给 OCR 引擎之前使用 Pillow 进行快速预处理(例如 `Image.open(...).convert('L')`)。这通常能提升准确率。 + +## 使用 Python 识别手写文本的方式 + +下面是完整脚本,它**创建 OCR engine python**对象,配置手写模式,并打印提取的字符串。将其保存为 `handwriting_ocr.py` 并在终端运行。 + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### 预期输出 + +脚本成功运行后,你会看到类似如下的输出: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +如果 OCR 引擎未检测到任何字符,`text` 字段将为空字符串。此时,请重新检查图像质量或尝试更高分辨率的扫描。 + +## 步骤详解 + +### 步骤 1 – **create OCR engine python** 实例 + +`OcrEngine` 类是入口点。可以把它想象成一本空白笔记本——在你指定语言和是否处理手写之前,它什么也不会做。 + +### 步骤 2 – 选择支持手写的语言 + +`ocr.Language.EXTENDED_LATIN` 不仅仅是“英语”。它包含一套基于拉丁字母的脚本,并且关键是包含了在手写样本上训练的模型。跳过此步骤常导致输出乱码,因为引擎默认使用印刷体模型。 + +### 步骤 3 – **turn on handwritten mode** + +调用 `enable_handwritten_mode(True)` 会翻转内部标志。引擎随后切换到针对真实笔记中不规则间距和可变笔画宽度调校的神经网络。忘记这行代码是常见错误;引擎会把你的涂鸦当作噪声。 + +### 步骤 4 – 提供图像并**recognize handwritten text** + +`recognize_image` 完成主要工作:它预处理位图,使用手写模型进行识别,并返回一个包含 `text` 属性的对象。如果需要质量指标,你也可以检查 `handwritten_result.confidence`。 + +### 步骤 5 – 打印结果并**read handwritten notes** + +`print(handwritten_result.text)` 是验证你已成功**extract text from image**的最简方式。在生产环境中,你可能会将字符串存入数据库或传递给其他服务。 + +## 处理边缘情况与常见变体 + +| 情况 | 处理方法 | +|-----------|------------| +| **图像已旋转** | 在调用 `recognize_image` 前使用 Pillow 进行旋转(`Image.rotate(angle)`)。 | +| **对比度低** | 转换为灰度并使用自适应阈值(`Image.point(lambda p: p > 128 and 255)`)。 | +| **多页** | 遍历文件路径列表并将结果拼接。 | +| **非拉丁脚本** | 将 `EXTENDED_LATIN` 替换为 `ocr.Language.CHINESE`(或相应语言),并保持 `enable_handwritten_mode(True)`。 | +| **性能关注** | 在处理多张图像时复用同一 `ocr_engine` 实例;每次初始化会增加开销。 | + +### 关于内存使用的专业提示 + +如果你一次性处理数百条笔记,完成后调用 `ocr_engine.dispose()`。它会释放 Python 包装器可能占用的本地资源。 + +## 快速视觉回顾 + +![手写文本识别示例](https://example.com/handwritten-note.png "手写文本识别示例") + +*上图展示了一张典型的手写笔记,我们的脚本可以将其转换为纯文本。* + +## 完整可运行示例(单文件脚本) + +对于喜欢复制粘贴的朋友,这里提供不带解释性注释的完整代码: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Run it with: + +```bash +python handwriting_ocr.py +``` + +现在你应该能在控制台看到 **recognize handwritten text** 的输出。 + +## 结论 + +我们已经完整介绍了在 Python 中**recognize handwritten text**所需的全部内容——从全新的**create OCR engine python**调用、选择正确的语言、**turn on handwritten mode**,到最终**extract text from image**并**read handwritten notes**。 + +只需一个独立的脚本,你就能把模糊的会议涂鸦照片转换为干净、可搜索的文本。接下来,可以考虑将输出送入自然语言处理流水线、存入可检索的索引,甚至回传给转录服务生成配音。 + +### 接下来可以做什么? + +- **批量处理:** 将脚本包装在循环中,以处理整个扫描文件夹。 +- **置信度过滤:** 使用 `result.confidence` 丢弃低质量的识别结果。 +- **替代库:** 如果 `ocr` 并非最佳选择,可尝试使用 `pytesseract` 并加上 `--psm 13` 以启用手写模式。 +- **UI 集成:** 与 Flask 或 FastAPI 结合,提供基于网页的上传服务。 + +对某种图像格式有疑问或需要调优模型?在下方留言吧,祝编码愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/czech/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..d8e5a49c8 --- /dev/null +++ b/ocr/czech/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-04-26 +description: Naučte se, jak stáhnout model HuggingFace v Pythonu a extrahovat text + z obrázku v Pythonu při zlepšování přesnosti OCR v Pythonu pomocí Aspose OCR Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: cs +og_description: Stáhněte model HuggingFace pro python a posilte svůj OCR pipeline. + Postupujte podle tohoto návodu, jak extrahovat text z obrázku v pythonu a zlepšit + přesnost OCR v pythonu. +og_title: stáhnout huggingface model python – Kompletní tutoriál vylepšení OCR +tags: +- OCR +- HuggingFace +- Python +- AI +title: Stáhnout model HuggingFace v Pythonu – krok za krokem průvodce OCR Boost. +url: /cs/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – Kompletní tutoriál pro vylepšení OCR + +Už jste někdy zkusili **download HuggingFace model python** a cítili se ztraceni? Nejste v tom sami. V mnoha projektech je největší úzkým hrdlem získání dobrého modelu na váš počítač a následné zpřehlednění výsledků OCR. + +V tomto průvodci projdeme praktickým příkladem, který vám ukáže, jak **download HuggingFace model python**, vytáhnout text z obrázku pomocí **extract text from image python** a následně **improve OCR accuracy python** pomocí AI post‑processoru od Aspose. Na konci budete mít připravený skript, který převádí špinavý obrázek faktury na čistý, čitelný text – žádná magie, jen jasné kroky. + +## Co budete potřebovat + +- Python 3.9+ (kód funguje i na 3.11) +- Internetové připojení pro jednorázové stažení modelu +- Balíček `asposeocrcloud` (`pip install asposeocrcloud`) +- Vzorek obrázku (např. `sample_invoice.png`) umístěný ve složce, kterou ovládáte + +To je vše – žádné těžké frameworky, žádné GPU‑specifické ovladače, pokud nechcete urychlit výpočty. + +Nyní se ponořme do samotné implementace. + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## Krok 1: Nastavení OCR enginu a výběr jazyka +*(Zde začínáme **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Proč je to důležité:** +OCR engine je první obranná linie; výběrem správného jazykového balíčku snížíte chyby rozpoznávání znaků hned na začátku, což je klíčová součást **improve OCR accuracy python**. + +## Krok 2: Konfigurace modelu AsposeAI – Stahování z HuggingFace +*(Zde skutečně **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**Co se děje pod kapotou?** +Když je `allow_auto_download` nastaven na true, SDK se spojí s HuggingFace, stáhne model `Qwen2.5‑3B‑Instruct‑GGUF` a uloží jej do složky, kterou jste zadali. To je jádro **download huggingface model python** – SDK provede těžkou práci, takže nemusíte psát žádné `git clone` ani `wget` příkazy. + +*Tip:* Uchovávejte `directory_model_path` na SSD pro rychlejší načítání; model má velikost ~3 GB i ve formátu `int8`. + +## Krok 3: Připojení AI enginu k OCR engineu +*(Propojujeme oba komponenty, abychom mohli **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Proč je to spojení potřeba?** +OCR engine nám poskytne surový text, který může obsahovat překlepy, rozbité řádky nebo špatnou interpunkci. AI engine funguje jako chytrý editor, který tyto problémy opraví – přesně to, co potřebujete k **improve OCR accuracy python**. + +## Krok 4: Spuštění OCR na vašem obrázku +*(Okamžik, kdy konečně **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` nyní obsahuje atribut `text` se surovými znaky, které engine rozpoznal. V praxi si všimnete několika drobných chyb – třeba „Invoice“ se promění na „Inv0ice“ nebo se objeví neočekávaný zalomení řádku uprostřed věty. + +## Krok 5: Vyčištění pomocí AI post‑processoru +*(Tento krok přímo **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +AI model přepíše text a aplikuje jazykově uvědomělé opravy. Protože používáme instrukčně laděný model z HuggingFace, výstup je obvykle plynulý a připravený pro další zpracování. + +## Krok 6: Zobrazení před a po +*(Rychlá kontrola, jak dobře **extract text from image python** a **improve OCR accuracy python** fungují.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Očekávaný výstup + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Všimněte si, jak AI opravil „Inv0ice“ na „Invoice“ a vyhladila nechtěné zalomení řádků. To je konkrétní výsledek **improve OCR accuracy python** pomocí staženého modelu z HuggingFace. + +## Často kladené otázky (FAQ) + +### Potřebuji GPU pro spuštění modelu? +Ne. Nastavení `gpu_layers=20` říká SDK, aby použilo až 20 GPU vrstev, pokud je k dispozici kompatibilní GPU; jinak přejde na CPU. Na moderním notebooku CPU cesta stále zpracovává několik stovek tokenů za sekundu – ideální pro občasné parsování faktur. + +### Co když se model nepodaří stáhnout? +Ujistěte se, že vaše prostředí může dosáhnout na `https://huggingface.co`. Pokud jste za firemním proxy, nastavte proměnné prostředí `HTTP_PROXY` a `HTTPS_PROXY`. SDK bude automaticky opakovat pokus, ale můžete také ručně `git lfs pull` repozitář do `directory_model_path`. + +### Můžu model vyměnit za menší? +Ano. Stačí nahradit `hugging_face_repo_id` jiným repozitářem (např. `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) a upravit `hugging_face_quantization` podle potřeby. Menší modely se stáhnou rychleji a spotřebují méně RAM, i když můžete ztratit trochu kvality korekcí. + +### Jak mi to pomůže **extract text from image python** v jiných oblastech? +Stejný pipeline funguje pro účtenky, pasy nebo ručně psané poznámky. Jediná změna je jazykový balíček (`ocr.Language.FRENCH` atd.) a případně doménově specifický model laděný na HuggingFace. + +## Bonus: Automatizace více souborů + +Pokud máte složku plnou obrázků, zabalte volání OCR do jednoduché smyčky: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +Toto malé rozšíření vám umožní **download huggingface model python** jednou a poté dávkově zpracovat desítky souborů – skvělé pro škálování vaší pipeline pro automatizaci dokumentů. + +## Závěr + +Právě jsme prošli kompletním, end‑to‑end příkladem, který ukazuje, jak **download HuggingFace model python**, **extract text from image python** a **improve OCR accuracy python** pomocí Aspose OCR Cloud a AI post‑processoru. Skript je připraven k spuštění, koncepty jsou vysvětleny a viděli jste výstup před a po, takže víte, že funguje. + +Co dál? Vyzkoušejte jiný model z HuggingFace, experimentujte s dalšími jazykovými balíčky nebo předejte vyčištěný text do downstream NLP pipeline (např. extrakce entit z položek faktury). Možnosti jsou neomezené a základ, který jste právě postavili, je pevný. + +Máte otázky nebo obtížný obrázek, který OCR stále zaskočí? Zanechte komentář níže a pojďme to společně vyřešit. Šťastné kódování! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/czech/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..aa4863bbb --- /dev/null +++ b/ocr/czech/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-04-26 +description: Rychle stáhněte OCR model pomocí Aspose OCR pro Python. Naučte se, jak + nastavit adresář modelu, nakonfigurovat cestu k modelu a jak stáhnout model v několika + řádcích. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: cs +og_description: Stáhněte OCR model během několika sekund s Aspose OCR Python. Tento + průvodce ukazuje, jak nastavit adresář modelu, nakonfigurovat cestu k modelu a jak + bezpečně stáhnout model. +og_title: Stáhněte OCR model – Kompletní tutoriál Aspose OCR pro Python +tags: +- OCR +- Python +- Aspose +title: Stáhněte OCR model s Aspose OCR Python – krok za krokem průvodce +url: /cs/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – Kompletní tutoriál Aspose OCR pro Python + +Už jste se někdy ptali, jak **download ocr model** pomocí Aspose OCR v Pythonu, aniž byste museli prohledávat nekonečné dokumentace? Nejste v tom sami. Mnoho vývojářů narazí na problém, když model není lokálně dostupný a SDK vyhodí nejasnou chybu. Dobrá zpráva? Oprava je jen pár řádků a model budete mít připravený během několika minut. + +V tomto tutoriálu projdeme vše, co potřebujete vědět: od importu správných tříd, přes **set model directory**, až po **how to download model**, a nakonec ověření cesty. Na konci budete schopni spustit OCR na libovolném obrázku jediným voláním funkce a pochopíte možnosti **configure model path**, které udrží váš projekt přehledný. Žádné zbytečnosti, jen praktický, spustitelný příklad pro uživatele **aspose ocr python**. + +## What You’ll Learn + +- Jak správně importovat třídy Aspose OCR Cloud. +- Přesné kroky k **download ocr model** automaticky. +- Způsoby, jak **set model directory** a **configure model path** pro reprodukovatelné sestavení. +- Jak ověřit, že je model inicializován a kde se nachází na disku. +- Běžné úskalí (oprávnění, chybějící adresáře) a rychlé opravy. + +### Prerequisites + +- Python 3.8+ nainstalovaný na vašem počítači. +- Balíček `asposeocrcloud` (`pip install asposeocrcloud`). +- Oprávnění k zápisu do složky, kam chcete model uložit (např. `C:\models` nebo `~/ocr_models`). + +--- + +## Step 1: Import Aspose OCR Cloud Classes + +První věc, kterou potřebujete, je správné importování. Toto načte třídy, které spravují konfiguraci modelu a OCR operace. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Proč je to důležité:* `AsposeAI` je engine, který bude provádět OCR, zatímco `AsposeAIModelConfig` říká engine **where** hledat model a **whether** má model stáhnout automaticky. Vynechání tohoto kroku nebo import špatného modulu způsobí `ModuleNotFoundError` ještě před částí stahování. + +--- + +## Step 2: Define the Model Configuration (Set Model Directory & Configure Model Path) + +Nyní řekneme Aspose, kde má uchovávat soubory modelu. Zde **set model directory** a **configure model path**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Tipy a úskalí** + +- **Absolutní cesty** zabraňují záměně, když skript běží z jiného pracovního adresáře. +- Na Linux/macOS můžete použít `"/home/you/ocr_models"`; na Windows přidejte předponu `r`, aby se zpětná lomítka brala doslovně. +- Nastavení `allow_auto_download="true"` je klíčové pro **how to download model** bez psaní dalšího kódu. + +--- + +## Step 3: Create the AsposeAI Instance Using the Configuration + +S připravenou konfigurací vytvořte instanci OCR enginu. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Proč je to důležité:* Objekt `ocr_ai` nyní obsahuje konfiguraci, kterou jsme právě definovali. Pokud model není přítomen, další volání automaticky spustí stažení – to je jádro **how to download model** v režimu hands‑off. + +--- + +## Step 4: Trigger the Model Download (If Needed) + +Než spustíte OCR, musíte se ujistit, že je model skutečně na disku. Metoda `is_initialized()` kontroluje i vynutí inicializaci. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**Co se děje pod kapotou?** + +- První volání `is_initialized()` vrátí `False`, protože složka modelu je prázdná. +- `print` informuje uživatele, že se chystá stažení. +- Druhé volání vynutí Aspose, aby stáhl model z Hugging Face repozitáře, který jste dříve zadali. +- Po stažení metoda při dalších kontrolách vrátí `True`. + +**Hraniční případ:** Pokud vám síť blokuje Hugging Face, zobrazí se výjimka. V takovém případě si model stáhněte ručně jako zip, rozbalte jej do `directory_model_path` a skript spusťte znovu. + +--- + +## Step 5: Report the Local Path Where the Model Is Now Available + +Po dokončení stažení pravděpodobně chcete vědět, kam se soubory uložily. To pomáhá při ladění i při nastavení CI pipeline. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Typický výstup vypadá takto: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Nyní jste úspěšně **download ocr model**, nastavili adresář a potvrdili cestu. + +--- + +## Visual Overview + +Níže je jednoduchý diagram, který ukazuje tok od konfigurace po připravený model. + +![download ocr model diagram toku ukazující konfiguraci, automatické stažení a lokální cestu](/images/download-ocr-model-flow.png) + +*Alt text zahrnuje primární klíčové slovo pro SEO.* + +--- + +## Common Variations & How to Handle Them + +### 1. Using a Different Model Repository + +Pokud potřebujete model jiný než `openai/gpt2`, stačí změnit hodnotu `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Ujistěte se, že repozitář je veřejný nebo že máte potřebný token nastavený v prostředí. + +### 2. Disabling Automatic Download + +Někdy chcete řídit stažení sami (např. v prostředích bez přístupu k internetu). Nastavte `allow_auto_download` na `"false"` a před inicializací spusťte vlastní skript pro stažení: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Changing the Model Directory at Runtime + +Cestu můžete změnit i během běhu, aniž byste museli znovu vytvářet objekt `AsposeAI`: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Pro Tips for Production Use + +- **Cache the model**: Uchovávejte adresář na sdíleném síťovém disku, pokud jej potřebuje více služeb. Tím se vyhnete zbytečným stažením. +- **Version pinning**: Repizitář na Hugging Face se může aktualizovat. Pro zamčení na konkrétní verzi přidejte `@v1.0.0` k ID repozitáře (`"openai/gpt2@v1.0.0"`). +- **Permissions**: Zajistěte, aby uživatel spouštějící skript měl práva čtení/zápisu na `directory_model_path`. Na Linuxu obvykle stačí `chmod 755`. +- **Logging**: Nahraďte jednoduché `print` výpisy modularem `logging` pro lepší pozorovatelnost ve větších aplikacích. + +--- + +## Full Working Example (Copy‑Paste Ready) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Očekávaný výstup** (první spuštění stáhne, následná spuštění přeskakují stažení): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Spusťte skript znovu; uvidíte jen řádek s cestou, protože model je již v cache. + +--- + +## Conclusion + +Právě jsme prošli kompletní proces **download ocr model** pomocí Aspose OCR Python, ukázali, jak **set model directory**, a vysvětlili nuance **configure model path**. Pouhých několik řádků kódu vám umožní automatizovat stažení, vyhnout se manuálním krokům a udržet OCR pipeline reprodukovatelnou. + +Dále můžete zkusit samotné volání OCR (`ocr_ai.recognize_image(...)`) nebo experimentovat s jiným modelem z Hugging Face pro vyšší přesnost. Ať už tak či tak, základ, který jste zde postavili – jasná konfigurace, automatické stažení a ověření cesty – usnadní jakoukoli budoucí integraci. + +Máte otázky ohledně hraničních případů, nebo chcete sdílet, jak jste upravili adresář modelu pro cloudové nasazení? Zanechte komentář níže a šťastné kódování! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/czech/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..97299eee9 --- /dev/null +++ b/ocr/czech/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-26 +description: Jak post‑processovat výsledky OCR a extrahovat text s koordináty. Naučte + se krok za krokem řešení pomocí strukturovaného výstupu a AI korekce. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: cs +og_description: Jak následně zpracovat výsledky OCR a extrahovat text s koordináty. + Sledujte tento komplexní návod pro spolehlivý pracovní postup. +og_title: Jak post‑processovat OCR – kompletní průvodce +tags: +- OCR +- Python +- AI +- Text Extraction +title: Jak post‑processovat OCR – Extrahovat text s koordináty v Pythonu +url: /cs/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak post‑processovat OCR – Extrahovat text s koordináty v Pythonu + +Už jste někdy potřebovali **jak post‑processovat OCR** výsledky, protože surový výstup byl šumivý nebo nesprávně zarovnaný? Nejste v tom sami. V mnoha reálných projektech—skenování faktur, digitalizace účtenek nebo dokonce rozšiřování AR zážitků—OCR engine vám poskytuje surová slova, ale stále je musíte vyčistit a sledovat, kde se každé slovo nachází na stránce. Právě zde se ukáže síla režimu strukturovaného výstupu kombinovaného s AI‑řízeným post‑procesorem. + +V tomto tutoriálu projdeme kompletní, spustitelnou Python pipeline, která **extrahuje text s koordináty** z obrázku, provede AI‑založený krok korekce a vytiskne každé slovo spolu s jeho (x, y) pozicí. Žádné chybějící importy, žádné vágní odkazy typu „viz dokumentace“—jen samostatné řešení, které můžete dnes vložit do svého projektu. + +> **Tip:** Pokud používáte jinou OCR knihovnu, hledejte režim „structured“ nebo „layout“; koncepty zůstávají stejné. + +--- + +## Požadavky + +Než se ponoříme dál, ujistěte se, že máte: + +| Požadavek | Proč je důležitý | +|-----------|-------------------| +| Python 3.9+ | Moderní syntax a typové nápovědy | +| `ocr` knihovna, která podporuje `OutputMode.STRUCTURED` (např. fiktivní `myocr`) | Potřebná pro data o ohraničovacích rámečcích | +| AI modul pro post‑processing (může být OpenAI, HuggingFace nebo vlastní model) | Zvyšuje přesnost po OCR | +| Obrázkový soubor (`input.png`) ve vašem pracovním adresáři | Zdroj, který načteme | + +Pokud některý z nich není známý, jednoduše nainstalujte placeholder balíčky pomocí `pip install myocr ai‑postproc`. Níže uvedený kód také obsahuje fallback stuby, takže můžete otestovat tok bez skutečných knihoven. + +--- + +## Krok 1: Povolení režimu strukturovaného výstupu pro OCR engine + +První věc, kterou uděláme, je říct OCR engine, aby nám poskytl víc než jen prostý text. Strukturovaný výstup vrací každé slovo spolu s jeho ohraničovacím rámečkem a skóre důvěry, což je nezbytné pro **extrahování textu s koordináty** později. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Proč je to důležité:* Bez strukturovaného režimu byste dostali jen dlouhý řetězec a ztratili byste prostorové informace, které potřebujete pro překrytí textu na obrázcích nebo pro následnou analýzu rozvržení. + +--- + +## Krok 2: Rozpoznání obrázku a zachycení slov, rámečků a důvěry + +Nyní předáme obrázek do engine. Výsledek je objekt, který obsahuje seznam objektů slov, z nichž každý poskytuje `text`, `x`, `y`, `width`, `height` a `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Hraniční případ:* Pokud je obrázek prázdný nebo nečitelné, `structured_result.words` bude prázdný seznam. Je dobré to zkontrolovat a ošetřit to elegantně. + +--- + +## Krok 3: Spuštění AI‑založeného post‑processingu při zachování pozic + +I ty nejlepší OCR enginy dělají chyby—např. „O“ vs. „0“ nebo chybějící diakritiku. AI model trénovaný na doménově specifickém textu může tyto chyby opravit. Důležité je, že zachováme původní souřadnice, aby prostorové rozvržení zůstalo nedotčeno. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Proč zachováváme souřadnice:* Mnoho následných úkolů (např. generování PDF, AR označování) závisí na přesném umístění. AI mění jen pole `text`, zatímco `x`, `y`, `width`, `height` zůstávají nedotčeny. + +--- + +## Krok 4: Iterace přes opravená slova a zobrazení jejich textu se souřadnicemi + +Nakonec projdeme opravená slova a vytiskneme každé slovo spolu s jeho levým horním rohem `(x, y)`. Tím splníme cíl **extrahování textu s koordináty**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Očekávaný výstup (příklad):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Každý řádek zobrazuje opravené slovo a jeho přesnou polohu na původním obrázku. + +--- + +## Kompletní funkční příklad + +Níže je jeden skript, který spojuje vše dohromady. Můžete jej zkopírovat, upravit importy tak, aby odpovídaly vašim skutečným knihovnám, a spustit jej přímo. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Spuštění skriptu** + +```bash +python ocr_postprocess_demo.py +``` + +Pokud máte nainstalované skutečné knihovny, skript zpracuje váš `input.png`. Jinak vám stub implementace umožní vidět očekávaný tok a výstup bez jakýchkoli externích závislostí. + +--- + +## Často kladené otázky (FAQ) + +| Otázka | Odpověď | +|--------|---------| +| *Funguje to s Tesseractem?* | Tesseract sám o sobě neexponuje strukturovaný režim přímo, ale wrappery jako `pytesseract.image_to_data` vrací ohraničovací rámečky, které můžete předat stejnému AI post‑processoru. | +| *Co když potřebuji pravý dolní roh místo levého horního?* | Každý objekt slova také poskytuje `width` a `height`. Vypočítejte `x2 = x + width` a `y2 = y + height` pro získání opačného rohu. | +| *Mohu zpracovávat více obrázků najednou?* | Určitě. Zabalte kroky do smyčky `for image_path in Path("folder").glob("*.png"):` a sbírejte výsledky po souborech. | +| *Jak si vybrat AI model pro korekci?* | Pro obecný text funguje malý GPT‑2 doladěný na OCR chyby. Pro doménově specifická data (např. lékařské předpisy) trénujte sekvence‑na‑sekvence model na párovaných špinavých‑čistých datech. | +| *Je skóre důvěry užitečné po AI korekci?* | Stále můžete zachovat původní skóre důvěry pro ladění, ale AI může vrátit své vlastní skóre, pokud model podporuje. | + +--- + +## Hraniční případy a osvědčené postupy + +1. **Prázdné nebo poškozené obrázky** – vždy ověřte, že `structured_result.words` není prázdný před pokračováním. +2. **Není‑latinské skripty** – ujistěte se, že váš OCR engine je nastaven pro cílový jazyk; AI post‑processor musí být trénován na stejný skript. +3. **Výkon** – AI korekce může být nákladná. Ukládejte výsledky do cache, pokud budete stejný obrázek znovu používat, nebo spusťte AI krok asynchronně. +4. **Systém souřadnic** – OCR knihovny mohou používat různé počátky (levý horní vs. levý dolní). Přizpůsobte to při překrývání na PDF nebo plátna. + +--- + +## Závěr + +Nyní máte solidní, end‑to‑end recept na **jak post‑processovat OCR** a spolehlivě **extrahovat text s koordináty**. Povolením strukturovaného výstupu, předáním výsledku přes AI korekční vrstvu a zachováním původních ohraničovacích rámečků můžete převést šumivé OCR skeny na čistý, prostorově‑vědomý text připravený pro následné úkoly jako generování PDF, automatizace zadávání dat nebo rozšířené realitní překrytí. + +Připraven na další krok? Zkuste nahradit stub AI voláním OpenAI `gpt‑4o‑mini`, nebo integrujte pipeline do FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/czech/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..981504299 --- /dev/null +++ b/ocr/czech/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-26 +description: Jak rychle rozpoznávat obrázky v Pythonu. Naučte se pipeline pro rozpoznávání + obrázků, dávkové zpracování a automatizaci rozpoznávání obrázků pomocí AI. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: cs +og_description: Jak rychle rozpoznávat obrázky v Pythonu. Tento průvodce vás provede + pipeline rozpoznávání obrázků, dávkováním a automatizací pomocí AI. +og_title: Jak rozpoznávat obrázky – Automatizujte proces rozpoznávání obrázků +tags: +- image-processing +- python +- ai +title: Jak rozpoznávat obrázky – Automatizujte pipeline pro rozpoznávání obrázků +url: /cs/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak rozpoznávat obrázky – Automatizace pipeline pro rozpoznávání obrázků + +Už jste se někdy ptali, **jak rozpoznávat obrázky** bez psaní tisíc řádků kódu? Nejste v tom sami — mnoho vývojářů narazí na stejnou překážku, když poprvé potřebují zpracovat desítky nebo stovky fotografií. Dobrá zpráva? S několika úhlednými kroky můžete spustit plnohodnotnou pipeline pro rozpoznávání obrázků, která dávkuje, spouští a uklízí vše sama. + +V tomto tutoriálu projdeme kompletním, spustitelným příkladem, který ukazuje **jak dávkovat obrázky**, předat je AI enginu, následně zpracovat výsledky a nakonec uvolnit prostředky. Na konci budete mít samostatný skript, který můžete vložit do libovolného projektu, ať už budujete tagger fotografií, systém kontroly kvality nebo generátor výzkumných datasetů. + +## Co se naučíte + +- **Jak rozpoznávat obrázky** pomocí simulovaného AI enginu (vzorec je stejný pro skutečné služby jako TensorFlow, PyTorch nebo cloudová API). +- Jak vytvořit **pipeline pro rozpoznávání obrázků**, která efektivně pracuje s dávkami. +- Nejlepší způsob, jak **automatizovat rozpoznávání obrázků**, abyste nemuseli pokaždé ručně procházet soubory. +- Tipy pro škálování pipeline a bezpečné uvolňování prostředků. + +> **Předpoklady:** Python 3.8+, základní znalost funkcí a smyček a několik souborů s obrázky (nebo jejich cest), které chcete zpracovat. Pro jádro příkladu nejsou potřeba žádné externí knihovny, ale zmíníme, kde můžete připojit skutečná AI SDK. + +![Diagram, jak rozpoznávat obrázky v pipeline pro dávkové zpracování](pipeline.png "Diagram rozpoznávání obrázků") + +## Krok 1: Dávkujte své obrázky – Jak efektivně dávkovat obrázky + +Než AI začne těžkou práci, potřebujete sbírku obrázků, které jí předáte. Představte si to jako nákupní seznam; engine si později vybere každou položku ze seznamu po jedné. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Proč dávkovat?** +Dávkování snižuje množství boilerplate kódu, který musíte napsat, a usnadňuje pozdější přidání paralelismu. Pokud budete někdy potřebovat zpracovat 10 000 obrázků, stačí změnit zdroj `image_batch` — zbytek pipeline zůstane nedotčen. + +## Krok 2: Spusťte pipeline pro rozpoznávání obrázků (Rozpoznávejte obrázky pomocí AI) + +Nyní připojíme dávku k samotnému rozpoznávači. Ve skutečném scénáři byste mohli volat `torchvision.models` nebo cloudový endpoint; zde simulujeme chování, aby byl tutoriál samostatný. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Vysvětlení:** +- `engine.recognize_image` je srdcem **pipeline pro rozpoznávání obrázků**; může jít o volání modelu hlubokého učení nebo REST API. +- `postprocessor.run` demonstruje **automatizaci rozpoznávání obrázků** tím, že normalizuje surové předpovědi do čistého slovníku, který můžete uložit nebo streamovat. +- Každý `corrected` slovník ukládáme do `recognized_results`, takže následné kroky (např. vložení do databáze) jsou jednoduché. + +## Krok 3: Post‑zpracování a uložení – Automatizace výsledků rozpoznávání obrázků + +Po získání úhledného seznamu předpovědí jej obvykle chcete uložit. Níže uvedený příklad zapisuje CSV soubor; klidně ho vyměňte za databázi nebo frontu zpráv. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Proč CSV?** +CSV je univerzálně čitelné — Excel, pandas, i běžné textové editory jej otevřou. Pokud později budete potřebovat **automatizovat rozpoznávání obrázků** ve velkém měřítku, nahraďte blok zápisu hromadným vložením do vašeho datového jezera. + +## Krok 4: Úklid – Bezpečné uvolnění AI prostředků + +Mnoho AI SDK alokuje GPU paměť nebo spouští pracovní vlákna. Zapomenutí na jejich uvolnění může vést k únikům paměti a nepříjemným pádům. I když naše simulované objekty to nepotřebují, ukážeme správný vzor. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +Spuštění skriptu vypíše přátelské potvrzení, že pipeline úspěšně skončila. + +## Kompletní funkční skript + +Spojením všech částí získáte kompletní, připravený program ke zkopírování a vložení: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Očekávaný výstup + +Po spuštění skriptu (za předpokladu, že tři zástupné cesty existují) uvidíte něco jako: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +A vygenerovaný soubor `recognition_results.csv` bude obsahovat: + +| image | label | confidence | +|---------------------|-------|------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Závěr + +Nyní máte solidní, end‑to‑end příklad **jak rozpoznávat obrázky** v Pythonu, kompletní s **pipeline pro rozpoznávání obrázků**, dávkováním a automatizovaným post‑zpracováním. Vzor je škálovatelný: vyměňte simulované třídy za skutečný model, předávejte větší `image_batch` a získáte řešení připravené do produkce. + +Chcete jít dál? Vyzkoušejte následující kroky: + +- Nahraďte `MockEngine` modelem TensorFlow nebo PyTorch pro reálné předpovědi. +- Paralelizujte smyčku pomocí `concurrent.futures.ThreadPoolExecutor` pro zrychlení velkých dávek. +- Připojte CSV zapisovač k úložišti v cloudu, abyste **automatizovali rozpoznávání obrázků** napříč distribuovanými pracovníky. + +Klidně experimentujte, rozbíjejte věci a pak je opravujte — tak se opravdu zvládnou pipeline pro rozpoznávání obrázků. Pokud narazíte na problémy nebo máte nápady na vylepšení, zanechte komentář níže. Šťastné kódování! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/czech/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..fa7ba2103 --- /dev/null +++ b/ocr/czech/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-26 +description: Rychle maskujte čísla kreditních karet pomocí post‑zpracování OCR od + AsposeAI. Naučte se o shodě s PCI, maskování regulárních výrazů a sanitaci dat v + tutoriálu krok za krokem. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: cs +og_description: Maskujte čísla kreditních karet ve výsledcích OCR pomocí AsposeAI. + Tento tutoriál pokrývá dodržování PCI, maskování pomocí regulárních výrazů a sanitaci + dat. +og_title: Maskování čísel kreditních karet – Kompletní průvodce post‑processingem + OCR v Pythonu +tags: +- OCR +- Python +- security +title: Maskování čísel kreditních karet v OCR výstupu – Kompletní průvodce v Pythonu +url: /cs/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maskování čísel kreditních karet – Kompletní průvodce v Pythonu + +Už jste někdy potřebovali **maskovat čísla kreditních karet** v textu, který pochází přímo z OCR enginu? Nejste v tom sami. V regulovaných odvětvích může odhalení úplného PAN (Primary Account Number) přivést problémy s auditorem PCI compliance. Dobrá zpráva? S několika řádky Pythonu a post‑processing hookem AsposeAI můžete automaticky skrýt prostředních osm číslic a zůstat na bezpečné straně. + +V tomto tutoriálu projdeme reálný scénář: spuštění OCR na obrázku účtenky a následné použití vlastní **OCR post‑processing** funkce, která sanitizuje jakákoli PCI data. Na konci budete mít znovupoužitelný úryvek, který můžete vložit do libovolného workflow AsposeAI, plus několik praktických tipů pro řešení okrajových případů a škálování řešení. + +## Co se naučíte + +- Jak zaregistrovat vlastní post‑processor s **AsposeAI**. +- Proč je přístup **regular expression masking** rychlý a spolehlivý. +- Základy **PCI compliance** související s sanitací dat. +- Způsoby, jak rozšířit vzor pro více formátů karet nebo mezinárodní čísla. +- Očekávaný výstup a jak ověřit, že maskování funguje. + +> **Předpoklady** – Měli byste mít funkční prostředí Python 3, nainstalovaný balíček Aspose.AI for OCR (`pip install aspose-ocr`) a ukázkový obrázek (např. `receipt.png`), který obsahuje číslo kreditní karty. Žádné další externí služby nejsou vyžadovány. + +--- + +## Krok 1: Definujte post‑processor, který maskuje čísla kreditních karet + +Srdce řešení spočívá v malé funkci, která přijímá výsledek OCR, spustí **regular expression masking** rutinu a vrátí sanitizovaný text. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Proč to funguje:** +- Regulární výraz `(\d{4})\d{8}(\d{4})` odpovídá přesně 16 po sobě jdoucím číslicím, což je běžný formát pro Visa, MasterCard a mnoho dalších. +- Zachycením prvních a posledních čtyř číslic (`\1` a `\2`) zachováme dostatek informací pro ladění a zároveň dodržujeme pravidla **PCI compliance**, která zakazují ukládání úplného PAN. +- Náhrada `\1****\2` skryje citlivých osm prostředních číslic a změní `1234567812345678` na `1234****5678`. + +> **Pro tip:** Pokud potřebujete podporovat 15‑ciferná čísla American Express, přidejte druhý vzor jako `r'(\d{4})\d{6}(\d{5})'` a spusťte oba nahrazení sekvenčně. + +--- + +## Krok 2: Inicializujte engine AsposeAI + +Než můžeme připojit náš post‑processor, potřebujeme instanci OCR enginu. AsposeAI balí OCR model a jednoduché API pro vlastní zpracování. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Proč inicializovat zde?** +Vytvořením objektu `AsposeAI` jednou a jeho opakovaným použitím napříč více obrázky snižujeme režii. Engine také kešuje jazykové modely, což urychluje následná volání – užitečné při skenování dávky účtenek. + +--- + +## Krok 3: Zaregistrujte vlastní maskovací funkci + +AsposeAI poskytuje metodu `set_post_processor`, která vám umožní připojit libovolný callable. Předáme naši funkci `mask_pci` spolu s volitelným slovníkem nastavení (prozatím prázdným). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**Co se děje v pozadí?** +Když později zavoláte `run_postprocessor`, AsposeAI předá surový výsledek OCR funkci `mask_pci`. Funkce dostane lehký objekt (`data`), který obsahuje rozpoznaný text, a vy vrátíte nový řetězec. Tento design ponechává jádro OCR nedotčené a umožňuje vynutit **data sanitization** politiku na jednom místě. + +--- + +## Krok 4: Spusťte OCR na obrázku účtenky + +Nyní, když engine ví, jak vyčistit výstup, předáme mu obrázek. Pro tento tutoriál předpokládáme, že již máte objekt `engine` nakonfigurovaný se správnými jazykovými a rozlišeními. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Tip:** Pokud nemáte předkonfigurovaný objekt, můžete jej vytvořit pomocí: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +Volání `recognize_image` vrací objekt, jehož atribut `text` obsahuje surový, ne‑maskovaný řetězec. + +--- + +## Krok 5: Použijte registrovaný post‑processor + +S čistými OCR daty v ruce je předáme instanci AI. Engine automaticky spustí funkci `mask_pci`, kterou jsme dříve zaregistrovali. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Proč použít `run_postprocessor` místo ručního volání funkce?** +Tím se workflow udrží konzistentní, zejména když máte více post‑processorů (např. kontrola pravopisu, detekce jazyka). AsposeAI je řadí v pořadí, ve kterém je zaregistrujete, a zaručuje deterministický výstup. + +--- + +## Krok 6: Ověřte sanitovaný výstup + +Nakonec vytiskneme sanitovaný text a potvrdíme, že všechna čísla kreditních karet jsou správně maskována. + +```python +print(final_result.text) +``` + +**Očekávaný výstup** (úryvek): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Pokud účtenka neobsahovala žádné číslo karty, text zůstane nezměněn – nic k maskování, nic k obavám. + +--- + +## Řešení okrajových případů a běžných variant + +### Více čísel karet v jednom dokumentu +Pokud účtenka obsahuje více než jeden PAN (např. věrnostní kartu plus platební kartu), regulární výraz běží globálně a automaticky maskuje všechny shody. Žádný další kód není potřeba. + +### Nestandardní formátování +Někdy OCR vloží mezery nebo pomlčky (`1234 5678 1234 5678` nebo `1234-5678-1234-5678`). Rozšiřte vzor, aby ignoroval tyto znaky: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +Přidané `[ -]?` toleruje volitelné mezery nebo pomlčky mezi bloky číslic. + +### Mezinárodní karty +Pro 19‑ciferné PANy používané v některých regionech můžete rozšířit vzor: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Jen si pamatujte, že **PCI compliance** stále vyžaduje maskování prostředních číslic, bez ohledu na délku. + +### Logování maskovaných hodnot (volitelné) +Pokud potřebujete auditní stopy, předávejte příznak přes `custom_settings` a upravte funkci: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Pak zaregistrujte pomocí: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Kompletní funkční příklad (připravený ke zkopírování) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Spuštěním tohoto skriptu na účtence, která obsahuje `4111111111111111`, získáte: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +To je celý pipeline – od surového OCR až po **data sanitization** – zabalený do několika čistých řádků Pythonu. + +--- + +## Závěr + +Právě jsme vám ukázali, jak **maskovat čísla kreditních karet** v OCR výsledcích pomocí post‑processing hooku AsposeAI, stručné rutiny regulárního výrazu a několika tipů pro **PCI compliance**. Řešení je zcela samostatné, funguje s libovolným obrázkem, který OCR engine dokáže přečíst, a lze jej rozšířit o složitější formáty karet nebo požadavky na logování. + +Jste připraveni na další krok? Zkuste propojit tuto masku s rutinou **vkládání do databáze**, která ukládá jen poslední čtyři číslice pro referenci, nebo integrujte **batch processor**, který během noci prohledá celý adresář účtenek. Můžete také prozkoumat další **OCR post‑processing** úkoly, jako je standardizace adres nebo detekce jazyka – každý z nich následuje stejný vzor, který jsme zde použili. + +Máte otázky ohledně okrajových případů, výkonu nebo toho, jak přizpůsobit kód pro jinou OCR knihovnu? Zanechte komentář níže a pojďme konverzaci posunout dál. Šťastné kódování a zůstaňte v bezpečí! + + + +![Diagram ilustrující, jak maskování čísel kreditních karet funguje v OCR pipeline](https://example.com/images/ocr-mask-flow.png "Diagram post‑processing maskování v OCR") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/czech/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..2c5e4339c --- /dev/null +++ b/ocr/czech/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-04-26 +description: Naučte se, jak měřit dobu inference v Pythonu, načíst model GGUF z Hugging + Face a optimalizovat využití GPU pro rychlejší výsledky. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: cs +og_description: Měřte čas inferencí v Pythonu načtením modelu GGUF z Hugging Face + a laděním GPU vrstev pro optimální výkon. +og_title: Měření doby inference – Načíst model GGUF a optimalizovat GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Měření doby inferencí – Načíst model GGUF a optimalizovat GPU +url: /cs/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Měření doby inference – Načtení GGUF modelu a optimalizace GPU + +Už jste někdy potřebovali **změřit dobu inference** velkého jazykového modelu, ale nevěděli jste, kde začít? Nejste sami — mnoho vývojářů narazí na stejnou překážku, když poprvé stáhnou GGUF soubor z Hugging Face a pokusí se jej spustit na smíšeném CPU/GPU nastavení. + +V tomto průvodci vás provedeme **načtením GGUF modelu**, jeho konfigurací pro Hugging Face a **měřením doby inference** pomocí čistého Python úryvku. Navíc vám ukážeme, jak **optimalizovat inference GPU**, aby byly vaše běhy co nejrychlejší. Žádné zbytečnosti, jen praktické řešení od začátku do konce, které můžete dnes zkopírovat a vložit. + +## Co se naučíte + +- Jak **konfigurovat model HuggingFace** pomocí `AsposeAIModelConfig`. +- Přesné kroky pro **načtení GGUF modelu** (`fp16` kvantizace) z Hugging Face hubu. +- Opakovatelný vzor pro **časování Python kódu** kolem volání inference. +- Tipy, jak **optimalizovat inference GPU** úpravou `gpu_layers`. +- Očekávaný výstup a jak ověřit, že vaše měření dává smysl. + +### Předpoklady + +| Požadavek | Proč je důležitý | +|-----------|-------------------| +| Python 3.9+ | Moderní syntaxe a typové nápovědy. | +| `asposeai` balíček (nebo ekvivalentní SDK) | Poskytuje `AsposeAI` a `AsposeAIModelConfig`. | +| Přístup k repozitáři Hugging Face `bartowski/Qwen2.5-3B-Instruct-GGUF` | GGUF model, který načteme. | +| GPU s alespoň 8 GB VRAM (volitelné, ale doporučené) | Umožňuje krok **optimalizovat inference GPU**. | + +Pokud jste ještě nenainstalovali SDK, spusťte: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![diagram měření doby inference](https://example.com/measure-inference-time.png){alt="diagram měření doby inference"} + +## Krok 1: Načtení GGUF modelu – Konfigurace modelu HuggingFace + +Prvním, co potřebujete, je správný konfigurační objekt, který řekne Aspose AI, kde model získat a jak s ním zacházet. Zde **načteme GGUF model** a **nastavíme parametry huggingface modelu**. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Proč je to důležité:** +- `hugging_face_repo_id` ukazuje na konkrétní GGUF soubor na Hubu. +- `fp16` snižuje šířku pásma paměti při zachování většiny věrnosti modelu. +- `gpu_layers` je ovládací prvek, který ladíte, když chcete **optimalizovat inference GPU** výkon; více vrstev na GPU obvykle znamená nižší latenci, pokud máte dostatek VRAM. + +## Krok 2: Vytvoření instance Aspose AI + +Jakmile je model popsán, vytvoříme objekt `AsposeAI`. Tento krok je přímočarý, ale právě zde SDK stáhne GGUF soubor (pokud není v cache) a připraví runtime. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Tip:** První spuštění bude trvat o několik sekund déle, protože se model stahuje a kompiluje pro GPU. Následující běhy jsou bleskově rychlé. + +## Krok 3: Spuštění inference a **měření doby inference** + +Tady je jádro tutoriálu: obalit volání inference pomocí `time.time()` pro **měření doby inference**. Také předáme malý OCR výstup, aby byl příklad samostatný. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Co byste měli vidět:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Pokud se číslo zdá vysoké, pravděpodobně běžíte většinu vrstev na CPU. To nás přivádí k dalšímu kroku. + +## Krok 4: **optimalizovat inference GPU** – Ladění `gpu_layers` + +Někdy je výchozí `gpu_layers=40` buď příliš agresivní (způsobí OOM), nebo příliš konzervativní (nevyužije výkon). Zde je rychlá smyčka, kterou můžete použít k nalezení optimálního bodu: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Proč to funguje:** +- Každé volání přestaví runtime s jinou alokací GPU, což vám okamžitě ukáže kompromis latence. +- Smyčka také demonstruje **časování python kódu** opakovaně použitelným způsobem, který můžete přizpůsobit pro jiné výkonnostní testy. + +Typický výstup na 16 GB RTX 3080 může vypadat takto: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +Z toho byste zvolili `gpu_layers=40` jako optimální nastavení pro tento hardware. + +## Kompletní funkční příklad + +Spojením všeho dohromady, zde je jediný skript, který můžete uložit do souboru (`measure_inference.py`) a spustit: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Spusťte jej pomocí: + +```bash +python measure_inference.py +``` + +Měli byste vidět latenci pod jednou sekundou na slušném GPU, což potvrzuje, že jste úspěšně **měřili dobu inference** a **optimalizovali inference GPU**. + +--- + +## Často kladené otázky (FAQ) + +**Q: Funguje to i s jinými kvantizačními formáty?** +A: Rozhodně. Vyměňte `hugging_face_quantization="int8"` (nebo `q4_0`, atd.) v konfiguraci a znovu spusťte benchmark. Očekávejte kompromis: nižší spotřeba paměti vs. mírný pokles přesnosti. + +**Q: Co když nemám GPU?** +A: Nastavte `gpu_layers=0`. Kód přejde kompletně na CPU a stále budete moci **měřit dobu inference** — očekávejte jen vyšší čísla. + +**Q: Můžu časovat jen samotný průchod modelem, bez post‑processingu?** +A: Ano. Zavolejte přímo `ai_engine.run_model(...)` (nebo ekvivalentní metodu) a obalte toto volání `time.time()`. Vzor pro **časování python kódu** zůstává stejný. + +--- + +## Závěr + +Nyní máte kompletní, připravené ke kopírování řešení pro **měření doby inference** GGUF modelu, **načtení gguf modelu** z Hugging Face a ladění **optimalizovat inference GPU** nastavení. Úpravou `gpu_layers` a experimentováním s kvantizací můžete vytlačit každou milisekundu výkonu. + +Další kroky, které můžete zvážit: + +- Integrace této logiky měření do CI pipeline pro zachycení regresí. +- Prozkoumání batch inference pro další zvýšení propustnosti. +- Spojení modelu se skutečným OCR pipeline místo dummy textu, který jsme zde použili. + +Šťastné programování a ať vaše latence zůstane vždy nízká! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/czech/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..bc302253a --- /dev/null +++ b/ocr/czech/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-04-26 +description: Rozpoznávejte ručně psaný text pomocí OCR enginu v Pythonu. Naučte se, + jak extrahovat text z obrázku, zapnout režim pro ručně psaný text a rychle číst + ručně psané poznámky. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: cs +og_description: Rozpoznávejte ručně psaný text pomocí Pythonu. Tento tutoriál ukazuje, + jak extrahovat text z obrázku, zapnout režim ručního psaní a číst ručně psané poznámky + pomocí jednoduchého OCR enginu. +og_title: Rozpoznat ručně psaný text v Pythonu – Kompletní průvodce OCR +tags: +- OCR +- Python +- Handwriting Recognition +title: Rozpoznání rukopisného textu v Pythonu – tutoriál OCR enginu +url: /cs/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# rozpoznávání ručně psaného textu v Pythonu – OCR Engine Tutorial + +Už jste někdy potřebovali **rozpoznat ručně psaný text**, ale nevěděli, kde začít? Nejste v tom sami. Ať už digitalizujete poznámky ze schůzek nebo získáváte data ze skenovaného formuláře, získat spolehlivý výsledek OCR může připadat jako honění jednorožce. + +Dobrá zpráva: s několika řádky Pythonu můžete **extrahovat text z obrázku**, **zapnout režim ručně psaného textu** a konečně **číst ručně psané poznámky** bez hledání neznámých knihoven. V tomto průvodci projdeme celý proces, od nastavení ve stylu **create OCR engine python** až po vytištění výsledku na obrazovku. + +## Co se naučíte + +- Jak vytvořit instanci **create OCR engine python** pomocí balíčku `ocr`. +- Které nastavení jazyka poskytuje vestavěnou podporu pro ručně psaný text. +- Přesné volání **turn on handwritten mode**, aby engine věděl, že pracujete s kurzívou. +- Jak předat obrázek poznámky a **rozpoznat ručně psaný text**. +- Tipy pro práci s různými formáty obrázků, řešení běžných problémů a rozšíření řešení. + +Žádné zbytečnosti, žádné „viz dokumentaci“ slepé uličky – jen kompletní, spustitelný skript, který můžete dnes zkopírovat, vložit a otestovat. + +## Předpoklady + +1. Python 3.8+ nainstalován (kód používá f‑stringy). +2. Hypotetická knihovna `ocr` (`pip install ocr‑engine` – nahraďte skutečným názvem balíčku, který používáte). +3. Čistý soubor obrázku ručně psané poznámky (funguje JPEG, PNG nebo TIFF). +4. Mírná dávka zvědavosti – vše ostatní je popsáno níže. + +> **Pro tip:** Pokud je váš obrázek šumivý, proveďte rychlý předzpracovatelský krok pomocí Pillow (např. `Image.open(...).convert('L')`) před odesláním do OCR engine. Často to zvyšuje přesnost. + +## Jak rozpoznat ručně psaný text pomocí Pythonu + +Níže je celý skript, který **creates OCR engine python** objekty, konfiguruje je pro ručně psaný text a vytiskne extrahovaný řetězec. Uložte jej jako `handwriting_ocr.py` a spusťte z terminálu. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Očekávaný výstup + +Když skript úspěšně proběhne, uvidíte něco jako: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Pokud OCR engine nedokáže detekovat žádné znaky, pole `text` bude prázdný řetězec. V takovém případě zkontrolujte kvalitu obrázku nebo zkuste sken s vyšším rozlišením. + +## Vysvětlení krok za krokem + +### Krok 1 – instance **create OCR engine python** + +Třída `OcrEngine` je vstupní bod. Představte si ji jako prázdný zápisník – nic se nestane, dokud mu neřeknete, jaký jazyk očekávat a zda pracujete s ručně psaným textem. + +### Krok 2 – Vyberte jazyk, který podporuje ručně psaný text + +`ocr.Language.EXTENDED_LATIN` není jen „angličtina“. Obsahuje sadu latinských skriptů a, co je klíčové, zahrnuje modely trénované na vzorcích kurzívy. Přeskočení tohoto kroku často vede k nečitelné výstupu, protože engine výchozí používá model pro tištěný text. + +### Krok 3 – **turn on handwritten mode** + +Volání `enable_handwritten_mode(True)` přepne vnitřní příznak. Engine pak přepne na svůj neuronový síť, která je naladěna na nepravidelné mezery a proměnlivé šířky tahů, které vidíte v reálných poznámkách. Zapomenutí tohoto řádku je častá chyba; engine bude vaše skici považovat za šum. + +### Krok 4 – Předání obrázku a **recognize handwritten text** + +`recognize_image` dělá těžkou práci: předzpracuje bitmapu, spustí ji přes model pro ručně psaný text a vrátí objekt s atributem `text`. Můžete také zkontrolovat `handwritten_result.confidence`, pokud potřebujete měřítko kvality. + +### Krok 5 – Vytiskněte výsledek a **read handwritten notes** + +`print(handwritten_result.text)` je nejjednodušší způsob, jak ověřit, že jste úspěšně **extract text from image**. V produkci pravděpodobně uložíte řetězec do databáze nebo jej předáte jiné službě. + +## Řešení okrajových případů a běžných variant + +| Situace | Co dělat | +|-----------|------------| +| **Obrázek je otočen** | Použijte Pillow k otočení (`Image.rotate(angle)`) před voláním `recognize_image`. | +| **Nízký kontrast** | Převést na odstíny šedi a aplikovat adaptivní prahování (`Image.point(lambda p: p > 128 and 255)`). | +| **Více stránek** | Procházet seznam souborových cest a spojovat výsledky. | +| **Není‑latinské skripty** | Nahradit `EXTENDED_LATIN` za `ocr.Language.CHINESE` (nebo vhodný) a zachovat `enable_handwritten_mode(True)`. | +| **Obavy o výkon** | Znovu použít stejnou instanci `ocr_engine` pro mnoho obrázků; inicializace pokaždé přidává režii. | + +### Pro tip pro správu paměti + +Pokud zpracováváte stovky poznámek najednou, po dokončení zavolejte `ocr_engine.dispose()`. Uvolní nativní zdroje, které může Python wrapper držet. + +## Rychlé vizuální shrnutí + +![příklad rozpoznání ručně psaného textu](https://example.com/handwritten-note.png "příklad rozpoznání ručně psaného textu") + +*Obrázek výše ukazuje typickou ručně psanou poznámku, kterou náš skript dokáže převést na prostý text.* + +## Kompletní funkční příklad (jednosouborový skript) + +Pro ty, kteří milují jednoduchost copy‑paste, zde je celé znovu bez vysvětlujících komentářů: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Spusťte jej pomocí: + +```bash +python handwriting_ocr.py +``` + +Nyní byste měli vidět výstup **recognize handwritten text** ve vaší konzoli. + +## Závěr + +Právě jsme pokryli vše, co potřebujete k **recognize handwritten text** v Pythonu – od čerstvého volání **create OCR engine python**, výběru správného jazyka, **turn on handwritten mode**, až po **extract text from image** a **read handwritten notes**. + +V jediném, samostatném skriptu můžete přejít od rozmazané fotografie schůzkových čmáranic k čistému, prohledávatelnému textu. Dále můžete výstup poslat do pipeline pro zpracování přirozeného jazyka, uložit do prohledávatelného indexu nebo dokonce vrátit zpět do transkripční služby pro generování hlasového přehrávání. + +### Kam dál? + +- **Zpracování dávky:** Zabalte skript do smyčky pro zpracování složky se skeny. +- **Filtrování podle důvěryhodnosti:** Použijte `result.confidence` k odfiltrování nízkokvalitních čtení. +- **Alternativní knihovny:** Pokud `ocr` není ideální, prozkoumejte `pytesseract` s `--psm 13` pro režim ručně psaného textu. +- **Integrace UI:** Kombinujte s Flask nebo FastAPI pro nabídku webové služby nahrávání. + +Máte otázky ohledně konkrétního formátu obrázku nebo potřebujete pomoc s laděním modelu? Zanechte komentář níže a šťastné kódování! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/dutch/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..e4a03d853 --- /dev/null +++ b/ocr/dutch/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-04-26 +description: Leer hoe je een HuggingFace‑model in Python downloadt en tekst uit een + afbeelding haalt in Python, terwijl je de OCR‑nauwkeurigheid in Python verbetert + met Aspose OCR Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: nl +og_description: download huggingface model python en verbeter je OCR-pijplijn. Volg + deze gids om tekst uit een afbeelding te extraheren met python en de OCR-nauwkeurigheid + te verbeteren met python. +og_title: Download huggingface‑model Python – Complete OCR‑verbeteringshandleiding +tags: +- OCR +- HuggingFace +- Python +- AI +title: download huggingface model python – Stap‑voor‑stap OCR Boost-gids +url: /nl/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – Complete OCR-verbeteringshandleiding + +Heb je ooit geprobeerd om **download HuggingFace model python** en voelde je je een beetje verloren? Je bent niet de enige. In veel projecten is de grootste bottleneck het krijgen van een goed model op je machine en vervolgens de OCR‑resultaten echt bruikbaar maken. + +In deze gids lopen we stap voor stap door een hands‑on voorbeeld dat je precies laat zien hoe je **download HuggingFace model python**, tekst uit een afbeelding haalt met **extract text from image python**, en vervolgens **improve OCR accuracy python** verbetert met de AI‑post‑processor van Aspose. Aan het einde heb je een kant‑klaar script dat een ruisvolle factuurafbeelding omzet in schone, leesbare tekst—geen magie, alleen duidelijke stappen. + +## Wat je nodig hebt + +- Python 3.9+ (de code werkt ook op 3.11) +- Een internetverbinding voor de eenmalige model‑download +- Het `asposeocrcloud`‑pakket (`pip install asposeocrcloud`) +- Een voorbeeldafbeelding (bijv. `sample_invoice.png`) geplaatst in een map die jij beheert + +Dat is alles—geen zware frameworks, geen GPU‑specifieke drivers tenzij je de snelheid wilt verhogen. + +Laten we nu duiken in de daadwerkelijke implementatie. + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## Stap 1: Stel de OCR-engine in en kies een taal +*(Dit is waar we beginnen met **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Waarom dit belangrijk is:** +De OCR-engine is de eerste verdedigingslinie; het kiezen van het juiste taalpakket vermindert direct fouten in tekenherkenning, wat een kernonderdeel is van **improve OCR accuracy python**. + +## Stap 2: Configureer het AsposeAI-model – Downloaden van HuggingFace +*(Hier downloaden we daadwerkelijk **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**Wat er onder de motorkap gebeurt:** +Wanneer `allow_auto_download` waar is, maakt de SDK contact met HuggingFace, haalt het `Qwen2.5‑3B‑Instruct‑GGUF`‑model op en slaat het op in de map die je hebt opgegeven. Dit is de kern van **download huggingface model python**—de SDK doet het zware werk, zodat je zelf geen `git clone`‑ of `wget`‑commando’s hoeft te schrijven. + +*Pro tip:* Houd `directory_model_path` op een SSD voor snellere laadtijden; het model is ~3 GB zelfs in `int8`‑vorm. + +## Stap 3: Koppel de AI-engine aan de OCR-engine +*(De twee onderdelen koppelen zodat we **improve OCR accuracy python** kunnen.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Waarom ze koppelen?** +De OCR-engine levert ruwe tekst, die spelfouten, gebroken regels of verkeerde interpunctie kan bevatten. De AI-engine fungeert als een slimme editor die die problemen opruimt—exact wat je nodig hebt om **improve OCR accuracy python** te bereiken. + +## Stap 4: Voer OCR uit op je afbeelding +*(Het moment waarop we eindelijk **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` bevat nu een `text`‑attribuut met de ruwe tekens die de engine heeft gezien. In de praktijk merk je een paar haperingen—misschien is “Invoice” veranderd in “Inv0ice” of staat er een regelbreuk midden in een zin. + +## Stap 5: Opruimen met de AI Post‑Processor +*(Deze stap verbetert direct **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +Het AI‑model herschrijft de tekst en past taal‑bewuste correcties toe. Omdat we een instruction‑tuned model van HuggingFace gebruiken, is de output meestal vloeiend en klaar voor verdere verwerking. + +## Stap 6: Toon voor en na +*(Een snelle controle om te zien hoe goed we **extract text from image python** en **improve OCR accuracy python**.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Verwachte output + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Let op hoe de AI “Inv0ice” corrigeerde naar “Invoice” en losse regelbreuken gladstrijkt. Dat is het tastbare resultaat van **improve OCR accuracy python** met een gedownload HuggingFace‑model. + +## Veelgestelde vragen (FAQ) + +### Heb ik een GPU nodig om het model uit te voeren? +Nee. De instelling `gpu_layers=20` vertelt de SDK om tot 20 GPU‑lagen te gebruiken als er een compatibele GPU aanwezig is; anders valt hij terug op de CPU. Op een moderne laptop verwerkt de CPU‑route nog steeds enkele honderden tokens per seconde—perfect voor incidentele factuur‑parsing. + +### Wat als het model niet kan downloaden? +Zorg ervoor dat je omgeving `https://huggingface.co` kan bereiken. Als je achter een bedrijfsproxy zit, stel dan de omgevingsvariabelen `HTTP_PROXY` en `HTTPS_PROXY` in. De SDK zal automatisch opnieuw proberen, maar je kunt ook handmatig `git lfs pull` uitvoeren naar `directory_model_path`. + +### Kan ik het model vervangen door een kleiner model? +Zeker. Vervang gewoon `hugging_face_repo_id` door een andere repo (bijv. `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) en pas `hugging_face_quantization` dienovereenkomstig aan. Kleinere modellen downloaden sneller en verbruiken minder RAM, hoewel je mogelijk iets van de correctiekwaliteit verliest. + +### Hoe helpt dit me **extract text from image python** in andere domeinen? +Dezelfde pipeline werkt voor bonnetjes, paspoorten of handgeschreven notities. De enige wijziging is het taalpakket (`ocr.Language.FRENCH`, enz.) en eventueel een domeinspecifiek fijn‑afgestemd model van HuggingFace. + +## Bonus: Meerdere bestanden automatiseren + +Als je een map vol afbeeldingen hebt, wikkel dan de OCR‑aanroep in een eenvoudige lus: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +Deze kleine toevoeging laat je **download huggingface model python** één keer doen, waarna je tientallen bestanden in batch kunt verwerken—ideaal om je document‑automatiseringspipeline op te schalen. + +## Conclusie + +We hebben zojuist een compleet, end‑to‑end voorbeeld doorlopen dat laat zien hoe je **download HuggingFace model python**, **extract text from image python**, en **improve OCR accuracy python** kunt uitvoeren met Aspose’s OCR Cloud en een AI‑post‑processor. Het script staat klaar om te draaien, de concepten zijn uitgelegd, en je hebt de voor‑en‑na‑output gezien zodat je weet dat het werkt. + +Wat nu? Probeer een ander HuggingFace‑model, experimenteer met andere taalpakketten, of voer de opgeschoonde tekst in een downstream NLP‑pipeline (bijv. entiteitsextractie voor factuurlijnen). De mogelijkheden zijn eindeloos, en de basis die je net hebt gelegd is solide. + +Heb je vragen of een lastig beeld dat de OCR nog steeds laat haperen? Laat een reactie achter hieronder, en laten we samen het probleem oplossen. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/dutch/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..443e59adb --- /dev/null +++ b/ocr/dutch/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-04-26 +description: Download OCR‑model snel met Aspose OCR Python. Leer hoe je de modelmap + instelt, het modelpad configureert en hoe je het model in een paar regels downloadt. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: nl +og_description: Download OCR‑model in seconden met Aspose OCR Python. Deze gids laat + zien hoe je de modelmap instelt, het modelpad configureert en hoe je het model veilig + downloadt. +og_title: download OCR‑model – Complete Aspose OCR Python‑tutorial +tags: +- OCR +- Python +- Aspose +title: download OCR‑model met Aspose OCR Python – Stapsgewijze handleiding +url: /nl/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – Complete Aspose OCR Python Tutorial + +Heb je je ooit afgevraagd hoe je **download ocr model** kunt gebruiken met Aspose OCR in Python zonder eindeloos door documentatie te hoeven zoeken? Je bent niet de enige. Veel ontwikkelaars lopen tegen een muur aan wanneer het model niet lokaal aanwezig is en de SDK een cryptische foutmelding geeft. Het goede nieuws? De oplossing bestaat uit een handvol regels code en je hebt het model binnen enkele minuten klaar voor gebruik. + +In deze tutorial lopen we alles door wat je moet weten: van het importeren van de juiste classes, tot **set model directory**, tot daadwerkelijk **how to download model**, en uiteindelijk het verifiëren van het pad. Aan het einde kun je OCR uitvoeren op elke afbeelding met één functieaanroep, en begrijp je de **configure model path**‑opties die je project overzichtelijk houden. Geen poespas, alleen een praktisch, uitvoerbaar voorbeeld voor **aspose ocr python**‑gebruikers. + +## What You’ll Learn + +- Hoe je de Aspose OCR Cloud‑classes correct importeert. +- De exacte stappen om **download ocr model** automatisch te downloaden. +- Manieren om **set model directory** en **configure model path** in te stellen voor reproduceerbare builds. +- Hoe je kunt verifiëren dat het model is geïnitialiseerd en waar het zich op schijf bevindt. +- Veelvoorkomende valkuilen (rechten, ontbrekende mappen) en snelle oplossingen. + +### Prerequisites + +- Python 3.8+ geïnstalleerd op je machine. +- `asposeocrcloud`‑package (`pip install asposeocrcloud`). +- Schrijfrechten voor een map waarin je het model wilt opslaan (bijv. `C:\models` of `~/ocr_models`). + +--- + +## Step 1: Import Aspose OCR Cloud Classes + +Het eerste wat je nodig hebt is de juiste import‑statement. Deze haalt de classes op die modelconfiguratie en OCR‑operaties beheren. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Waarom dit belangrijk is:* `AsposeAI` is de engine die OCR uitvoert, terwijl `AsposeAIModelConfig` de engine vertelt **waar** het model moet zoeken en **of** het automatisch moet worden opgehaald. Het overslaan van deze stap of het importeren van de verkeerde module leidt tot een `ModuleNotFoundError` nog voordat je bij het downloadgedeelte komt. + +--- + +## Step 2: Define the Model Configuration (Set Model Directory & Configure Model Path) + +Nu vertellen we Aspose waar de modelbestanden moeten worden bewaard. Dit is waar je **set model directory** en **configure model path** instelt. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Tips & Gotchas** + +- **Absolute paden** voorkomen verwarring wanneer het script vanuit een andere werkmap wordt uitgevoerd. +- Op Linux/macOS kun je `"/home/you/ocr_models"` gebruiken; op Windows zet je een `r` voor de string om backslashes letterlijk te behandelen. +- Het instellen van `allow_auto_download="true"` is de sleutel tot **how to download model** zonder extra code te schrijven. + +--- + +## Step 3: Create the AsposeAI Instance Using the Configuration + +Met de configuratie klaar, maak je een instantie van de OCR‑engine. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Waarom dit belangrijk is:* Het `ocr_ai`‑object bevat nu de configuratie die we zojuist hebben gedefinieerd. Als het model niet aanwezig is, zal de volgende aanroep automatisch het downloaden starten — dit is de kern van **how to download model** op een hands‑off manier. + +--- + +## Step 4: Trigger the Model Download (If Needed) + +Voordat je OCR kunt uitvoeren, moet je ervoor zorgen dat het model daadwerkelijk op schijf staat. De methode `is_initialized()` controleert én dwingt de initialisatie af. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**Wat er onder de motorkap gebeurt** + +- De eerste `is_initialized()`‑aanroep geeft `False` omdat de modelmap leeg is. +- De `print` informeert de gebruiker dat een download op het punt staat te starten. +- De tweede aanroep dwingt Aspose om het model op te halen uit de Hugging Face‑repo die je eerder hebt opgegeven. +- Zodra het gedownload is, geeft de methode bij volgende controles `True` terug. + +**Edge case:** Als je netwerk de toegang tot Hugging Face blokkeert, zie je een uitzondering. In dat geval download je handmatig het model‑zip‑bestand, pak je het uit in `directory_model_path` en voer je het script opnieuw uit. + +--- + +## Step 5: Report the Local Path Where the Model Is Now Available + +Na het downloaden wil je waarschijnlijk weten waar de bestanden zijn neergezet. Dit helpt bij debugging en bij het opzetten van CI‑pipelines. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Typische output ziet er als volgt uit: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Nu heb je succesvol **download ocr model**, de directory ingesteld en het pad bevestigd. + +--- + +## Visual Overview + +Hieronder staat een eenvoudige diagram die de stroom van configuratie naar een kant‑en‑klaar model toont. + +![download ocr model stroomdiagram dat configuratie, automatische download en lokaal pad toont](/images/download-ocr-model-flow.png) + +*Alt‑tekst bevat het primaire zoekwoord voor SEO.* + +--- + +## Common Variations & How to Handle Them + +### 1. Using a Different Model Repository + +Als je een ander model nodig hebt dan `openai/gpt2`, vervang je simpelweg de waarde van `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Zorg ervoor dat de repository openbaar is of dat je het benodigde token in je omgeving hebt ingesteld. + +### 2. Disabling Automatic Download + +Soms wil je de download zelf beheren (bijv. in lucht‑gesloten omgevingen). Stel `allow_auto_download` in op `"false"` en roep een aangepast download‑script aan voordat je initialiseert: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Changing the Model Directory at Runtime + +Je kunt het pad opnieuw configureren zonder het `AsposeAI`‑object opnieuw te maken: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Pro Tips for Production Use + +- **Cache het model**: Plaats de map op een gedeelde netwerkschijf als meerdere services hetzelfde model nodig hebben. Dit voorkomt overbodige downloads. +- **Versie‑pinning**: De Hugging Face‑repo kan worden bijgewerkt. Om vast te pinnen op een specifieke versie, voeg `@v1.0.0` toe aan de repo‑ID (`"openai/gpt2@v1.0.0"`). +- **Rechten**: Zorg dat de gebruiker die het script uitvoert lees‑/schrijfrechten heeft op `directory_model_path`. Op Linux is `chmod 755` meestal voldoende. +- **Logging**: Vervang de eenvoudige `print`‑statements door Python’s `logging`‑module voor betere observability in grotere applicaties. + +--- + +## Full Working Example (Copy‑Paste Ready) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Verwachte output** (eerste uitvoering downloadt, latere uitvoeringen slaan het downloaden over): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Voer het script opnieuw uit; je ziet alleen de pad‑regel omdat het model al in de cache staat. + +--- + +## Conclusion + +We hebben zojuist het volledige proces behandeld om **download ocr model** te gebruiken met Aspose OCR Python, laten zien hoe je **set model directory** instelt, en de nuances van **configure model path** uitgelegd. Met slechts een paar regels code kun je het downloaden automatiseren, handmatige stappen vermijden en je OCR‑pipeline reproduceerbaar houden. + +Vervolgens kun je de daadwerkelijke OCR‑aanroep (`ocr_ai.recognize_image(...)`) verkennen of experimenteren met een ander Hugging Face‑model om de nauwkeurigheid te verbeteren. Hoe dan ook, de basis die je hier hebt gelegd — duidelijke configuratie, automatische download en pad‑verificatie — maakt elke toekomstige integratie een fluitje van een cent. + +Heb je vragen over randgevallen, of wil je delen hoe jij de modeldirectory hebt aangepast voor cloud‑deployments? Laat een reactie achter, en happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/dutch/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..dd34a0632 --- /dev/null +++ b/ocr/dutch/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-26 +description: Hoe OCR‑resultaten post‑processen en tekst met coördinaten extraheren. + Leer een stapsgewijze oplossing met gestructureerde output en AI‑correctie. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: nl +og_description: Hoe OCR‑resultaten post‑processen en tekst met coördinaten extraheren. + Volg deze uitgebreide tutorial voor een betrouwbare workflow. +og_title: Hoe OCR nabewerken – Complete gids +tags: +- OCR +- Python +- AI +- Text Extraction +title: Hoe OCR nabewerken – Tekst met coördinaten extraheren in Python +url: /nl/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe OCR na‑verwerken – Tekst met coördinaten extraheren in Python + +Heb je ooit **hoe OCR na‑verwerken** moeten doen omdat de ruwe output ruisig of mis‑aligned was? Je bent niet de enige. In veel real‑world projecten—factuurscanning, bondigitalisatie, of zelfs het verrijken van AR‑ervaringen—geeft de OCR‑engine je ruwe woorden, maar moet je ze nog opschonen en bijhouden waar elk woord zich op de pagina bevindt. Dat is waar een gestructureerde output‑modus gecombineerd met een AI‑gedreven post‑processor schittert. + +In deze tutorial lopen we een complete, uitvoerbare Python‑pipeline door die **tekst met coördinaten** uit een afbeelding haalt, een AI‑gebaseerde correctiestap uitvoert, en elk woord samen met zijn (x, y)‑positie afdrukt. Geen ontbrekende imports, geen vage “zie de docs” shortcuts—gewoon een zelfstandige oplossing die je vandaag nog in je project kunt gebruiken. + +> **Pro tip:** Als je een andere OCR‑bibliotheek gebruikt, zoek dan naar een “structured” of “layout”‑modus; de concepten blijven hetzelfde. + +--- + +## Vereisten + +Voordat we beginnen, zorg dat je het volgende hebt: + +| Vereiste | Waarom het belangrijk is | +|----------|--------------------------| +| Python 3.9+ | Moderne syntax en type hints | +| `ocr`‑bibliotheek die `OutputMode.STRUCTURED` ondersteunt (bijv. een fictieve `myocr`) | Nodig voor bounding‑box‑data | +| Een AI‑post‑processing module (kan OpenAI, HuggingFace, of een aangepast model zijn) | Verbetert de nauwkeurigheid na OCR | +| Een afbeeldingsbestand (`input.png`) in je werkmap | De bron die we gaan lezen | + +Als een van deze onbekend klinkt, installeer dan de placeholder‑pakketten met `pip install myocr ai‑postproc`. De code hieronder bevat ook fallback‑stubs zodat je de flow kunt testen zonder de echte bibliotheken. + +--- + +## Stap 1: Gestructureerde output‑modus inschakelen voor de OCR‑engine + +Het eerste wat we doen is de OCR‑engine vertellen meer dan alleen platte tekst te geven. Gestructureerde output levert elk woord samen met zijn omhullende rechthoek en confidence‑score, wat essentieel is voor **tekst met coördinaten extraheren** later. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Waarom dit belangrijk is:* Zonder gestructureerde modus krijg je alleen een lange string, en verlies je de ruimtelijke informatie die je nodig hebt om tekst op afbeeldingen te overlayen of downstream layout‑analyse te voeren. + +--- + +## Stap 2: De afbeelding herkennen en woorden, vakken en confidence vastleggen + +Nu voeren we de afbeelding in de engine. Het resultaat is een object dat een lijst van woordobjecten bevat, elk met `text`, `x`, `y`, `width`, `height` en `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Randgeval:* Als de afbeelding leeg of onleesbaar is, zal `structured_result.words` een lege lijst zijn. Het is goed om dat te controleren en netjes af te handelen. + +--- + +## Stap 3: AI‑gebaseerde post‑processing uitvoeren terwijl posities behouden blijven + +Zelfs de beste OCR‑engines maken fouten—denk aan “O” vs. “0” of ontbrekende diakritische tekens. Een AI‑model getraind op domeinspecifieke tekst kan die fouten corrigeren. Cruciaal is dat we de oorspronkelijke coördinaten behouden zodat de ruimtelijke lay-out intact blijft. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Waarom we coördinaten behouden:* Veel downstream‑taken (bijv. PDF‑generatie, AR‑labeling) vertrouwen op exacte plaatsing. De AI wijzigt alleen het `text`‑veld, en laat `x`, `y`, `width`, `height` onaangeroerd. + +--- + +## Stap 4: Over de gecorrigeerde woorden itereren en hun tekst met coördinaten weergeven + +Tot slot lopen we door de gecorrigeerde woorden en printen elk woord samen met zijn linkerbovenhoek `(x, y)`. Dit voldoet aan het doel **tekst met coördinaten extraheren**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Verwachte output (voorbeeld):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Elke regel toont het gecorrigeerde woord en de exacte locatie op de originele afbeelding. + +--- + +## Volledig werkend voorbeeld + +Hieronder staat één script dat alles samenbrengt. Je kunt het kopiëren‑plakken, de import‑statements aanpassen aan je eigen bibliotheken, en direct uitvoeren. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Het script uitvoeren** + +```bash +python ocr_postprocess_demo.py +``` + +Als je de echte bibliotheken geïnstalleerd hebt, verwerkt het script je `input.png`. Anders laat de stub‑implementatie je de verwachte flow en output zien zonder externe afhankelijkheden. + +--- + +## Veelgestelde vragen (FAQ) + +| Vraag | Antwoord | +|-------|----------| +| *Werkt dit met Tesseract?* | Tesseract zelf biedt geen gestructureerde modus out‑of‑the‑box, maar wrappers zoals `pytesseract.image_to_data` geven bounding boxes terug die je kunt gebruiken met dezelfde AI‑post‑processor. | +| *Wat als ik de rechteronderhoek in plaats van linkerbovenhoek nodig heb?* | Elk woordobject levert ook `width` en `height`. Bereken `x2 = x + width` en `y2 = y + height` om de tegenovergestelde hoek te krijgen. | +| *Kan ik meerdere afbeeldingen in batch verwerken?* | Zeker. Plaats de stappen in een `for image_path in Path("folder").glob("*.png"):`‑lus en verzamel resultaten per bestand. | +| *Hoe kies ik een AI‑model voor correctie?* | Voor generieke tekst werkt een kleine GPT‑2 die is gefinetuned op OCR‑fouten. Voor domeinspecifieke data (bijv. medische recepten) train je een sequence‑to‑sequence‑model op gekoppelde noisy‑clean data. | +| *Is de confidence‑score nuttig na AI‑correctie?* | Je kunt de oorspronkelijke confidence behouden voor debugging, maar de AI kan zijn eigen confidence teruggeven als het model dat ondersteunt. | + +--- + +## Randgevallen & Best Practices + +1. **Lege of corrupte afbeeldingen** – controleer altijd dat `structured_result.words` niet leeg is voordat je verder gaat. +2. **Niet‑Latijnse scripts** – zorg dat je OCR‑engine is geconfigureerd voor de doeltaal; de AI‑post‑processor moet op hetzelfde script getraind zijn. +3. **Prestaties** – AI‑correctie kan duur zijn. Cache resultaten als je dezelfde afbeelding opnieuw gebruikt, of voer de AI‑stap asynchroon uit. +4. **Coördinatensysteem** – OCR‑bibliotheken kunnen verschillende oorsprongen gebruiken (linkerboven vs. linksonder). Pas dit aan bij het overlayen op PDF’s of canvassen. + +--- + +## Conclusie + +Je hebt nu een solide, end‑to‑end recept voor **hoe OCR na‑verwerken** en betrouwbaar **tekst met coördinaten extraheren**. Door gestructureerde output in te schakelen, het resultaat door een AI‑correctielaag te voeren, en de oorspronkelijke bounding boxes te behouden, kun je ruisige OCR‑scans omzetten in schone, ruimtelijk‑bewuste tekst die klaar is voor downstream‑taken zoals PDF‑generatie, data‑invoer‑automatisering, of augmented‑reality overlays. + +Klaar voor de volgende stap? Probeer de stub‑AI te vervangen door een OpenAI `gpt‑4o‑mini`‑call, of integreer de pipeline in een FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/dutch/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..557f1c964 --- /dev/null +++ b/ocr/dutch/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-26 +description: Hoe herken je afbeeldingen snel met Python. Leer een beeldherkenningspipeline, + batchverwerking en automatiseer beeldherkenning met AI. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: nl +og_description: Hoe herken je afbeeldingen snel met Python. Deze gids loopt door een + beeldherkenningspipeline, batchverwerking en automatisering met AI. +og_title: Hoe afbeeldingen te herkennen – Automatiseer een beeldherkenningspipeline +tags: +- image-processing +- python +- ai +title: Hoe afbeeldingen te herkennen – Automatiseer een beeldherkenningspipeline +url: /nl/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe afbeeldingen te herkennen – Automatiseer een afbeeldingherkenningspipeline + +Heb je je ooit afgevraagd **hoe je afbeeldingen kunt herkennen** zonder duizenden regels code te schrijven? Je bent niet de enige—veel ontwikkelaars lopen tegen dezelfde muur aan wanneer ze voor het eerst tientallen of honderden foto's moeten verwerken. Het goede nieuws? Met een paar nette stappen kun je een volledige afbeeldingherkenningspipeline opzetten die batcht, uitvoert en zelf alles opruimt. + +In deze tutorial lopen we een compleet, uitvoerbaar voorbeeld door dat laat zien **hoe je afbeeldingen batcht**, elke afbeelding aan een AI‑engine voert, de resultaten post‑processen en uiteindelijk resources vrijgeeft. Aan het einde heb je een zelfstandige script die je in elk project kunt gebruiken, of je nu een foto‑tagger, een kwaliteitscontrolesysteem of een dataset‑generator voor onderzoek bouwt. + +## Wat je zult leren + +- **Hoe je afbeeldingen kunt herkennen** met een mock AI‑engine (het patroon is identiek voor echte services zoals TensorFlow, PyTorch of cloud‑API’s). +- Hoe je een **afbeeldingherkenningspipeline** bouwt die batches efficiënt afhandelt. +- De beste manier om **afbeeldingherkenning te automatiseren** zodat je niet elke keer handmatig over bestanden hoeft te loopen. +- Tips voor het schalen van de pipeline en het veilig vrijgeven van resources. + +> **Prerequisites:** Python 3.8+, basiskennis van functies en loops, en een handvol afbeeldingsbestanden (of paden) die je wilt verwerken. Er zijn geen externe bibliotheken nodig voor het kernvoorbeeld, maar we noemen waar je echte AI‑SDK’s kunt aansluiten. + +![Diagram van hoe afbeeldingen te herkennen in een batchverwerkingspipeline](pipeline.png "Diagram van hoe afbeeldingen te herkennen") + +## Stap 1: Batch je afbeeldingen – Hoe afbeeldingen efficiënt te batchen + +Voordat de AI enige zware taak uitvoert, heb je een collectie afbeeldingen nodig om aan te voeren. Beschouw dit als je boodschappenlijst; de engine zal later elk item één voor één van de lijst halen. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Waarom batchen?** +Batchen vermindert de hoeveelheid boilerplate‑code die je moet schrijven en maakt het triviaal om later parallelisme toe te voegen. Als je ooit 10 000 afbeeldingen moet verwerken, wijzig je alleen de bron van `image_batch`—de rest van de pipeline blijft ongewijzigd. + +## Stap 2: Voer de afbeeldingherkenningspipeline uit (Afbeeldingen herkennen met AI) + +Nu koppelen we de batch aan de daadwerkelijke recognizer. In een real‑world scenario zou je `torchvision.models` of een cloud‑endpoint aanroepen; hier simuleren we het gedrag zodat de tutorial zelfstandig blijft. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Explanation:** +- `engine.recognize_image` is het hart van de **afbeeldingherkenningspipeline**; het kan een aanroep zijn naar een deep‑learning model of een REST‑API. +- `postprocessor.run` demonstreert **automate image recognition** door ruwe voorspellingen te normaliseren naar een nette dictionary die je kunt opslaan of streamen. +- We verzamelen elke `corrected` dict in `recognized_results` zodat downstream stappen (bijv. database‑invoeging) eenvoudig zijn. + +## Stap 3: Post‑process en opslaan – Automatiseer afbeeldingherkenningsresultaten + +Nadat je een nette lijst met voorspellingen hebt, wil je ze meestal bewaren. Het voorbeeld hieronder schrijft een CSV‑bestand; voel je vrij om een database of berichtwachtrij in te schakelen. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Waarom een CSV?** +CSV is universeel leesbaar—Excel, pandas, zelfs gewone teksteditors kunnen het openen. Als je later **automate image recognition** op schaal nodig hebt, vervang je het schrijfblok door een bulk‑insert naar je data‑lake. + +## Stap 4: Opruimen – AI‑resources veilig vrijgeven + +Veel AI‑SDK’s reserveren GPU‑geheugen of starten worker‑threads. Het vergeten om ze vrij te geven kan leiden tot geheugenlekken en nare crashes. Ook al hebben onze mock‑objecten dat niet nodig, we laten het juiste patroon zien. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +Het uitvoeren van het script print een vriendelijke bevestiging, zodat je weet dat de pipeline netjes is afgerond. + +## Volledig werkend script + +Alles bij elkaar genomen, hier is het complete, copy‑and‑paste‑klare programma: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Verwachte output + +Wanneer je het script uitvoert (ervan uitgaande dat de drie placeholder‑paden bestaan), zie je iets als: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +En het gegenereerde `recognition_results.csv` zal bevatten: + +| afbeelding | label | vertrouwen | +|---------------------|-------|------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Conclusie + +Je hebt nu een solide, end‑to‑end voorbeeld van **hoe je afbeeldingen kunt herkennen** in Python, compleet met een **afbeeldingherkenningspipeline**, batch‑afhandeling en geautomatiseerde post‑processing. Het patroon schaalt: vervang de mock‑klassen door een echt model, voer een grotere `image_batch` in, en je hebt een productie‑klare oplossing. + +Wil je verder gaan? Probeer de volgende stappen: + +- Vervang `MockEngine` door een TensorFlow‑ of PyTorch‑model voor echte voorspellingen. +- Paralleliseer de loop met `concurrent.futures.ThreadPoolExecutor` om grote batches te versnellen. +- Koppel de CSV‑writer aan een cloud‑storage bucket om **automate image recognition** over gedistribueerde workers uit te voeren. + +Voel je vrij om te experimenteren, dingen kapot te maken en ze vervolgens te repareren—that’s how you truly master image recognition pipelines. Als je ergens vastloopt of ideeën hebt voor verbeteringen, laat dan een reactie achter. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/dutch/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..9af6137cb --- /dev/null +++ b/ocr/dutch/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,251 @@ +--- +category: general +date: 2026-04-26 +description: Maskeer creditcardnummers snel met AsposeAI OCR‑nabewerking. Leer PCI‑compliance, + masking met reguliere expressies en gegevenssanitatie in een stapsgewijze tutorial. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: nl +og_description: Maskeer creditcardnummers in OCR‑resultaten met AsposeAI. Deze tutorial + behandelt PCI‑naleving, maskering met reguliere expressies en gegevenssanitatie. +og_title: Creditcardnummers maskeren – Complete Python OCR-nabewerkingsgids +tags: +- OCR +- Python +- security +title: Maskeer creditcardnummers in OCR‑uitvoer – Complete Python‑gids +url: /nl/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Creditcardnummers maskeren – Complete Python-gids + +Heb je ooit **creditcardnummers moeten maskeren** in tekst die rechtstreeks uit een OCR‑engine komt? Je bent niet de enige. In gereguleerde sectoren kan het blootstellen van een volledige PAN (Primary Account Number) je in de problemen brengen bij PCI‑compliance‑auditors. Het goede nieuws? Met een paar regels Python en de post‑processing‑hook van AsposeAI kun je automatisch de middelste acht cijfers verbergen en veilig blijven. + +In deze tutorial lopen we door een real‑world scenario: OCR uitvoeren op een bonafbeelding, vervolgens een aangepaste **OCR post‑processing** functie toepassen die alle PCI‑gegevens sanitiseert. Aan het einde heb je een herbruikbare snippet die je in elke AsposeAI‑workflow kunt plaatsen, plus een reeks praktische tips voor het omgaan met randgevallen en het opschalen van de oplossing. + +## Wat je zult leren + +- Hoe je een aangepaste post‑processor registreert bij **AsposeAI**. +- Waarom een **regular expression masking** aanpak zowel snel als betrouwbaar is. +- De basisprincipes van **PCI compliance** met betrekking tot data‑sanitization. +- Manieren om het patroon uit te breiden voor meerdere kaartformaten of internationale nummers. +- Verwachte output en hoe je kunt verifiëren dat de maskering heeft gewerkt. + +> **Prerequisites** – Je moet een werkende Python 3‑omgeving hebben, het Aspose.AI for OCR‑pakket geïnstalleerd (`pip install aspose-ocr`), en een voorbeeldafbeelding (bijv. `receipt.png`) die een creditcardnummer bevat. Er zijn geen andere externe services vereist. + +--- + +## Stap 1: Definieer een post‑processor die creditcardnummers maskert + +Het hart van de oplossing zit in een kleine functie die het OCR‑resultaat ontvangt, een **regular expression masking** routine uitvoert, en de gesaniteerde tekst retourneert. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Waarom dit werkt:** +- De regex `(\d{4})\d{8}(\d{4})` komt exact overeen met 16 opeenvolgende cijfers, het gangbare formaat voor Visa, MasterCard en vele anderen. +- Door de eerste en laatste vier cijfers vast te leggen (`\1` en `\2`) behouden we voldoende informatie voor debugging, terwijl we voldoen aan **PCI compliance** regels die het opslaan van de volledige PAN verbieden. +- De substitutie `\1****\2` verbergt de gevoelige middelste acht cijfers, waardoor `1234567812345678` wordt `1234****5678`. + +> **Pro tip:** Als je 15‑cijferige American Express‑nummers moet ondersteunen, voeg dan een tweede patroon toe zoals `r'(\d{4})\d{6}(\d{5})'` en voer beide vervangingen opeenvolgend uit. + +## Stap 2: Initialise de AsposeAI‑engine + +Voordat we onze post‑processor kunnen koppelen, hebben we een instantie van de OCR‑engine nodig. AsposeAI bundelt het OCR‑model en een eenvoudige API voor aangepaste verwerking. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Waarom hier initialiseren?** +Het één keer aanmaken van het `AsposeAI`‑object en hergebruiken ervan over meerdere afbeeldingen vermindert overhead. De engine cachet ook taalmodellen, wat latere oproepen versnelt—handig wanneer je batches bonnen scant. + +## Stap 3: Registreer de aangepaste maskeringsfunctie + +AsposeAI biedt een `set_post_processor`‑methode die je in staat stelt elke callable in te pluggen. We geven onze `mask_pci`‑functie door samen met een optioneel instellingen‑dictionary (nu leeg). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**Wat gebeurt er achter de schermen?** +Wanneer je later `run_postprocessor` aanroept, geeft AsposeAI het ruwe OCR‑resultaat door aan `mask_pci`. De functie ontvangt een lichtgewicht object (`data`) dat de herkende tekst bevat, en je retourneert een nieuwe string. Dit ontwerp houdt de kern‑OCR onaangeroerd terwijl je **data sanitization**‑beleid op één plek kunt afdwingen. + +## Stap 4: Voer OCR uit op de bonafbeelding + +Nu de engine weet hoe de output te reinigen, voeren we een afbeelding in. Voor deze tutorial gaan we ervan uit dat je al een `engine`‑object hebt geconfigureerd met de juiste taal‑ en resolutie‑instellingen. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Tip:** Als je geen vooraf geconfigureerd object hebt, kun je er een maken met: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +De `recognize_image`‑aanroep retourneert een object waarvan het `text`‑attribuut de ruwe, niet‑gemaskeerde string bevat. + +## Stap 5: Pas de geregistreerde post‑processor toe + +Met de ruwe OCR‑data in de hand, geven we deze door aan de AI‑instantie. De engine voert automatisch de `mask_pci`‑functie uit die we eerder hebben geregistreerd. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Waarom `run_postprocessor` gebruiken in plaats van de functie handmatig aan te roepen?** +Dit houdt de workflow consistent, vooral wanneer je meerdere post‑processors hebt (bijv. spell‑checking, language detection). AsposeAI plaatst ze in de volgorde waarin je ze registreert, wat een deterministische output garandeert. + +## Stap 6: Verifieer de gesaniteerde output + +Laten we tenslotte de gesaniteerde tekst afdrukken en bevestigen dat eventuele creditcardnummers correct gemaskeerd zijn. + +```python +print(final_result.text) +``` + +**Verwachte output** (excerpt): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Als de bon geen kaartnummer bevatte, blijft de tekst ongewijzigd—niets te maskeren, niets om je zorgen over te maken. + +## Randgevallen en veelvoorkomende variaties afhandelen + +### Meerdere kaartnummers in één document +Als een bon meer dan één PAN bevat (bijv. een loyaliteitskaart plus een betaalkaart), voert de regex globaal uit en maskert automatisch alle overeenkomsten. Geen extra code nodig. + +### Niet‑standaard opmaak +Soms voegt OCR spaties of streepjes in (`1234 5678 1234 5678` of `1234-5678-1234-5678`). Breid het patroon uit om die tekens te negeren: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +De toegevoegde `[ -]?` staat optionele spaties of streepjes tussen cijferblokken toe. + +### Internationale kaarten +Voor 19‑cijferige PAN's die in sommige regio's worden gebruikt, kun je het patroon verbreden: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Onthoud wel dat **PCI compliance** nog steeds vereist dat de middelste cijfers worden gemaskeerd, ongeacht de lengte. + +### Gemaskeerde waarden loggen (optioneel) +Als je audit‑trails nodig hebt, geef dan een vlag door via `custom_settings` en pas de functie aan: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Registreer vervolgens met: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +## Volledig werkend voorbeeld (klaar om te kopiëren en plakken) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Het uitvoeren van dit script op een bon die `4111111111111111` bevat, zal produceren: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +Dat is de volledige pipeline—van ruwe OCR tot **data sanitization**—verpakt in een paar nette regels Python. + +## Conclusie + +We hebben je net laten zien hoe je **creditcardnummers kunt maskeren** in OCR‑resultaten met behulp van de post‑processing‑hook van AsposeAI, een beknopte regular‑expression‑routine, en een reeks best‑practice‑tips voor **PCI compliance**. De oplossing is volledig zelfstandig, werkt met elke afbeelding die de OCR‑engine kan lezen, en kan worden uitgebreid om complexere kaartformaten of logvereisten te dekken. + +Klaar voor de volgende stap? Probeer deze maskering te koppelen aan een **database‑invoeg**‑routine die alleen de laatste vier cijfers opslaat voor referentie, of integreer een **batch‑processor** die ’s nachts een hele map bonnen scant. Je kunt ook andere **OCR post‑processing**‑taken verkennen, zoals adresstandaardisatie of taaldetectie—elk volgt hetzelfde patroon dat we hier hebben gebruikt. + +Heb je vragen over randgevallen, prestaties, of hoe je de code kunt aanpassen voor een andere OCR‑bibliotheek? Laat een reactie achter hieronder, en laten we het gesprek voortzetten. Veel plezier met coderen, en blijf veilig! + +![Diagram dat laat zien hoe het maskeren van creditcardnummers werkt in een OCR‑pipeline](https://example.com/images/ocr-mask-flow.png "Diagram van OCR post‑processing maskeringsstroom") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/dutch/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..9c82246f3 --- /dev/null +++ b/ocr/dutch/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-04-26 +description: Leer hoe je de inferentietijd in Python kunt meten, een GGUF‑model van + Hugging Face kunt laden en het GPU‑gebruik kunt optimaliseren voor snellere resultaten. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: nl +og_description: Meet de inferentietijd in Python door een GGUF‑model van Hugging Face + te laden en de GPU‑lagen af te stemmen voor optimale prestaties. +og_title: Meet inferentietijd – Laad GGUF‑model & optimaliseer GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Meet inferentietijd – Laad GGUF‑model & optimaliseer GPU +url: /nl/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Meet inferentietijd – Laad GGUF‑model & optimaliseer GPU + +Heb je ooit **inferentietijd willen meten** voor een groot taalmodel, maar wist je niet waar te beginnen? Je bent niet de enige—veel ontwikkelaars lopen tegen dezelfde muur aan wanneer ze voor het eerst een GGUF‑bestand van Hugging Face halen en proberen uit te voeren op een gemengde CPU/GPU‑setup. + +In deze gids lopen we stap voor stap door **hoe je een GGUF‑model laadt**, het configureert voor Hugging Face, en **inferentietijd meet** met een eenvoudige Python‑fragment. Onderweg laten we ook zien hoe je **GPU‑inference optimaliseert** zodat je runs zo snel mogelijk zijn. Geen poespas, alleen een praktische end‑to‑end‑oplossing die je vandaag nog kunt copy‑pasten. + +## Wat je leert + +- Hoe je een **HuggingFace‑model configureert** met `AsposeAIModelConfig`. +- De exacte stappen om een **GGUF‑model te laden** (`fp16`‑kwantisatie) van de Hugging Face hub. +- Een herbruikbaar patroon voor **het timen van Python‑code** rond een inference‑aanroep. +- Tips om **GPU‑inference te optimaliseren** door `gpu_layers` aan te passen. +- Verwachte output en hoe je kunt verifiëren dat je timing logisch is. + +### Vereisten + +| Vereiste | Waarom het belangrijk is | +|----------|--------------------------| +| Python 3.9+ | Moderne syntax en type‑hints. | +| `asposeai`‑package (of de equivalente SDK) | Biedt `AsposeAI` en `AsposeAIModelConfig`. | +| Toegang tot de Hugging Face‑repo `bartowski/Qwen2.5-3B-Instruct-GGUF` | Het GGUF‑model dat we gaan laden. | +| Een GPU met minstens 8 GB VRAM (optioneel maar aanbevolen) | Maakt de stap **GPU‑inference optimaliseren** mogelijk. | + +Als je de SDK nog niet hebt geïnstalleerd, voer dan uit: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![meet inferentietijd diagram](https://example.com/measure-inference-time.png){alt="meet inferentietijd diagram"} + +## Stap 1: Laad het GGUF‑model – Configureer HuggingFace‑model + +Het eerste wat je nodig hebt, is een juist configuratie‑object dat Aspose AI vertelt waar het model op te halen en hoe het behandeld moet worden. Hier laden we een **GGUF‑model** en **configureren we de HuggingFace‑model‑parameters**. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Waarom dit belangrijk is:** +- `hugging_face_repo_id` wijst naar het exacte GGUF‑bestand op de Hub. +- `fp16` vermindert het geheugen‑bandbreedte‑verbruik terwijl de meeste model‑fidelity behouden blijft. +- `gpu_layers` is de instelling die je aanpast wanneer je **GPU‑inference wilt optimaliseren**; meer lagen op de GPU betekenen meestal lagere latency, mits je voldoende VRAM hebt. + +## Stap 2: Maak de Aspose AI‑instantie + +Nu het model beschreven is, starten we een `AsposeAI`‑object. Deze stap is eenvoudig, maar hier downloadt de SDK daadwerkelijk het GGUF‑bestand (als het nog niet in de cache staat) en bereidt de runtime voor. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Pro‑tip:** De eerste uitvoering duurt een paar seconden langer omdat het model wordt gedownload en gecompileerd voor de GPU. Volgende runs zijn bliksemsnel. + +## Stap 3: Voer inference uit en **meet inferentietijd** + +Dit is het hart van de tutorial: de inference‑aanroep omhullen met `time.time()` om **inferentietijd te meten**. We voeren ook een klein OCR‑resultaat in om het voorbeeld zelf‑voorzienend te houden. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Wat je zou moeten zien:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Als het getal hoog lijkt, draai je waarschijnlijk de meeste lagen op de CPU. Dan gaan we verder met de volgende stap. + +## Stap 4: **GPU‑inference optimaliseren** – Stem `gpu_layers` af + +Soms is de standaard `gpu_layers=40` ofwel te agressief (OOM) of te conservatief (prestaties blijven achter). Hier is een korte loop die je kunt gebruiken om de optimale instelling te vinden: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Waarom dit werkt:** +- Elke aanroep bouwt de runtime opnieuw op met een andere GPU‑allocatie, zodat je de latency‑trade‑off direct ziet. +- De loop demonstreert ook **time python code** op een herbruikbare manier, die je kunt aanpassen voor andere prestatietests. + +Typische output op een 16 GB RTX 3080 kan er als volgt uitzien: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +Op basis daarvan kies je `gpu_layers=40` als het optimale punt voor deze hardware. + +## Volledig werkend voorbeeld + +Alles samengevoegd, hier is een enkel script dat je kunt plaatsen in een bestand (`measure_inference.py`) en uitvoeren: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Voer het uit met: + +```bash +python measure_inference.py +``` + +Je zou een sub‑seconde latency moeten zien op een degelijke GPU, wat bevestigt dat je succesvol **inferentietijd hebt gemeten** en **GPU‑inference hebt geoptimaliseerd**. + +--- + +## Veelgestelde vragen (FAQ) + +**V: Werkt dit met andere kwantisatie‑formaten?** +A: Zeker. Vervang `hugging_face_quantization="int8"` (of `q4_0`, enz.) in de configuratie en voer de benchmark opnieuw uit. Verwacht een trade‑off: minder geheugen‑gebruik versus een lichte daling in nauwkeurigheid. + +**V: Wat als ik geen GPU heb?** +A: Stel `gpu_layers=0`. De code valt volledig terug op de CPU, en je kunt nog steeds **inferentietijd meten**—verwacht gewoon hogere getallen. + +**V: Kan ik alleen de model‑forward‑pass timen, exclusief post‑processing?** +A: Ja. Roep `ai_engine.run_model(...)` (of de equivalente methode) direct aan en omhul die aanroep met `time.time()`. Het patroon voor **time python code** blijft hetzelfde. + +--- + +## Conclusie + +Je hebt nu een complete copy‑and‑paste‑oplossing om **inferentietijd te meten** voor een GGUF‑model, **GGUF‑model te laden** van Hugging Face, en **GPU‑inference te optimaliseren**. Door `gpu_layers` aan te passen en te experimenteren met kwantisatie, kun je elke milliseconde performance eruit persen. + +Wat je hierna kunt doen: + +- Deze timing‑logica integreren in een CI‑pipeline om regressies op te vangen. +- Batch‑inference verkennen om de doorvoer verder te verbeteren. +- Het model combineren met een echte OCR‑pipeline in plaats van de dummy‑tekst die we hier hebben gebruikt. + +Veel programmeerplezier, en moge je latency‑cijfers altijd laag blijven! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/dutch/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..ff943ee44 --- /dev/null +++ b/ocr/dutch/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-26 +description: herken handgeschreven tekst met de OCR‑engine van Python. Leer hoe je + tekst uit een afbeelding kunt extraheren, de handgeschreven modus inschakelt en + handgeschreven notities snel leest. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: nl +og_description: herken handgeschreven tekst met Python. Deze tutorial laat zien hoe + je tekst uit een afbeelding kunt extraheren, de handgeschreven modus inschakelt + en handgeschreven notities leest met een eenvoudige OCR‑engine. +og_title: handgeschreven tekst herkennen in Python – Complete OCR‑gids +tags: +- OCR +- Python +- Handwriting Recognition +title: handgeschreven tekst herkennen in Python – OCR Engine Handleiding +url: /nl/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# herken handgeschreven tekst in Python – OCR Engine Tutorial + +Heb je ooit **handgeschreven tekst** moeten **herkennen** maar zat je vast bij de vraag “waar moet ik beginnen?”? Je bent niet de enige. Of je nu notities van een vergadering digitaliseert of gegevens uit een gescand formulier haalt, het krijgen van een betrouwbaar OCR‑resultaat kan voelen als het najagen van een eenhoorn. + +Goed nieuws: met slechts een paar regels Python kun je **tekst uit afbeelding** bestanden **extraheren**, **handgeschreven modus inschakelen**, en eindelijk **handgeschreven notities lezen** zonder obscure bibliotheken te zoeken. In deze gids lopen we het volledige proces door, van een **create OCR engine python**‑achtige setup tot het afdrukken van het resultaat op het scherm. + +## Wat je zult leren + +- Hoe je een **create OCR engine python**‑instantie maakt met het `ocr`‑pakket. +- Welke taalinstelling ingebouwde handgeschreven ondersteuning biedt. +- De exacte aanroep om **handgeschreven modus in te schakelen** zodat de engine weet dat je met cursief werkt. +- Hoe je een foto van een notitie invoert en **handgeschreven tekst herkent**. +- Tips voor het omgaan met verschillende afbeeldingsformaten, het oplossen van veelvoorkomende valkuilen, en het uitbreiden van de oplossing. + +Geen poespas, geen “zie de docs” doodlopende routes—gewoon een compleet, uitvoerbaar script dat je vandaag nog kunt kopiëren‑plakken en testen. + +## Vereisten + +Voordat we beginnen, zorg dat je het volgende hebt: + +1. Python 3.8+ geïnstalleerd (de code gebruikt f‑strings). +2. De hypothetische `ocr`‑bibliotheek (`pip install ocr‑engine` – vervang door de echte pakketnaam die je gebruikt). +3. Een duidelijke afbeelding van een handgeschreven notitie (JPEG, PNG of TIFF werkt). +4. Een bescheiden hoeveelheid nieuwsgierigheid—alles andere wordt hieronder behandeld. + +> **Pro tip:** Als je afbeelding ruis bevat, voer dan een snelle voorbewerking uit met Pillow (bijv. `Image.open(...).convert('L')`) voordat je deze naar de OCR‑engine stuurt. Dit verbetert vaak de nauwkeurigheid. + +## Hoe handgeschreven tekst herkennen met Python + +Hieronder staat het volledige script dat **creates OCR engine python** objecten maakt, ze configureert voor handschrift, en de geëxtraheerde string afdrukt. Sla het op als `handwriting_ocr.py` en voer het uit vanuit je terminal. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Verwachte uitvoer + +Wanneer het script succesvol draait, zie je iets als: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Als de OCR‑engine geen tekens kan detecteren, zal het `text`‑veld een lege string zijn. Controleer in dat geval de beeldkwaliteit of probeer een scan met hogere resolutie. + +## Stap‑voor‑stap uitleg + +### Stap 1 – **create OCR engine python**‑instantie + +De `OcrEngine`‑klasse is het toegangspunt. Beschouw het als een leeg notitieboek—er gebeurt niets totdat je aangeeft welke taal je verwacht en of je met handschrift werkt. + +### Stap 2 – Kies een taal die handschrift ondersteunt + +`ocr.Language.EXTENDED_LATIN` is niet alleen “Engels”. Het bundelt een reeks op het Latijn gebaseerde scripts en bevat, cruciaal, modellen die getraind zijn op cursieve voorbeelden. Deze stap overslaan leidt vaak tot onleesbare uitvoer omdat de engine standaard een model voor gedrukte tekst gebruikt. + +### Stap 3 – **handgeschreven modus inschakelen** + +Het aanroepen van `enable_handwritten_mode(True)` zet een interne vlag. De engine schakelt dan over naar zijn neurale netwerk dat is afgestemd op de onregelmatige spatiëring en variabele penseelstreken die je in echte notities ziet. Deze regel vergeten is een veelgemaakte fout; de engine zal je krabbels als ruis behandelen. + +### Stap 4 – Voer de afbeelding in en **handgeschreven tekst herkennen** + +`recognize_image` doet het zware werk: het pre‑processes de bitmap, voert deze door het handschriftmodel, en retourneert een object met het `text`‑attribuut. Je kunt ook `handwritten_result.confidence` inspecteren als je een kwaliteitsmeting nodig hebt. + +### Stap 5 – Print het resultaat en **handgeschreven notities lezen** + +`print(handwritten_result.text)` is de eenvoudigste manier om te verifiëren dat je succesvol **extract text from image** hebt uitgevoerd. In productie zou je de string waarschijnlijk opslaan in een database of doorgeven aan een andere service. + +## Omgaan met randgevallen & veelvoorkomende variaties + +| Situatie | Wat te doen | +|-----------|------------| +| **Afbeelding is gedraaid** | Gebruik Pillow om te roteren (`Image.rotate(angle)`) voordat je `recognize_image` aanroept. | +| **Lage contrast** | Converteer naar grijstinten en pas adaptieve drempelwaarde toe (`Image.point(lambda p: p > 128 and 255)`). | +| **Meerdere pagina's** | Loop over een lijst met bestandspaden en concateneer de resultaten. | +| **Niet‑Latijnse scripts** | Vervang `EXTENDED_LATIN` door `ocr.Language.CHINESE` (of een passende) en behoud `enable_handwritten_mode(True)`. | +| **Prestatiezorgen** | Hergebruik dezelfde `ocr_engine`‑instantie voor veel afbeeldingen; elke keer opnieuw initialiseren voegt overhead toe. | + +### Pro tip over geheugengebruik + +Als je honderden notities in één batch verwerkt, roep dan `ocr_engine.dispose()` aan nadat je klaar bent. Het vrijgeeft native resources die de Python‑wrapper mogelijk vasthoudt. + +## Snelle visuele samenvatting + +![voorbeeld handgeschreven tekst herkennen](https://example.com/handwritten-note.png "voorbeeld handgeschreven tekst herkennen") + +*De bovenstaande afbeelding toont een typische handgeschreven notitie die ons script kan omzetten naar platte tekst.* + +## Volledig werkend voorbeeld (één‑bestand script) + +Voor wie van kopiëren‑plakken houdt, hier nogmaals het volledige script zonder de verklarende opmerkingen: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Voer het uit met: + +```bash +python handwriting_ocr.py +``` + +Je zou nu de **recognize handwritten text**‑uitvoer in je console moeten zien. + +## Conclusie + +We hebben zojuist alles behandeld wat je nodig hebt om **handgeschreven tekst** in Python te **herkennen**—beginnend met een verse **create OCR engine python**‑aanroep, het selecteren van de juiste taal, **handgeschreven modus inschakelen**, en uiteindelijk **extract text from image** om **handgeschreven notities te lezen**. + +In één enkel, zelf‑voorzienend script kun je van een wazige foto van een vergaderkrabbel naar schone, doorzoekbare tekst gaan. Overweeg vervolgens de output in een natural‑language‑pipeline te voeren, op te slaan in een doorzoekbare index, of zelfs terug te geven aan een transcriptieservice voor voice‑over‑generatie. + +### Waar ga je hierna naartoe? + +- **Batchverwerking:** Plaats het script in een lus om een map met scans te verwerken. +- **Betrouwbaarheidsfiltering:** Gebruik `result.confidence` om lezingen van lage kwaliteit te negeren. +- **Alternatieve bibliotheken:** Als `ocr` niet perfect past, verken `pytesseract` met `--psm 13` voor handgeschreven modus. +- **UI‑integratie:** Combineer met Flask of FastAPI om een web‑gebaseerde uploadservice aan te bieden. + +Heb je vragen over een specifiek afbeeldingsformaat of heb je hulp nodig bij het afstemmen van het model? Laat een reactie achter hieronder, en happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/english/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..184da2967 --- /dev/null +++ b/ocr/english/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-04-26 +description: Learn how to download HuggingFace model python and extract text from + image python while improving OCR accuracy python with Aspose OCR Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: en +og_description: download huggingface model python and boost your OCR pipeline. Follow + this guide to extract text from image python and improve ocr accuracy python. +og_title: download huggingface model python – Complete OCR Enhancement Tutorial +tags: +- OCR +- HuggingFace +- Python +- AI +title: download huggingface model python – Step‑by‑Step OCR Boost Guide +url: /python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – Complete OCR Enhancement Tutorial + +Ever tried to **download HuggingFace model python** and felt a bit lost? You're not the only one. In many projects the biggest bottleneck is getting a good model onto your machine and then making the OCR results actually useful. + +In this guide we’ll walk through a hands‑on example that shows you exactly how to **download HuggingFace model python**, pull text out of a picture with **extract text from image python**, and then **improve OCR accuracy python** using Aspose’s AI post‑processor. By the end you’ll have a ready‑to‑run script that turns a noisy invoice image into clean, readable text—no magic, just clear steps. + +## What You’ll Need + +- Python 3.9+ (the code works on 3.11 as well) +- An internet connection for the one‑time model download +- The `asposeocrcloud` package (`pip install asposeocrcloud`) +- A sample image (e.g., `sample_invoice.png`) placed in a folder you control + +That’s it—no heavyweight frameworks, no GPU‑specific drivers unless you want to speed things up. + +Now, let’s dive into the actual implementation. + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## Step 1: Set Up the OCR Engine and Choose a Language +*(This is where we start to **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Why this matters:** +The OCR engine is the first line of defense; picking the right language pack reduces character‑recognition errors right away, which is a core part of **improve OCR accuracy python**. + +## Step 2: Configure the AsposeAI Model – Downloading from HuggingFace +*(Here we actually **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**What’s happening under the hood?** +When `allow_auto_download` is true, the SDK reaches out to HuggingFace, fetches the `Qwen2.5‑3B‑Instruct‑GGUF` model, and stores it in the folder you specified. This is the core of **download huggingface model python**—the SDK handles the heavy lifting, so you don’t have to write any `git clone` or `wget` commands yourself. + +*Pro tip:* Keep `directory_model_path` on an SSD for faster load times; the model is ~3 GB even in `int8` form. + +## Step 3: Attach the AI Engine to the OCR Engine +*(Linking the two pieces so we can **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Why bind them?** +The OCR engine gives us raw text, which may contain misspellings, broken lines, or wrong punctuation. The AI engine acts as a smart editor, cleaning up those issues—exactly what you need to **improve OCR accuracy python**. + +## Step 4: Run OCR on Your Image +*(The moment we finally **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` now holds a `text` attribute with the raw characters the engine saw. In practice you’ll notice a few hiccups—maybe “Invoice” turned into “Inv0ice” or a line break in the middle of a sentence. + +## Step 5: Clean Up with the AI Post‑Processor +*(This step directly **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +The AI model rewrites the text, applying language‑aware fixes. Because we used an instruction‑tuned model from HuggingFace, the output is usually fluent and ready for downstream processing. + +## Step 6: Show the Before and After +*(A quick sanity check to see how well we **extract text from image python** and **improve OCR accuracy python**.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Expected Output + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Notice how the AI corrected “Inv0ice” to “Invoice” and smoothed out any stray line breaks. That’s the tangible result of **improve OCR accuracy python** using a downloaded HuggingFace model. + +## Frequently Asked Questions (FAQ) + +### Do I need a GPU to run the model? +No. The `gpu_layers=20` setting tells the SDK to use up to 20 GPU layers if a compatible GPU is present; otherwise it falls back to CPU. On a modern laptop the CPU path still processes a few hundred tokens per second—perfect for occasional invoice parsing. + +### What if the model fails to download? +Make sure your environment can reach `https://huggingface.co`. If you’re behind a corporate proxy, set the `HTTP_PROXY` and `HTTPS_PROXY` environment variables. The SDK will retry automatically, but you can also manually `git lfs pull` the repo into `directory_model_path`. + +### Can I swap the model for a smaller one? +Absolutely. Just replace `hugging_face_repo_id` with another repo (e.g., `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) and adjust `hugging_face_quantization` accordingly. Smaller models download faster and consume less RAM, though you may lose a bit of correction quality. + +### How does this help me **extract text from image python** in other domains? +The same pipeline works for receipts, passports, or handwritten notes. The only change is the language pack (`ocr.Language.FRENCH`, etc.) and possibly a domain‑specific fine‑tuned model from HuggingFace. + +## Bonus: Automating Multiple Files + +If you have a folder full of images, wrap the OCR call in a simple loop: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +This tiny addition lets you **download huggingface model python** once, then batch‑process dozens of files—great for scaling your document‑automation pipeline. + +## Conclusion + +We’ve just walked through a complete, end‑to‑end example that shows you how to **download HuggingFace model python**, **extract text from image python**, and **improve OCR accuracy python** using Aspose’s OCR Cloud and an AI post‑processor. The script is ready to run, the concepts are explained, and you’ve seen the before‑and‑after output so you know it works. + +What’s next? Try swapping in a different HuggingFace model, experiment with other language packs, or feed the cleaned text into a downstream NLP pipeline (e.g., entity extraction for invoice line items). The sky’s the limit, and the foundation you just built is solid. + +Got questions or a tricky image that still trips the OCR? Drop a comment below, and let’s troubleshoot together. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/english/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..951937222 --- /dev/null +++ b/ocr/english/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-04-26 +description: download ocr model quickly using Aspose OCR Python. Learn how to set + model directory, configure model path, and how to download model in a few lines. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: en +og_description: download ocr model in seconds with Aspose OCR Python. This guide shows + how to set model directory, configure model path, and how to download model safely. +og_title: download ocr model – Complete Aspose OCR Python Tutorial +tags: +- OCR +- Python +- Aspose +title: download ocr model with Aspose OCR Python – Step‑by‑Step Guide +url: /python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – Complete Aspose OCR Python Tutorial + +Ever wondered how to **download ocr model** using Aspose OCR in Python without hunting through endless docs? You're not the only one. Many developers hit a wall when the model isn’t present locally and the SDK throws a cryptic error. The good news? The fix is a handful of lines, and you’ll have the model ready to go in minutes. + +In this tutorial we’ll walk through everything you need to know: from importing the right classes, to **set model directory**, to actually **how to download model**, and finally verifying the path. By the end you’ll be able to run OCR on any image with a single function call, and you’ll understand **configure model path** options that keep your project tidy. No fluff, just a practical, runnable example for **aspose ocr python** users. + +## What You’ll Learn + +- How to import the Aspose OCR Cloud classes correctly. +- The exact steps to **download ocr model** automatically. +- Ways to **set model directory** and **configure model path** for reproducible builds. +- How to verify that the model is initialized and where it lives on disk. +- Common pitfalls (permissions, missing directories) and quick fixes. + +### Prerequisites + +- Python 3.8+ installed on your machine. +- `asposeocrcloud` package (`pip install asposeocrcloud`). +- Write permission to a folder where you want to store the model (e.g., `C:\models` or `~/ocr_models`). + +--- + +## Step 1: Import Aspose OCR Cloud Classes + +The first thing you need is the right import statement. This pulls in the classes that manage model configuration and OCR operations. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Why this matters:* `AsposeAI` is the engine that will run OCR, while `AsposeAIModelConfig` tells the engine **where** to look for the model and **whether** it should fetch it automatically. Skipping this step or importing the wrong module will cause a `ModuleNotFoundError` before you even get to the download part. + +--- + +## Step 2: Define the Model Configuration (Set Model Directory & Configure Model Path) + +Now we tell Aspose where to keep the model files. This is where you **set model directory** and **configure model path**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Tips & Gotchas** + +- **Absolute paths** avoid confusion when the script runs from a different working directory. +- On Linux/macOS you might use `"/home/you/ocr_models"`; on Windows, prefix with `r` to treat backslashes literally. +- Setting `allow_auto_download="true"` is the key to **how to download model** without writing extra code. + +--- + +## Step 3: Create the AsposeAI Instance Using the Configuration + +With the configuration ready, instantiate the OCR engine. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Why this matters:* The `ocr_ai` object now holds the configuration we just defined. If the model isn’t present, the next call will trigger the download automatically—this is the core of **how to download model** in a hands‑off manner. + +--- + +## Step 4: Trigger the Model Download (If Needed) + +Before you can run OCR, you need to make sure the model is actually on disk. The `is_initialized()` method both checks and forces initialization. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**What happens under the hood?** + +- The first `is_initialized()` call returns `False` because the model folder is empty. +- The `print` informs the user that a download is about to start. +- The second call forces Aspose to fetch the model from the Hugging Face repo you specified earlier. +- Once downloaded, the method returns `True` on subsequent checks. + +**Edge case:** If your network blocks Hugging Face, you’ll see an exception. In that case, manually download the model zip, extract it into `directory_model_path`, and rerun the script. + +--- + +## Step 5: Report the Local Path Where the Model Is Now Available + +After the download finishes, you probably want to know where the files landed. This helps with debugging and with setting up CI pipelines. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Typical output looks like: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Now you’ve successfully **download ocr model**, set the directory, and confirmed the path. + +--- + +## Visual Overview + +Below is a simple diagram that shows the flow from configuration to a ready‑to‑use model. + +![download ocr model flow diagram showing configuration, automatic download, and local path](/images/download-ocr-model-flow.png) + +*Alt text includes the primary keyword for SEO.* + +--- + +## Common Variations & How to Handle Them + +### 1. Using a Different Model Repository + +If you need a model other than `openai/gpt2`, just replace the `hugging_face_repo_id` value: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Make sure the repository is public or you have the necessary token set in your environment. + +### 2. Disabling Automatic Download + +Sometimes you want to control the download yourself (e.g., in air‑gapped environments). Set `allow_auto_download` to `"false"` and call a custom download script before initializing: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Changing the Model Directory at Runtime + +You can reconfigure the path without recreating the `AsposeAI` object: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Pro Tips for Production Use + +- **Cache the model**: Keep the directory on a shared network drive if multiple services need the same model. This avoids redundant downloads. +- **Version pinning**: The Hugging Face repo may update. To lock to a specific version, append `@v1.0.0` to the repo ID (`"openai/gpt2@v1.0.0"`). +- **Permissions**: Ensure the user running the script has read/write rights on `directory_model_path`. On Linux, `chmod 755` is usually enough. +- **Logging**: Replace the simple `print` statements with Python’s `logging` module for better observability in larger applications. + +--- + +## Full Working Example (Copy‑Paste Ready) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Expected output** (first run will download, subsequent runs will skip download): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Run the script again; you’ll see only the path line because the model is already cached. + +--- + +## Conclusion + +We’ve just covered the complete process to **download ocr model** using Aspose OCR Python, shown how to **set model directory**, and explained the nuances of **configure model path**. With just a few lines of code you can automate the download, avoid manual steps, and keep your OCR pipeline reproducible. + +Next, you might want to explore the actual OCR call (`ocr_ai.recognize_image(...)`) or experiment with a different Hugging Face model to improve accuracy. Either way, the foundation you’ve built here—clear configuration, automatic download, and path verification—will make any future integration a breeze. + +Got questions about edge cases, or want to share how you tweaked the model directory for cloud deployments? Drop a comment below, and happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/english/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..12d478c9e --- /dev/null +++ b/ocr/english/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-26 +description: How to post‑process OCR results and extract text with coordinates. Learn + a step‑by‑step solution using structured output and AI correction. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: en +og_description: How to post‑process OCR results and extract text with coordinates. + Follow this comprehensive tutorial for a reliable workflow. +og_title: How to Post‑Process OCR – Complete Guide +tags: +- OCR +- Python +- AI +- Text Extraction +title: How to Post‑Process OCR – Extract Text with Coordinates in Python +url: /python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to Post‑Process OCR – Extract Text with Coordinates in Python + +Ever needed to **how to post‑process OCR** results because the raw output was noisy or mis‑aligned? You’re not the only one. In many real‑world projects—invoice scanning, receipt digitization, or even augmenting AR experiences—the OCR engine gives you raw words, but you still have to clean them up and keep track of where each word lives on the page. That’s where a structured output mode combined with an AI‑driven post‑processor shines. + +In this tutorial we’ll walk through a complete, runnable Python pipeline that **extracts text with coordinates** from an image, runs an AI‑based correction step, and prints each word together with its (x, y) position. No missing imports, no vague “see the docs” shortcuts—just a self‑contained solution you can drop into your project today. + +> **Pro tip:** If you’re using a different OCR library, look for a “structured” or “layout” mode; the concepts stay the same. + +--- + +## Prerequisites + +Before we dive in, make sure you have: + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.9+ | Modern syntax and type hints | +| `ocr` library that supports `OutputMode.STRUCTURED` (e.g., a fictional `myocr`) | Needed for bounding‑box data | +| An AI post‑processing module (could be OpenAI, HuggingFace, or a custom model) | Improves accuracy after OCR | +| An image file (`input.png`) in your working directory | The source we’ll read | + +If any of these sound unfamiliar, just install the placeholder packages with `pip install myocr ai‑postproc`. The code below also includes fallback stubs so you can test the flow without the real libraries. + +--- + +## Step 1: Enable Structured Output Mode for the OCR Engine + +The first thing we do is tell the OCR engine to give us more than just plain text. Structured output returns each word together with its bounding box and confidence score, which is essential for **extract text with coordinates** later on. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Why this matters:* Without structured mode you’d only get a long string, and you’d lose the spatial information you need for overlaying text on images or feeding downstream layout analysis. + +--- + +## Step 2: Recognize the Image and Capture Words, Boxes, and Confidence + +Now we feed the image into the engine. The result is an object that contains a list of word objects, each exposing `text`, `x`, `y`, `width`, `height`, and `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Edge case:* If the image is empty or unreadable, `structured_result.words` will be an empty list. It’s good practice to check for that and handle it gracefully. + +--- + +## Step 3: Run AI‑Based Post‑Processing While Preserving Positions + +Even the best OCR engines make mistakes—think of “O” vs. “0” or missing diacritics. An AI model trained on domain‑specific text can correct those errors. Crucially, we keep the original coordinates so the spatial layout stays intact. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Why we preserve coordinates:* Many downstream tasks (e.g., PDF generation, AR labeling) rely on exact placement. The AI only touches the `text` field, leaving `x`, `y`, `width`, `height` untouched. + +--- + +## Step 4: Iterate Over the Corrected Words and Display Their Text with Coordinates + +Finally, we loop through the corrected words and print each word together with its top‑left corner `(x, y)`. This satisfies the **extract text with coordinates** goal. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Expected output (example):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Each line shows the corrected word and its exact location on the original image. + +--- + +## Full Working Example + +Below is a single script that ties everything together. You can copy‑paste it, adjust the import statements to match your actual libraries, and run it directly. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Running the script** + +```bash +python ocr_postprocess_demo.py +``` + +If you have the real libraries installed, the script will process your `input.png`. Otherwise, the stub implementation lets you see the expected flow and output without any external dependencies. + +--- + +## Frequently Asked Questions (FAQ) + +| Question | Answer | +|----------|--------| +| *Does this work with Tesseract?* | Tesseract itself doesn’t expose a structured mode out‑of‑the‑box, but wrappers like `pytesseract.image_to_data` return bounding boxes that you can feed into the same AI post‑processor. | +| *What if I need the bottom‑right corner instead of top‑left?* | Each word object also provides `width` and `height`. Compute `x2 = x + width` and `y2 = y + height` to get the opposite corner. | +| *Can I batch‑process multiple images?* | Absolutely. Wrap the steps in a `for image_path in Path("folder").glob("*.png"):` loop and collect results per file. | +| *How do I choose an AI model for correction?* | For generic text, a small GPT‑2 fine‑tuned on OCR errors works. For domain‑specific data (e.g., medical prescriptions), train a sequence‑to‑sequence model on paired noisy‑clean data. | +| *Is the confidence score useful after AI correction?* | You can still keep the original confidence for debugging, but the AI may output its own confidence if the model supports it. | + +--- + +## Edge Cases & Best Practices + +1. **Empty or corrupted images** – always verify `structured_result.words` is non‑empty before proceeding. +2. **Non‑Latin scripts** – ensure your OCR engine is configured for the target language; the AI post‑processor must be trained on the same script. +3. **Performance** – AI correction can be expensive. Cache results if you’ll reuse the same image, or run the AI step asynchronously. +4. **Coordinate system** – OCR libraries may use different origins (top‑left vs. bottom‑left). Adjust accordingly when overlaying on PDFs or canvases. + +--- + +## Conclusion + +You now have a solid, end‑to‑end recipe for **how to post‑process OCR** and reliably **extract text with coordinates**. By enabling structured output, feeding the result through an AI correction layer, and preserving the original bounding boxes, you can turn noisy OCR scans into clean, spatially‑aware text ready for downstream tasks like PDF generation, data entry automation, or augmented‑reality overlays. + +Ready for the next step? Try swapping the stub AI with an OpenAI `gpt‑4o‑mini` call, or integrate the pipeline into a FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/english/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..d044e8571 --- /dev/null +++ b/ocr/english/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-26 +description: How to recognize images quickly with Python. Learn an image recognition + pipeline, batch processing, and automate image recognition using AI. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: en +og_description: How to recognize images quickly with Python. This guide walks through + an image recognition pipeline, batching, and automation using AI. +og_title: How to Recognize Images – Automate an Image Recognition Pipeline +tags: +- image-processing +- python +- ai +title: How to Recognize Images – Automate an Image Recognition Pipeline +url: /python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to Recognize Images – Automate an Image Recognition Pipeline + +Ever wondered **how to recognize images** without writing a thousand lines of code? You're not alone—many developers hit the same wall when they first need to process dozens or hundreds of pictures. The good news? With a few tidy steps you can spin up a full‑blown image recognition pipeline that batches, runs, and cleans up all by itself. + +In this tutorial we’ll walk through a complete, runnable example that shows **how to batch images**, feed each one to an AI engine, post‑process the results, and finally release resources. By the end you’ll have a self‑contained script that you can drop into any project, whether you’re building a photo‑tagger, a quality‑control system, or a research dataset generator. + +## What You’ll Learn + +- **How to recognize images** using a mock AI engine (the pattern is identical for real services like TensorFlow, PyTorch, or cloud APIs). +- How to build an **image recognition pipeline** that handles batches efficiently. +- The best way to **automate image recognition** so you don’t have to manually loop over files each time. +- Tips for scaling the pipeline and freeing up resources safely. + +> **Prerequisites:** Python 3.8+, basic familiarity with functions and loops, and a handful of image files (or paths) you want to process. No external libraries are required for the core example, but we’ll mention where you could plug in real AI SDKs. + +![Diagram of how to recognize images in a batch processing pipeline](pipeline.png "How to recognize images diagram") + +## Step 1: Batch Your Images – How to Batch Images Efficiently + +Before the AI does any heavy lifting, you need a collection of images to feed it. Think of this as your grocery list; the engine will later pick each item off the list one by one. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Why batch?** +Batching reduces the amount of boilerplate code you write and makes it trivial to add parallelism later. If you ever need to process 10 000 pictures, you’ll only change the source of `image_batch`—the rest of the pipeline stays untouched. + +## Step 2: Run the Image Recognition Pipeline (Recognize Images with AI) + +Now we hook the batch into the actual recognizer. In a real‑world scenario you might call `torchvision.models` or a cloud endpoint; here we mock the behavior so the tutorial stays self‑contained. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Explanation:** +- `engine.recognize_image` is the heart of the **image recognition pipeline**; it could be a call to a deep‑learning model or a REST API. +- `postprocessor.run` demonstrates **automate image recognition** by normalising raw predictions into a clean dictionary you can store or stream. +- We collect each `corrected` dict in `recognized_results` so downstream steps (e.g., database insertion) are straightforward. + +## Step 3: Post‑process and Store – Automate Image Recognition Results + +After you have a tidy list of predictions, you typically want to persist them. The example below writes a CSV file; feel free to swap in a database or message queue. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Why a CSV?** +CSV is universally readable—Excel, pandas, even plain‑text editors can open it. If you later need to **automate image recognition** at scale, replace the write block with a bulk insert to your data lake. + +## Step 4: Clean Up – Release AI Resources Safely + +Many AI SDKs allocate GPU memory or spawn worker threads. Forgetting to free them can lead to memory leaks and nasty crashes. Even though our mock objects don’t need it, we’ll show the proper pattern. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +Running the script prints a friendly confirmation, letting you know the pipeline has finished cleanly. + +## Full Working Script + +Putting everything together, here’s the complete, copy‑and‑paste‑ready program: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Expected Output + +When you run the script (assuming the three placeholder paths exist), you’ll see something like: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +And the generated `recognition_results.csv` will contain: + +| image | label | confidence | +|---------------------|-------|------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Conclusion + +You now have a solid, end‑to‑end example of **how to recognize images** in Python, complete with an **image recognition pipeline**, batch handling, and automated post‑processing. The pattern scales: swap the mock classes for a real model, feed it a larger `image_batch`, and you’ve got a production‑ready solution. + +Want to go further? Try these next steps: + +- Replace `MockEngine` with a TensorFlow or PyTorch model for real predictions. +- Parallelise the loop with `concurrent.futures.ThreadPoolExecutor` to speed up large batches. +- Hook the CSV writer into a cloud storage bucket to **automate image recognition** across distributed workers. + +Feel free to experiment, break things, and then fix them—that’s how you truly master image recognition pipelines. If you hit any snags or have ideas for improvements, drop a comment below. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/english/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..fe2991c86 --- /dev/null +++ b/ocr/english/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-04-26 +description: Mask credit card numbers quickly using AsposeAI OCR post‑processing. + Learn PCI compliance, regular expression masking, and data sanitization in a step‑by‑step + tutorial. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: en +og_description: Mask credit card numbers in OCR results with AsposeAI. This tutorial + covers PCI compliance, regular expression masking, and data sanitization. +og_title: Mask Credit Card Numbers – Full Python OCR Post‑Processing Guide +tags: +- OCR +- Python +- security +title: Mask Credit Card Numbers in OCR Output – Complete Python Guide +url: /python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mask Credit Card Numbers – Complete Python Guide + +Ever needed to **mask credit card numbers** in text that comes straight from an OCR engine? You’re not the only one. In regulated industries, exposing a full PAN (Primary Account Number) can land you in hot water with PCI compliance auditors. The good news? With a few lines of Python and AsposeAI’s post‑processing hook, you can automatically hide the middle eight digits and stay on the safe side. + +In this tutorial we’ll walk through a real‑world scenario: running OCR on a receipt image, then applying a custom **OCR post‑processing** function that sanitizes any PCI data. By the end you’ll have a reusable snippet that you can drop into any AsposeAI workflow, plus a handful of practical tips for handling edge cases and scaling the solution. + +## What You’ll Learn + +- How to register a custom post‑processor with **AsposeAI**. +- Why a **regular expression masking** approach is both fast and reliable. +- The basics of **PCI compliance** related to data sanitization. +- Ways to extend the pattern for multiple card formats or international numbers. +- Expected output and how to verify that the masking worked. + +> **Prerequisites** – You should have a working Python 3 environment, the Aspose.AI for OCR package installed (`pip install aspose-ocr`), and a sample image (e.g., `receipt.png`) that contains a credit‑card number. No other external services are required. + +--- + +## Step 1: Define a Post‑Processor that Masks Credit Card Numbers + +The heart of the solution lives in a tiny function that receives the OCR result, runs a **regular expression masking** routine, and returns the sanitized text. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Why this works:** +- The regex `(\d{4})\d{8}(\d{4})` matches exactly 16 consecutive digits, the common format for Visa, MasterCard, and many others. +- By capturing the first and last four digits (`\1` and `\2`) we preserve enough information for debugging while complying with **PCI compliance** rules that forbid storing the full PAN. +- The substitution `\1****\2` hides the sensitive middle eight digits, turning `1234567812345678` into `1234****5678`. + +> **Pro tip:** If you need to support 15‑digit American Express numbers, add a second pattern like `r'(\d{4})\d{6}(\d{5})'` and run both replacements sequentially. + +--- + +## Step 2: Initialise the AsposeAI Engine + +Before we can attach our post‑processor, we need an instance of the OCR engine. AsposeAI bundles the OCR model and a simple API for custom processing. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Why initialise here?** +Creating the `AsposeAI` object once and reusing it across multiple images reduces overhead. The engine also caches language models, which speeds up subsequent calls—handy when you’re scanning batches of receipts. + +--- + +## Step 3: Register the Custom Masking Function + +AsposeAI exposes a `set_post_processor` method that lets you plug in any callable. We pass our `mask_pci` function along with an optional settings dictionary (empty for now). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**What’s happening behind the scenes?** +When you later invoke `run_postprocessor`, AsposeAI will hand the raw OCR result to `mask_pci`. The function receives a lightweight object (`data`) that contains the recognized text, and you return a new string. This design keeps the core OCR untouched while letting you enforce **data sanitization** policies in a single place. + +--- + +## Step 4: Run OCR on the Receipt Image + +Now that the engine knows how to clean the output, we feed it an image. For the sake of this tutorial we assume you already have an `engine` object configured with the right language and resolution settings. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Tip:** If you don’t have a pre‑configured object, you can create one with: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +The `recognize_image` call returns an object whose `text` attribute holds the raw, unmasked string. + +--- + +## Step 5: Apply the Registered Post‑Processor + +With the raw OCR data in hand, we hand it over to the AI instance. The engine automatically runs the `mask_pci` function we registered earlier. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Why use `run_postprocessor` instead of calling the function manually?** +Doing so keeps the workflow consistent, especially when you have multiple post‑processors (e.g., spell‑checking, language detection). AsposeAI queues them in the order you register, guaranteeing deterministic output. + +--- + +## Step 6: Verify the Sanitized Output + +Finally, let’s print the sanitized text and confirm that any credit‑card numbers are properly masked. + +```python +print(final_result.text) +``` + +**Expected output** (excerpt): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +If the receipt contained no card number, the text remains unchanged—nothing to mask, nothing to worry about. + +--- + +## Handling Edge Cases and Common Variations + +### Multiple Card Numbers in One Document +If a receipt includes more than one PAN (e.g., a loyalty card plus a payment card), the regex runs globally, masking all matches automatically. No extra code needed. + +### Non‑Standard Formatting +Sometimes OCR inserts spaces or dashes (`1234 5678 1234 5678` or `1234-5678-1234-5678`). Extend the pattern to ignore those characters: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +The added `[ -]?` tolerates optional spaces or hyphens between digit blocks. + +### International Cards +For 19‑digit PANs used in some regions, you can broaden the pattern: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Just remember that **PCI compliance** still mandates masking the middle digits, regardless of length. + +### Logging Masked Values (Optional) +If you need audit trails, pass a flag via `custom_settings` and adjust the function: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Then register with: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Full Working Example (Copy‑Paste Ready) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Running this script on a receipt that contains `4111111111111111` will produce: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +That’s the whole pipeline—from raw OCR to **data sanitization**—wrapped in a few clean lines of Python. + +--- + +## Conclusion + +We’ve just shown you how to **mask credit card numbers** in OCR results using AsposeAI’s post‑processing hook, a concise regular‑expression routine, and a handful of best‑practice tips for **PCI compliance**. The solution is fully self‑contained, works with any image that the OCR engine can read, and can be extended to cover more complex card formats or logging requirements. + +Ready for the next step? Try coupling this mask with a **database insertion** routine that stores only the last four digits for reference, or integrate a **batch processor** that scans an entire folder of receipts overnight. You might also explore other **OCR post‑processing** tasks like address standardization or language detection—each follows the same pattern we used here. + +Got questions about edge cases, performance, or how to adapt the code for a different OCR library? Drop a comment below, and let’s keep the conversation going. Happy coding, and stay secure! + + + +![Diagram illustrating how mask credit card numbers works in an OCR pipeline](https://example.com/images/ocr-mask-flow.png "Diagram of OCR post‑processing masking flow") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/english/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..a9ad56ac1 --- /dev/null +++ b/ocr/english/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-04-26 +description: Learn how to measure inference time in Python, load a GGUF model from + Hugging Face, and optimize GPU usage for faster results. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: en +og_description: Measure inference time in Python by loading a GGUF model from Hugging + Face and tuning GPU layers for optimal performance. +og_title: Measure Inference Time – Load GGUF Model & Optimize GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Measure Inference Time – Load GGUF Model & Optimize GPU +url: /python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Measure Inference Time – Load GGUF Model & Optimize GPU + +Ever needed to **measure inference time** for a large language model but weren’t sure where to start? You’re not alone—many developers hit the same wall when they first pull a GGUF file from Hugging Face and try to run it on a mixed CPU/GPU setup. + +In this guide we’ll walk through **how to load a GGUF model**, configure it for Hugging Face, and **measure inference time** with a clean Python snippet. Along the way we’ll also show you how to **optimize inference GPU** usage so your runs are as fast as they can be. No fluff, just a practical, end‑to‑end solution you can copy‑paste today. + +## What You’ll Learn + +- How to **configure a HuggingFace model** with `AsposeAIModelConfig`. +- The exact steps to **load a GGUF model** (`fp16` quantization) from the Hugging Face hub. +- A reusable pattern for **timing Python code** around an inference call. +- Tips to **optimize inference GPU** by adjusting `gpu_layers`. +- Expected output and how to verify that your timing makes sense. + +### Prerequisites + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.9+ | Modern syntax and type hints. | +| `asposeai` package (or the equivalent SDK) | Provides `AsposeAI` and `AsposeAIModelConfig`. | +| Access to the Hugging Face repo `bartowski/Qwen2.5-3B-Instruct-GGUF` | The GGUF model we’ll load. | +| A GPU with at least 8 GB VRAM (optional but recommended) | Enables the **optimize inference GPU** step. | + +If you haven’t installed the SDK yet, run: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![measure inference time diagram](https://example.com/measure-inference-time.png){alt="measure inference time diagram"} + +## Step 1: Load the GGUF Model – Configure HuggingFace Model + +The first thing you need is a proper configuration object that tells Aspose AI where to fetch the model and how to treat it. This is where we **load a GGUF model** and **configure huggingface model** parameters. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Why this matters:** +- `hugging_face_repo_id` points to the exact GGUF file on the Hub. +- `fp16` reduces memory bandwidth while keeping most of the model’s fidelity. +- `gpu_layers` is the knob you tweak when you want to **optimize inference GPU** performance; more layers on the GPU usually mean faster latency, provided you have enough VRAM. + +## Step 2: Create the Aspose AI Instance + +Now that the model is described, we spin up an `AsposeAI` object. This step is straightforward, but it’s where the SDK actually downloads the GGUF file (if it isn’t cached) and prepares the runtime. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Pro tip:** The first run will take a few seconds longer because the model is being downloaded and compiled for the GPU. Subsequent runs are lightning‑fast. + +## Step 3: Run Inference and **Measure Inference Time** + +Here’s the heart of the tutorial: wrapping the inference call with `time.time()` to **measure inference time**. We also feed a tiny OCR result just to keep the example self‑contained. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**What you should see:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +If the number feels high, you’re probably running most layers on the CPU. That brings us to the next step. + +## Step 4: **Optimize Inference GPU** – Tune `gpu_layers` + +Sometimes the default `gpu_layers=40` is either too aggressive (causing OOM) or too conservative (leaving performance on the table). Here’s a quick loop you can use to find the sweet spot: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Why this works:** +- Each call rebuilds the runtime with a different GPU allocation, letting you see the latency trade‑off instantly. +- The loop also demonstrates **time python code** in a reusable way, which you can adapt for other performance tests. + +Typical output on a 16 GB RTX 3080 might look like: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +From that, you’d pick `gpu_layers=40` as the optimal point for this hardware. + +## Full Working Example + +Putting everything together, here’s a single script you can drop into a file (`measure_inference.py`) and run: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Run it with: + +```bash +python measure_inference.py +``` + +You should see a sub‑second latency on a decent GPU, confirming that you’ve successfully **measure inference time** and **optimize inference GPU**. + +--- + +## Frequently Asked Questions (FAQs) + +**Q: Does this work with other quantization formats?** +A: Absolutely. Swap `hugging_face_quantization="int8"` (or `q4_0`, etc.) in the config and re‑run the benchmark. Expect a trade‑off: lower memory usage vs. a slight accuracy dip. + +**Q: What if I don’t have a GPU?** +A: Set `gpu_layers=0`. The code will fall back entirely to the CPU, and you’ll still be able to **measure inference time**—just expect higher numbers. + +**Q: Can I time only the model forward pass, excluding post‑processing?** +A: Yes. Call `ai_engine.run_model(...)` (or the equivalent method) directly and wrap that call with `time.time()`. The pattern for **time python code** stays the same. + +--- + +## Conclusion + +You now have a complete, copy‑and‑paste solution to **measure inference time** for a GGUF model, **load gguf model** from Hugging Face, and fine‑tune **optimize inference GPU** settings. By adjusting `gpu_layers` and experimenting with quantization, you can squeeze out every millisecond of performance. + +Next up, you might want to: + +- Integrate this timing logic into a CI pipeline to catch regressions. +- Explore batch inference to further improve throughput. +- Combine the model with a real OCR pipeline instead of the dummy text we used here. + +Happy coding, and may your latency numbers always stay low! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/english/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..594d49da6 --- /dev/null +++ b/ocr/english/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,205 @@ +--- +category: general +date: 2026-04-26 +description: recognize handwritten text using Python's OCR engine. Learn how to extract + text from image, turn on handwritten mode, and read handwritten notes quickly. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: en +og_description: recognize handwritten text with Python. This tutorial shows how to + extract text from image, turn on handwritten mode, and read handwritten notes using + a simple OCR engine. +og_title: recognize handwritten text in Python – Complete OCR Guide +tags: +- OCR +- Python +- Handwriting Recognition +title: recognize handwritten text in Python – OCR Engine Tutorial +url: /python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# recognize handwritten text in Python – OCR Engine Tutorial + +Ever needed to **recognize handwritten text** but felt stuck at the “where do I start?”? You’re not the only one. Whether you’re digitizing meeting scribbles or pulling data from a scanned form, getting a reliable OCR result can feel like chasing a unicorn. + +Good news: with just a few lines of Python you can **extract text from image** files, **turn on handwritten mode**, and finally **read handwritten notes** without hunting down obscure libraries. In this guide we’ll walk through the whole process, from **create OCR engine python** style setup to printing the result on screen. + +## What You’ll Learn + +- How to **create OCR engine python** instance using the `ocr` package. +- Which language setting gives you built‑in handwritten support. +- The exact call to **turn on handwritten mode** so the engine knows you’re dealing with cursive. +- How to feed a picture of a note and **recognize handwritten text** from it. +- Tips for handling different image formats, troubleshooting common pitfalls, and extending the solution. + +No fluff, no “see the docs” dead‑ends—just a complete, runnable script you can copy‑paste and test today. + +## Prerequisites + +Before we dive in, make sure you have: + +1. Python 3.8+ installed (the code uses f‑strings). +2. The hypothetical `ocr` library (`pip install ocr‑engine` – replace with the real package name you’re using). +3. A clear image file of a handwritten note (JPEG, PNG, or TIFF works). +4. A modest amount of curiosity—everything else is covered below. + +> **Pro tip:** If your image is noisy, run a quick preprocessing step with Pillow (e.g., `Image.open(...).convert('L')`) before sending it to the OCR engine. It often boosts accuracy. + +## How to recognize handwritten text with Python + +Below is the full script that **creates OCR engine python** objects, configures them for handwriting, and prints the extracted string. Save it as `handwriting_ocr.py` and run it from your terminal. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Expected Output + +When the script runs successfully, you’ll see something like: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +If the OCR engine can’t detect any characters, the `text` field will be an empty string. In that case, double‑check the image quality or try a higher‑resolution scan. + +## Step‑by‑Step Explanation + +### Step 1 – **create OCR engine python** instance + +The `OcrEngine` class is the entry point. Think of it like a blank notebook—nothing happens until you tell it what language to expect and whether you’re dealing with handwriting. + +### Step 2 – Choose a language that supports handwriting + +`ocr.Language.EXTENDED_LATIN` isn’t just “English”. It bundles a set of Latin‑based scripts and, crucially, includes models trained on cursive samples. Skipping this step often leads to garbled output because the engine defaults to a printed‑text model. + +### Step 3 – **turn on handwritten mode** + +Calling `enable_handwritten_mode(True)` flips an internal flag. The engine then switches to its neural net that’s tuned for the irregular spacing and variable stroke widths you see in real‑world notes. Forgetting this line is a common mistake; the engine will treat your scribbles as noise. + +### Step 4 – Feed the image and **recognize handwritten text** + +`recognize_image` does the heavy lifting: it preprocesses the bitmap, runs it through the handwriting model, and returns an object with the `text` attribute. You can also inspect `handwritten_result.confidence` if you need a quality metric. + +### Step 5 – Print the result and **read handwritten notes** + +`print(handwritten_result.text)` is the simplest way to verify that you’ve successfully **extract text from image**. In production you’d probably store the string in a database or pass it to another service. + +## Handling Edge Cases & Common Variations + +| Situation | What to Do | +|-----------|------------| +| **Image is rotated** | Use Pillow to rotate (`Image.rotate(angle)`) before calling `recognize_image`. | +| **Low contrast** | Convert to grayscale and apply adaptive thresholding (`Image.point(lambda p: p > 128 and 255)`). | +| **Multiple pages** | Loop over a list of file paths and concatenate results. | +| **Non‑Latin scripts** | Replace `EXTENDED_LATIN` with `ocr.Language.CHINESE` (or appropriate) and keep `enable_handwritten_mode(True)`. | +| **Performance concerns** | Reuse the same `ocr_engine` instance across many images; initializing it each time adds overhead. | + +### Pro tip on memory usage + +If you’re processing hundreds of notes in a batch, call `ocr_engine.dispose()` after you’re done. It frees native resources that the Python wrapper may hold onto. + +## Quick Visual Recap + +![recognize handwritten text example](https://example.com/handwritten-note.png "recognize handwritten text example") + +*The image above shows a typical handwritten note that our script can turn into plain text.* + +## Full Working Example (One‑File Script) + +For those who love copy‑paste simplicity, here’s the entire thing again without the explanatory comments: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Run it with: + +```bash +python handwriting_ocr.py +``` + +You should now see the **recognize handwritten text** output in your console. + +## Conclusion + +We’ve just covered everything you need to **recognize handwritten text** in Python—starting from a fresh **create OCR engine python** call, selecting the right language, **turn on handwritten mode**, and finally **extract text from image** to **read handwritten notes**. + +In a single, self‑contained script you can go from a blurry photo of a meeting doodle to clean, searchable text. Next, consider feeding the output into a natural‑language pipeline, storing it in a searchable index, or even feeding it back into a transcription service for voice‑over generation. + +### Where to Go From Here? + +- **Batch processing:** Wrap the script in a loop to handle a folder of scans. +- **Confidence filtering:** Use `result.confidence` to discard low‑quality reads. +- **Alternative libraries:** If `ocr` isn’t a perfect fit, explore `pytesseract` with `--psm 13` for handwritten mode. +- **UI integration:** Combine with Flask or FastAPI to offer a web‑based upload service. + +Got questions about a particular image format or need help tuning the model? Drop a comment below, and happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/french/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..ba1434955 --- /dev/null +++ b/ocr/french/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,193 @@ +--- +category: general +date: 2026-04-26 +description: Apprenez comment télécharger le modèle HuggingFace en Python et extraire + du texte d’une image en Python tout en améliorant la précision de l’OCR en Python + avec Aspose OCR Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: fr +og_description: Téléchargez le modèle HuggingFace Python et boostez votre pipeline + OCR. Suivez ce guide pour extraire du texte d’une image Python et améliorer la précision + OCR Python. +og_title: Télécharger le modèle HuggingFace Python – Tutoriel complet d'amélioration + OCR +tags: +- OCR +- HuggingFace +- Python +- AI +title: télécharger le modèle HuggingFace Python – Guide étape par étape pour booster + l’OCR +url: /fr/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# télécharger modèle huggingface python – Tutoriel complet d'amélioration OCR + +Vous avez déjà essayé de **télécharger modèle huggingface python** et vous êtes senti un peu perdu ? Vous n'êtes pas le seul. Dans de nombreux projets, le principal goulot d'étranglement est d'obtenir un bon modèle sur votre machine, puis de rendre les résultats OCR réellement utiles. + +Dans ce guide, nous allons parcourir un exemple pratique qui vous montre exactement comment **télécharger modèle huggingface python**, extraire du texte d'une image avec **extract text from image python**, puis **improve OCR accuracy python** en utilisant le post‑processeur IA d’Aspose. À la fin, vous disposerez d’un script prêt à l’emploi qui transforme une image de facture bruitée en texte propre et lisible—pas de magie, juste des étapes claires. + +## Ce dont vous aurez besoin + +- Python 3.9+ (le code fonctionne aussi avec 3.11) +- Une connexion Internet pour le téléchargement unique du modèle +- Le package `asposeocrcloud` (`pip install asposeocrcloud`) +- Une image d’exemple (par ex., `sample_invoice.png`) placée dans un dossier que vous contrôlez + +C’est tout—pas de frameworks lourds, pas de pilotes GPU spécifiques sauf si vous voulez accélérer les choses. + +Passons maintenant à l’implémentation réelle. + +![download huggingface model python workflow](image.png "diagramme du téléchargement du modèle huggingface python") + +## Étape 1 : Configurer le moteur OCR et choisir une langue +*(C’est ici que nous commençons à **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Pourquoi c’est important :** +Le moteur OCR est la première ligne de défense ; choisir le bon pack de langue réduit immédiatement les erreurs de reconnaissance de caractères, ce qui constitue une partie essentielle de **improve OCR accuracy python**. + +## Étape 2 : Configurer le modèle AsposeAI – Téléchargement depuis HuggingFace +*(Ici nous **download huggingface model python** réellement.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**Que se passe-t‑il en coulisses ?** +Lorsque `allow_auto_download` est vrai, le SDK contacte HuggingFace, récupère le modèle `Qwen2.5‑3B‑Instruct‑GGUF` et le stocke dans le dossier que vous avez indiqué. C’est le cœur de **download huggingface model python**—le SDK gère la partie lourde, vous n’avez donc pas à écrire de commandes `git clone` ou `wget` vous‑même. + +*Astuce :* Conservez `directory_model_path` sur un SSD pour des temps de chargement plus rapides ; le modèle fait environ 3 Go même en version `int8`. + +## Étape 3 : Attacher le moteur IA au moteur OCR +*(Lier les deux pièces afin de **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Pourquoi les lier ?** +Le moteur OCR nous fournit du texte brut, qui peut contenir des fautes d’orthographe, des lignes cassées ou une ponctuation incorrecte. Le moteur IA agit comme un éditeur intelligent, nettoyant ces problèmes—exactement ce dont vous avez besoin pour **improve OCR accuracy python**. + +## Étape 4 : Exécuter l’OCR sur votre image +*(Le moment où nous **extract text from image python** enfin.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` contient maintenant un attribut `text` avec les caractères bruts que le moteur a vus. En pratique, vous remarquerez quelques accrocs—peut‑être “Invoice” devenu “Inv0ice” ou un saut de ligne au milieu d’une phrase. + +## Étape 5 : Nettoyer avec le post‑processeur IA +*(Cette étape **improve OCR accuracy python** directement.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +Le modèle IA réécrit le texte, appliquant des corrections conscientes de la langue. Parce que nous utilisons un modèle ajusté par instruction depuis HuggingFace, la sortie est généralement fluide et prête pour le traitement en aval. + +## Étape 6 : Afficher avant et après +*(Une vérification rapide pour voir comment nous **extract text from image python** et **improve OCR accuracy python**.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Résultat attendu + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Remarquez comment l’IA a corrigé “Inv0ice” en “Invoice” et a éliminé les sauts de ligne indésirables. C’est le résultat tangible de **improve OCR accuracy python** en utilisant un modèle HuggingFace téléchargé. + +## FAQ (Foire aux questions) + +### Ai‑je besoin d’un GPU pour exécuter le modèle ? +Non. Le paramètre `gpu_layers=20` indique au SDK d’utiliser jusqu’à 20 couches GPU si un GPU compatible est présent ; sinon il revient au CPU. Sur un ordinateur portable moderne, le chemin CPU traite encore quelques centaines de tokens par seconde—parfait pour le traitement occasionnel de factures. + +### Que faire si le modèle ne parvient pas à se télécharger ? +Assurez‑vous que votre environnement peut atteindre `https://huggingface.co`. Si vous êtes derrière un proxy d’entreprise, définissez les variables d’environnement `HTTP_PROXY` et `HTTPS_PROXY`. Le SDK réessaiera automatiquement, mais vous pouvez aussi exécuter manuellement `git lfs pull` du dépôt dans `directory_model_path`. + +### Puis‑je remplacer le modèle par un plus petit ? +Absolument. Remplacez simplement `hugging_face_repo_id` par un autre dépôt (par ex., `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) et ajustez `hugging_face_quantization` en conséquence. Les modèles plus petits se téléchargent plus rapidement et consomment moins de RAM, bien que vous puissiez perdre un peu de qualité de correction. + +### Comment cela m’aide‑t‑il à **extract text from image python** dans d’autres domaines ? +Le même pipeline fonctionne pour les reçus, passeports ou notes manuscrites. Le seul changement est le pack de langue (`ocr.Language.FRENCH`, etc.) et éventuellement un modèle finement ajusté pour le domaine depuis HuggingFace. + +## Bonus : Automatiser le traitement de plusieurs fichiers + +Si vous avez un dossier rempli d’images, encapsulez l’appel OCR dans une boucle simple : + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +Cette petite addition vous permet de **download huggingface model python** une fois, puis de traiter par lots des dizaines de fichiers—idéal pour faire évoluer votre pipeline d’automatisation de documents. + +## Conclusion + +Nous venons de parcourir un exemple complet, de bout en bout, qui montre comment **download huggingface model python**, **extract text from image python**, et **improve OCR accuracy python** en utilisant Aspose OCR Cloud et un post‑processeur IA. Le script est prêt à être exécuté, les concepts sont expliqués, et vous avez vu le résultat avant‑et‑après pour savoir que cela fonctionne. + +Et après ? Essayez de remplacer le modèle HuggingFace par un autre, expérimentez avec d’autres packs de langue, ou alimentez le texte nettoyé dans un pipeline NLP en aval (par ex., extraction d’entités pour les lignes de facture). Le ciel est la limite, et les bases que vous venez de construire sont solides. + +Des questions ou une image difficile qui fait encore échouer l’OCR ? Laissez un commentaire ci‑dessous, et résolvons le problème ensemble. Bon codage ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/french/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..e8ffe1119 --- /dev/null +++ b/ocr/french/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-04-26 +description: Téléchargez rapidement le modèle OCR avec Aspose OCR Python. Apprenez + à définir le répertoire du modèle, à configurer le chemin du modèle et à télécharger + le modèle en quelques lignes. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: fr +og_description: Téléchargez le modèle OCR en quelques secondes avec Aspose OCR Python. + Ce guide montre comment définir le répertoire du modèle, configurer le chemin du + modèle et télécharger le modèle en toute sécurité. +og_title: télécharger le modèle OCR – Tutoriel complet Aspose OCR Python +tags: +- OCR +- Python +- Aspose +title: Télécharger le modèle OCR avec Aspose OCR Python – Guide étape par étape +url: /fr/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# télécharger le modèle ocr – Tutoriel complet Aspose OCR Python + +Vous vous êtes déjà demandé comment **télécharger le modèle ocr** avec Aspose OCR en Python sans fouiller dans d'innombrables documents ? Vous n'êtes pas le seul. De nombreux développeurs se heurtent à un mur lorsque le modèle n'est pas présent localement et que le SDK lance une erreur cryptique. Bonne nouvelle ? La solution ne tient qu'à quelques lignes, et vous aurez le modèle prêt à l'emploi en quelques minutes. + +Dans ce tutoriel, nous passerons en revue tout ce que vous devez savoir : de l'importation des bonnes classes, à **set model directory**, en passant par **how to download model**, et enfin la vérification du chemin. À la fin, vous pourrez exécuter l'OCR sur n'importe quelle image avec un seul appel de fonction, et vous comprendrez les options **configure model path** qui maintiennent votre projet propre. Pas de superflu, juste un exemple pratique et exécutable pour les utilisateurs de **aspose ocr python**. + +## Ce que vous apprendrez + +- Comment importer correctement les classes Aspose OCR Cloud. +- Les étapes exactes pour **download ocr model** automatiquement. +- Les façons de **set model directory** et **configure model path** pour des builds reproductibles. +- Comment vérifier que le modèle est initialisé et où il se trouve sur le disque. +- Les pièges courants (permissions, répertoires manquants) et les solutions rapides. + +### Prérequis + +- Python 3.8+ installé sur votre machine. +- Package `asposeocrcloud` (`pip install asposeocrcloud`). +- Permission d'écriture sur un dossier où vous souhaitez stocker le modèle (par ex., `C:\models` ou `~/ocr_models`). + +--- + +## Étape 1 : Importer les classes Aspose OCR Cloud + +La première chose dont vous avez besoin est la bonne instruction d'importation. Celle-ci charge les classes qui gèrent la configuration du modèle et les opérations OCR. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Pourquoi c'est important :* `AsposeAI` est le moteur qui exécutera l'OCR, tandis que `AsposeAIModelConfig` indique au moteur **où** chercher le modèle et **si** il doit le récupérer automatiquement. Ignorer cette étape ou importer le mauvais module provoquera une `ModuleNotFoundError` avant même d'arriver à la partie téléchargement. + +## Étape 2 : Définir la configuration du modèle (Set Model Directory & Configure Model Path) + +Nous indiquons maintenant à Aspose où conserver les fichiers du modèle. C'est ici que vous **set model directory** et **configure model path**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Conseils & pièges** + +- **Chemins absolus** évitent la confusion lorsque le script s'exécute depuis un répertoire de travail différent. +- Sur Linux/macOS, vous pouvez utiliser `"/home/you/ocr_models"` ; sous Windows, préfixez avec `r` pour traiter les barres obliques inverses littéralement. +- Définir `allow_auto_download="true"` est la clé pour **how to download model** sans écrire de code supplémentaire. + +## Étape 3 : Créer l'instance AsposeAI en utilisant la configuration + +Avec la configuration prête, instanciez le moteur OCR. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Pourquoi c'est important :* L'objet `ocr_ai` contient maintenant la configuration que nous venons de définir. Si le modèle n'est pas présent, l'appel suivant déclenchera le téléchargement automatiquement — c'est le cœur de **how to download model** de manière automatisée. + +## Étape 4 : Déclencher le téléchargement du modèle (si nécessaire) + +Avant de pouvoir exécuter l'OCR, vous devez vous assurer que le modèle est réellement présent sur le disque. La méthode `is_initialized()` vérifie et force l'initialisation. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**Ce qui se passe en coulisses ?** + +- Le premier appel `is_initialized()` renvoie `False` parce que le dossier du modèle est vide. +- Le `print` informe l'utilisateur qu'un téléchargement va commencer. +- Le deuxième appel force Aspose à récupérer le modèle depuis le dépôt Hugging Face que vous avez spécifié précédemment. +- Une fois téléchargé, la méthode renvoie `True` lors des vérifications suivantes. + +**Cas limite :** Si votre réseau bloque Hugging Face, vous verrez une exception. Dans ce cas, téléchargez manuellement le zip du modèle, extrayez‑le dans `directory_model_path`, puis relancez le script. + +## Étape 5 : Signaler le chemin local où le modèle est maintenant disponible + +Après la fin du téléchargement, vous voudrez probablement savoir où les fichiers ont été placés. Cela aide au débogage et à la mise en place des pipelines CI. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Un exemple de sortie typique ressemble à : + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Vous avez maintenant réussi à **download ocr model**, à définir le répertoire et à confirmer le chemin. + +## Vue d'ensemble visuelle + +Below is a simple diagram that shows the flow from configuration to a ready‑to‑use model. + +![diagramme du flux de téléchargement du modèle ocr montrant la configuration, le téléchargement automatique et le chemin local](/images/download-ocr-model-flow.png) + +*Le texte alternatif inclut le mot‑clé principal pour le SEO.* + +## Variations courantes & comment les gérer + +### 1. Utiliser un autre dépôt de modèle + +Si vous avez besoin d'un modèle autre que `openai/gpt2`, remplacez simplement la valeur `hugging_face_repo_id` : + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Assurez‑vous que le dépôt est public ou que le jeton nécessaire est défini dans votre environnement. + +### 2. Désactiver le téléchargement automatique + +Parfois vous souhaitez contrôler le téléchargement vous‑même (par ex., dans des environnements isolés). Définissez `allow_auto_download` à `"false"` et appelez un script de téléchargement personnalisé avant l'initialisation : + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Modifier le répertoire du modèle à l'exécution + +Vous pouvez reconfigurer le chemin sans recréer l'objet `AsposeAI` : + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +## Conseils pro pour l'utilisation en production + +- **Mettre en cache le modèle** : Conservez le répertoire sur un lecteur réseau partagé si plusieurs services ont besoin du même modèle. Cela évite les téléchargements redondants. +- **Verrouillage de version** : Le dépôt Hugging Face peut être mis à jour. Pour bloquer une version spécifique, ajoutez `@v1.0.0` à l'ID du dépôt (`"openai/gpt2@v1.0.0"`). +- **Permissions** : Assurez‑vous que l'utilisateur exécutant le script possède les droits de lecture/écriture sur `directory_model_path`. Sous Linux, `chmod 755` suffit généralement. +- **Journalisation** : Remplacez les simples instructions `print` par le module `logging` de Python pour une meilleure observabilité dans les applications plus importantes. + +## Exemple complet fonctionnel (prêt à copier‑coller) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Sortie attendue** (la première exécution téléchargera, les exécutions suivantes sauteront le téléchargement) : + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Exécutez à nouveau le script ; vous ne verrez que la ligne du chemin car le modèle est déjà mis en cache. + +## Conclusion + +Nous venons de couvrir le processus complet pour **download ocr model** avec Aspose OCR Python, montré comment **set model directory**, et expliqué les subtilités de **configure model path**. Avec seulement quelques lignes de code, vous pouvez automatiser le téléchargement, éviter les étapes manuelles, et garder votre pipeline OCR reproductible. + +Ensuite, vous voudrez peut‑être explorer l'appel OCR réel (`ocr_ai.recognize_image(...)`) ou expérimenter avec un autre modèle Hugging Face pour améliorer la précision. Dans tous les cas, la base que vous avez construite ici—configuration claire, téléchargement automatique et vérification du chemin—facilitera toute intégration future. + +Des questions sur les cas limites, ou envie de partager comment vous avez ajusté le répertoire du modèle pour des déploiements cloud ? Laissez un commentaire ci‑dessous, et bon codage ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/french/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..7cae0b939 --- /dev/null +++ b/ocr/french/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,274 @@ +--- +category: general +date: 2026-04-26 +description: Comment post‑traiter les résultats OCR et extraire le texte avec les + coordonnées. Découvrez une solution étape par étape utilisant une sortie structurée + et la correction par IA. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: fr +og_description: Comment post‑traiter les résultats OCR et extraire le texte avec coordonnées. + Suivez ce tutoriel complet pour un flux de travail fiable. +og_title: Comment post‑traiter l’OCR – Guide complet +tags: +- OCR +- Python +- AI +- Text Extraction +title: Comment post‑traiter l’OCR – Extraire le texte avec ses coordonnées en Python +url: /fr/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment post‑traiter l’OCR – Extraire du texte avec coordonnées en Python + +Vous avez déjà eu besoin de **post‑traiter les résultats OCR** parce que la sortie brute était bruyante ou mal alignée ? Vous n'êtes pas le seul. Dans de nombreux projets réels—numérisation de factures, digitalisation de reçus, ou même l’enrichissement d’expériences AR—le moteur OCR vous fournit des mots bruts, mais vous devez encore les nettoyer et suivre où chaque mot se trouve sur la page. C’est là qu’un mode de sortie structuré combiné à un post‑processeur piloté par l’IA brille. + +Dans ce tutoriel, nous parcourrons un pipeline Python complet et exécutable qui **extrait du texte avec coordonnées** d’une image, exécute une étape de correction basée sur l’IA, et affiche chaque mot avec sa position (x, y). Aucun import manquant, aucune astuce vague du type « voir la documentation »—juste une solution autonome que vous pouvez intégrer à votre projet dès aujourd’hui. + +> **Astuce :** Si vous utilisez une autre bibliothèque OCR, cherchez un mode « structuré » ou « mise en page » ; les concepts restent les mêmes. + +--- + +## Prérequis + +| Exigence | Pourquoi c’est important | +|----------|---------------------------| +| Python 3.9+ | Syntaxe moderne et annotations de type | +| `ocr` library that supports `OutputMode.STRUCTURED` (e.g., a fictional `myocr`) | Bibliothèque `ocr` qui prend en charge `OutputMode.STRUCTURED` (par ex., une bibliothèque fictive `myocr`) | +| Needed for bounding‑box data | Nécessaire pour les données de boîte englobante | +| An AI post‑processing module (could be OpenAI, HuggingFace, or a custom model) | Un module de post‑traitement IA (peut être OpenAI, HuggingFace, ou un modèle personnalisé) | +| Improves accuracy after OCR | Améliore la précision après l’OCR | +| An image file (`input.png`) in your working directory | Un fichier image (`input.png`) dans votre répertoire de travail | +| The source we’ll read | La source que nous lirons | + +Si l’un de ces éléments vous est inconnu, installez simplement les paquets factices avec `pip install myocr ai‑postproc`. Le code ci‑dessous inclut également des stubs de secours afin que vous puissiez tester le flux sans les bibliothèques réelles. + +--- + +## Étape 1 : Activer le mode de sortie structuré pour le moteur OCR + +La première chose que nous faisons est d’indiquer au moteur OCR de nous fournir plus que du texte brut. La sortie structurée renvoie chaque mot avec sa boîte englobante et son score de confiance, ce qui est essentiel pour **extraire du texte avec coordonnées** plus tard. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Pourquoi c’est important :* Sans le mode structuré, vous n’obtiendriez qu’une longue chaîne, et vous perdriez les informations spatiales nécessaires pour superposer du texte sur des images ou alimenter une analyse de mise en page en aval. + +--- + +## Étape 2 : Reconnaître l’image et capturer les mots, les boîtes et la confiance + +Nous injectons maintenant l’image dans le moteur. Le résultat est un objet qui contient une liste d’objets mot, chacun exposant `text`, `x`, `y`, `width`, `height` et `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Cas limite :* Si l’image est vide ou illisible, `structured_result.words` sera une liste vide. Il est recommandé de vérifier cela et de le gérer gracieusement. + +--- + +## Étape 3 : Exécuter le post‑traitement basé sur l’IA tout en préservant les positions + +Même les meilleurs moteurs OCR commettent des erreurs—pensez à « O » vs. « 0 » ou aux diacritiques manquants. Un modèle IA entraîné sur du texte spécifique à un domaine peut corriger ces erreurs. De façon cruciale, nous conservons les coordonnées originales afin que la mise en page spatiale reste intacte. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Pourquoi nous préservons les coordonnées :* De nombreuses tâches en aval (par ex., génération de PDF, étiquetage AR) dépendent d’un placement exact. L’IA ne modifie que le champ `text`, laissant `x`, `y`, `width`, `height` intacts. + +--- + +## Étape 4 : Parcourir les mots corrigés et afficher leur texte avec les coordonnées + +Enfin, nous parcourons les mots corrigés et affichons chaque mot avec son coin supérieur gauche `(x, y)`. Cela répond à l’objectif **extraire du texte avec coordonnées**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Sortie attendue (exemple) :** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Chaque ligne montre le mot corrigé et son emplacement exact sur l’image originale. + +--- + +## Exemple complet fonctionnel + +Voici un script unique qui rassemble tout. Vous pouvez le copier‑coller, ajuster les instructions d’importation pour correspondre à vos bibliothèques réelles, et l’exécuter directement. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Exécution du script** + +```bash +python ocr_postprocess_demo.py +``` + +Si vous avez les bibliothèques réelles installées, le script traitera votre `input.png`. Sinon, l’implémentation stub vous permet de voir le flux et la sortie attendus sans aucune dépendance externe. + +--- + +## Questions fréquemment posées (FAQ) + +| Question | Réponse | +|----------|---------| +| *Cela fonctionne‑t‑il avec Tesseract ?* | Tesseract ne propose pas de mode structuré natif, mais des wrappers comme `pytesseract.image_to_data` renvoient des boîtes englobantes que vous pouvez transmettre au même post‑processeur IA. | +| *Et si j’ai besoin du coin inférieur droit au lieu du coin supérieur gauche ?* | Chaque objet mot fournit également `width` et `height`. Calculez `x2 = x + width` et `y2 = y + height` pour obtenir le coin opposé. | +| *Puis‑je traiter plusieurs images en lot ?* | Absolument. Enveloppez les étapes dans une boucle `for image_path in Path("folder").glob("*.png"):` et collectez les résultats par fichier. | +| *Comment choisir un modèle IA pour la correction ?* | Pour du texte générique, un petit GPT‑2 affiné sur les erreurs OCR fonctionne. Pour des données spécifiques à un domaine (par ex., prescriptions médicales), entraînez un modèle séquence‑à‑séquence sur des données bruitées‑propres appariées. | +| *Le score de confiance est‑il utile après la correction IA ?* | Vous pouvez toujours conserver la confiance originale pour le débogage, mais l’IA peut produire son propre score de confiance si le modèle le supporte. | + +--- + +## Cas limites et bonnes pratiques + +1. **Images vides ou corrompues** – vérifiez toujours que `structured_result.words` n’est pas vide avant de continuer. +2. **Scripts non latins** – assurez‑vous que votre moteur OCR est configuré pour la langue cible ; le post‑processeur IA doit être entraîné sur le même script. +3. **Performance** – la correction IA peut être coûteuse. Mettez en cache les résultats si vous réutilisez la même image, ou exécutez l’étape IA de façon asynchrone. +4. **Système de coordonnées** – les bibliothèques OCR peuvent utiliser des origines différentes (coin supérieur gauche vs. coin inférieur gauche). Ajustez en conséquence lors de la superposition sur des PDF ou des canevas. + +--- + +## Conclusion + +Vous disposez maintenant d’une méthode solide, de bout en bout, pour **post‑traiter l’OCR** et **extraire du texte avec coordonnées** de manière fiable. En activant la sortie structurée, en faisant passer le résultat par une couche de correction IA, et en préservant les boîtes englobantes originales, vous pouvez transformer des scans OCR bruyants en texte propre et spatialement conscient, prêt pour des tâches en aval comme la génération de PDF, l’automatisation de la saisie de données, ou les superpositions en réalité augmentée. + +Prêt pour l’étape suivante ? Essayez de remplacer l’IA factice par un appel OpenAI `gpt‑4o‑mini`, ou intégrez le pipeline dans un FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/french/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..a2ac126a9 --- /dev/null +++ b/ocr/french/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,249 @@ +--- +category: general +date: 2026-04-26 +description: Comment reconnaître rapidement des images avec Python. Apprenez un pipeline + de reconnaissance d'images, le traitement par lots et automatisez la reconnaissance + d'images grâce à l'IA. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: fr +og_description: Comment reconnaître rapidement des images avec Python. Ce guide parcourt + un pipeline de reconnaissance d'images, le traitement par lots et l'automatisation + à l'aide de l'IA. +og_title: Comment reconnaître les images – automatiser un pipeline de reconnaissance + d'images +tags: +- image-processing +- python +- ai +title: Comment reconnaître les images – Automatiser un pipeline de reconnaissance + d'images +url: /fr/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment reconnaître des images – Automatiser un pipeline de reconnaissance d'images + +Vous vous êtes déjà demandé **comment reconnaître des images** sans écrire des milliers de lignes de code ? Vous n'êtes pas seul — de nombreux développeurs rencontrent le même obstacle lorsqu'ils doivent traiter des dizaines ou des centaines de photos. La bonne nouvelle ? En suivant quelques étapes simples, vous pouvez mettre en place un pipeline complet de reconnaissance d'images qui regroupe, exécute et nettoie tout automatiquement. + +Dans ce tutoriel, nous parcourrons un exemple complet et exécutable qui montre **comment regrouper des images**, les envoyer à un moteur d'IA, post‑traiter les résultats, puis libérer les ressources. À la fin, vous disposerez d'un script autonome que vous pourrez intégrer à n'importe quel projet, que vous construisiez un étiqueteur de photos, un système de contrôle qualité ou un générateur de jeux de données de recherche. + +## Ce que vous allez apprendre + +- **Comment reconnaître des images** à l'aide d'un moteur d'IA factice (le même schéma s'applique aux services réels comme TensorFlow, PyTorch ou les API cloud). +- Comment construire un **pipeline de reconnaissance d'images** qui gère efficacement les lots. +- La meilleure façon d'**automatiser la reconnaissance d'images** afin de ne plus devoir boucler manuellement sur les fichiers à chaque fois. +- Des astuces pour faire évoluer le pipeline et libérer les ressources en toute sécurité. + +> **Prérequis :** Python 3.8+, connaissance de base des fonctions et des boucles, et quelques fichiers image (ou chemins) que vous souhaitez traiter. Aucune bibliothèque externe n'est requise pour l'exemple de base, mais nous indiquerons où vous pourriez brancher de vrais SDK d'IA. + +![Diagramme montrant comment reconnaître des images dans un pipeline de traitement par lots](pipeline.png "Diagramme de la reconnaissance d'images") + +## Étape 1 : Regroupez vos images – Comment regrouper les images efficacement + +Avant que l'IA ne commence le traitement intensif, vous avez besoin d'une collection d'images à lui fournir. Considérez cela comme votre liste de courses ; le moteur prendra chaque élément de la liste un par un. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Pourquoi regrouper ?** +Le regroupement réduit la quantité de code boilerplate que vous devez écrire et rend trivial l'ajout de parallélisme ultérieur. Si vous devez un jour traiter 10 000 photos, vous ne changerez que la source de `image_batch` — le reste du pipeline reste intact. + +## Étape 2 : Exécutez le pipeline de reconnaissance d'images (Reconnaître les images avec l'IA) + +Nous branchons maintenant le lot dans le véritable reconnaisseur. Dans un scénario réel, vous pourriez appeler `torchvision.models` ou un point de terminaison cloud ; ici nous simulons le comportement afin que le tutoriel reste autonome. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Explication :** +- `engine.recognize_image` est le cœur du **pipeline de reconnaissance d'images** ; il pourrait s'agir d'un appel à un modèle d'apprentissage profond ou à une API REST. +- `postprocessor.run` montre comment **automatiser la reconnaissance d'images** en normalisant les prédictions brutes dans un dictionnaire propre que vous pouvez stocker ou diffuser. +- Nous collectons chaque dictionnaire `corrected` dans `recognized_results` afin que les étapes en aval (par ex. insertion en base de données) soient simples. + +## Étape 3 : Post‑traiter et stocker – Automatiser les résultats de la reconnaissance d'images + +Une fois que vous avez une liste ordonnée de prédictions, vous voulez généralement les persister. L'exemple ci‑dessous écrit un fichier CSV ; n'hésitez pas à le remplacer par une base de données ou une file de messages. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Pourquoi un CSV ?** +Le CSV est universellement lisible — Excel, pandas, voire les éditeurs de texte brut peuvent l'ouvrir. Si vous devez plus tard **automatiser la reconnaissance d'images** à grande échelle, remplacez le bloc d'écriture par une insertion massive dans votre data lake. + +## Étape 4 : Nettoyage – Libérer les ressources d'IA en toute sécurité + +De nombreux SDK d'IA allouent de la mémoire GPU ou créent des threads de travail. Oublier de les libérer peut entraîner des fuites de mémoire et des plantages désagréables. Même si nos objets factices n'en ont pas besoin, nous montrons le bon schéma. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +L'exécution du script affiche une confirmation conviviale, indiquant que le pipeline s'est terminé proprement. + +## Script complet fonctionnel + +En rassemblant le tout, voici le programme complet, prêt à copier‑coller : + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Résultat attendu + +Lorsque vous exécutez le script (en supposant que les trois chemins factices existent), vous verrez quelque chose comme : + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +Et le fichier `recognition_results.csv` généré contiendra : + +| image | label | confidence | +|---------------------|-------|------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Conclusion + +Vous disposez maintenant d'un exemple complet, de bout en bout, de **comment reconnaître des images** en Python, incluant un **pipeline de reconnaissance d'images**, la gestion des lots et le post‑traitement automatisé. Le modèle est extensible : remplacez les classes factices par un vrai modèle, alimentez‑le avec un `image_batch` plus grand, et vous avez une solution prête pour la production. + +Envie d'aller plus loin ? Essayez les étapes suivantes : + +- Remplacez `MockEngine` par un modèle TensorFlow ou PyTorch pour des prédictions réelles. +- Parallelisez la boucle avec `concurrent.futures.ThreadPoolExecutor` pour accélérer les gros lots. +- Connectez l'écrivain CSV à un bucket de stockage cloud afin d'**automatiser la reconnaissance d'images** sur des travailleurs distribués. + +N'hésitez pas à expérimenter, à casser des choses, puis à les réparer — c'est ainsi que l'on maîtrise vraiment les pipelines de reconnaissance d'images. Si vous rencontrez des problèmes ou avez des idées d'amélioration, laissez un commentaire ci‑dessous. Bon codage ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/french/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..f09e8ebb0 --- /dev/null +++ b/ocr/french/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-04-26 +description: Masquez rapidement les numéros de carte de crédit à l'aide du post‑traitement + OCR d’AsposeAI. Apprenez la conformité PCI, le masquage par expression régulière + et la désinfection des données dans un tutoriel étape par étape. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: fr +og_description: Masquez les numéros de carte de crédit dans les résultats OCR avec + AsposeAI. Ce tutoriel couvre la conformité PCI, le masquage par expression régulière + et l’assainissement des données. +og_title: Masquer les numéros de carte de crédit – Guide complet de post‑traitement + OCR en Python +tags: +- OCR +- Python +- security +title: Masquer les numéros de carte de crédit dans la sortie OCR – Guide complet Python +url: /fr/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Masquer les numéros de carte de crédit – Guide complet Python + +Vous avez déjà eu besoin de **masquer les numéros de carte de crédit** dans du texte provenant directement d’un moteur OCR ? Vous n’êtes pas le seul. Dans les secteurs réglementés, exposer un PAN complet (Primary Account Number) peut vous mettre dans l’eau chaude avec les auditeurs de conformité PCI. La bonne nouvelle ? Avec quelques lignes de Python et le hook de post‑processing d’AsposeAI, vous pouvez masquer automatiquement les huit chiffres du milieu et rester du bon côté. + +Dans ce tutoriel, nous allons parcourir un scénario réel : exécuter l’OCR sur une image de reçu, puis appliquer une fonction personnalisée de **post‑processing OCR** qui assainit toutes les données PCI. À la fin, vous disposerez d’un extrait réutilisable que vous pourrez intégrer à n’importe quel workflow AsposeAI, ainsi que d’une série de conseils pratiques pour gérer les cas limites et faire évoluer la solution. + +## Ce que vous apprendrez + +- Comment enregistrer un post‑processor personnalisé avec **AsposeAI**. +- Pourquoi une approche de **masquage par expression régulière** est à la fois rapide et fiable. +- Les bases de la **conformité PCI** liées à l’assainissement des données. +- Des moyens d’étendre le motif pour plusieurs formats de cartes ou des numéros internationaux. +- Le résultat attendu et comment vérifier que le masquage a fonctionné. + +> **Prérequis** – Vous devez disposer d’un environnement Python 3 fonctionnel, du package Aspose.AI for OCR installé (`pip install aspose-ocr`), et d’une image d’exemple (par ex., `receipt.png`) contenant un numéro de carte de crédit. Aucun autre service externe n’est requis. + +--- + +## Étape 1 : Définir un post‑processor qui masque les numéros de carte de crédit + +Le cœur de la solution réside dans une petite fonction qui reçoit le résultat OCR, exécute une routine de **masquage par expression régulière**, et renvoie le texte assaini. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Pourquoi cela fonctionne :** +- L’expression régulière `(\d{4})\d{8}(\d{4})` correspond exactement à 16 chiffres consécutifs, le format commun pour Visa, MasterCard et bien d’autres. +- En capturant les quatre premiers et les quatre derniers chiffres (`\1` et `\2`), nous conservons suffisamment d’informations pour le débogage tout en respectant les règles de **conformité PCI** qui interdisent le stockage du PAN complet. +- La substitution `\1****\2` masque les huit chiffres sensibles du milieu, transformant `1234567812345678` en `1234****5678`. + +> **Astuce pro** : Si vous devez prendre en charge les numéros American Express à 15 chiffres, ajoutez un second motif comme `r'(\d{4})\d{6}(\d{5})'` et exécutez les deux remplacements séquentiellement. + +## Étape 2 : Initialiser le moteur AsposeAI + +Avant de pouvoir attacher notre post‑processor, nous avons besoin d’une instance du moteur OCR. AsposeAI regroupe le modèle OCR et une API simple pour le traitement personnalisé. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Pourquoi initialiser ici ?** +Créer l’objet `AsposeAI` une fois et le réutiliser pour plusieurs images réduit la surcharge. Le moteur met également en cache les modèles linguistiques, ce qui accélère les appels suivants—pratique lorsque vous scannez des lots de reçus. + +## Étape 3 : Enregistrer la fonction de masquage personnalisée + +AsposeAI expose une méthode `set_post_processor` qui vous permet de brancher n’importe quel callable. Nous passons notre fonction `mask_pci` ainsi qu’un dictionnaire de paramètres optionnel (vide pour l’instant). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**Ce qui se passe en coulisses** +Lorsque vous invoquez plus tard `run_postprocessor`, AsposeAI transmet le résultat OCR brut à `mask_pci`. La fonction reçoit un objet léger (`data`) contenant le texte reconnu, et vous renvoyez une nouvelle chaîne. Cette conception garde le cœur de l’OCR intact tout en vous permettant d’appliquer des politiques de **sanitisation des données** en un seul endroit. + +## Étape 4 : Exécuter l’OCR sur l’image du reçu + +Maintenant que le moteur sait comment nettoyer la sortie, nous lui fournissons une image. Pour les besoins de ce tutoriel, nous supposons que vous avez déjà un objet `engine` configuré avec les bons paramètres de langue et de résolution. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +> **Conseil** : Si vous n’avez pas d’objet pré‑configuré, vous pouvez en créer un avec : + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +L’appel `recognize_image` renvoie un objet dont l’attribut `text` contient la chaîne brute, non masquée. + +## Étape 5 : Appliquer le post‑processor enregistré + +Avec les données OCR brutes en main, nous les transmettons à l’instance AI. Le moteur exécute automatiquement la fonction `mask_pci` que nous avons enregistrée précédemment. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Pourquoi utiliser `run_postprocessor` au lieu d’appeler la fonction manuellement ?** +Cela maintient le flux de travail cohérent, surtout lorsque vous avez plusieurs post‑processors (par ex., correction orthographique, détection de langue). AsposeAI les place dans la file d’attente dans l’ordre d’enregistrement, garantissant une sortie déterministe. + +## Étape 6 : Vérifier la sortie assainie + +Enfin, affichons le texte assaini et confirmons que tous les numéros de carte de crédit sont correctement masqués. + +```python +print(final_result.text) +``` + +**Sortie attendue** : + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Si le reçu ne contenait aucun numéro de carte, le texte reste inchangé—rien à masquer, rien à craindre. + +## Gestion des cas limites et des variations courantes + +### Plusieurs numéros de carte dans un même document +Si un reçu inclut plus d’un PAN (par ex., une carte de fidélité plus une carte de paiement), l’expression régulière s’exécute globalement, masquant automatiquement toutes les correspondances. Aucun code supplémentaire n’est nécessaire. + +### Formatage non standard +Parfois l’OCR insère des espaces ou des tirets (`1234 5678 1234 5678` ou `1234-5678-1234-5678`). Étendez le motif pour ignorer ces caractères : + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +Le `[ -]?` ajouté tolère les espaces ou tirets optionnels entre les blocs de chiffres. + +### Cartes internationales +Pour les PAN à 19 chiffres utilisés dans certaines régions, vous pouvez élargir le motif : + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +N’oubliez pas que la **conformité PCI** impose toujours le masquage des chiffres du milieu, quelle que soit la longueur. + +### Journalisation des valeurs masquées (optionnel) +Si vous avez besoin de pistes d’audit, transmettez un drapeau via `custom_settings` et ajustez la fonction : + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Puis enregistrez avec : + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +## Exemple complet fonctionnel (prêt à copier‑coller) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Exécuter ce script sur un reçu contenant `4111111111111111` produira : + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +Voici l’ensemble du pipeline—du OCR brut à la **sanitisation des données**—emballé en quelques lignes claires de Python. + +## Conclusion + +Nous venons de vous montrer comment **masquer les numéros de carte de crédit** dans les résultats OCR en utilisant le hook de post‑processing d’AsposeAI, une routine concise d’expression régulière, et une série de bonnes pratiques pour la **conformité PCI**. La solution est entièrement autonome, fonctionne avec n’importe quelle image que le moteur OCR peut lire, et peut être étendue pour couvrir des formats de cartes plus complexes ou des exigences de journalisation. + +Prêt pour l’étape suivante ? Essayez de coupler ce masque avec une routine **d’insertion en base de données** qui ne conserve que les quatre derniers chiffres à titre de référence, ou intégrez un **processeur par lots** qui analyse un dossier complet de reçus pendant la nuit. Vous pouvez également explorer d’autres tâches de **post‑processing OCR** comme la normalisation d’adresses ou la détection de langue—toutes suivent le même schéma que celui présenté ici. + +Des questions sur les cas limites, les performances, ou l’adaptation du code à une autre bibliothèque OCR ? Laissez un commentaire ci‑dessous, et continuons la discussion. Bon codage, et restez sécurisés ! + + + +![Diagram illustrating how mask credit card numbers works in an OCR pipeline](https://example.com/images/ocr-mask-flow.png "Diagram of OCR post‑processing masking flow") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/french/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..cebfb4aa6 --- /dev/null +++ b/ocr/french/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,228 @@ +--- +category: general +date: 2026-04-26 +description: Apprenez à mesurer le temps d'inférence en Python, à charger un modèle + GGUF depuis Hugging Face et à optimiser l'utilisation du GPU pour des résultats + plus rapides. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: fr +og_description: Mesurez le temps d'inférence en Python en chargeant un modèle GGUF + depuis Hugging Face et en ajustant les couches GPU pour des performances optimales. +og_title: Mesurer le temps d'inférence – Charger le modèle GGUF et optimiser le GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Mesurer le temps d’inférence – Charger le modèle GGUF et optimiser le GPU +url: /fr/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mesurer le temps d'inférence – Charger le modèle GGUF & Optimiser le GPU + +Vous avez déjà eu besoin de **mesurer le temps d'inférence** pour un grand modèle de langage mais vous ne saviez pas par où commencer ? Vous n'êtes pas seul—de nombreux développeurs rencontrent le même obstacle lorsqu'ils récupèrent pour la première fois un fichier GGUF depuis Hugging Face et essaient de l'exécuter sur une configuration mixte CPU/GPU. + +Dans ce guide, nous allons parcourir **comment charger un modèle GGUF**, le configurer pour Hugging Face, et **mesurer le temps d'inférence** avec un extrait Python propre. En cours de route, nous vous montrerons également comment **optimiser l'utilisation du GPU pour l'inférence** afin que vos exécutions soient aussi rapides que possible. Pas de superflu, juste une solution pratique, de bout en bout, que vous pouvez copier‑coller dès aujourd'hui. + +## Ce que vous apprendrez + +- Comment **configurer un modèle HuggingFace** avec `AsposeAIModelConfig`. +- Les étapes exactes pour **charger un modèle GGUF** (quantification `fp16`) depuis le hub Hugging Face. +- Un modèle réutilisable pour **chronométrer du code Python** autour d'un appel d'inférence. +- Conseils pour **optimiser le GPU d'inférence** en ajustant `gpu_layers`. +- Sortie attendue et comment vérifier que votre chronométrage a du sens. + +### Prérequis + +| Exigence | Pourquoi c'est important | +|-------------|----------------| +| Python 3.9+ | Syntaxe moderne et annotations de type. | +| `asposeai` package (or the equivalent SDK) | Package `asposeai` (ou le SDK équivalent) | +| `AsposeAI` and `AsposeAIModelConfig`. | +| Access to the Hugging Face repo `bartowski/Qwen2.5-3B-Instruct-GGUF` | Accès au dépôt Hugging Face `bartowski/Qwen2.5-3B-Instruct-GGUF` | +| The GGUF model we’ll load. | +| A GPU with at least 8 GB VRAM (optional but recommended) | Un GPU avec au moins 8 Go de VRAM (optionnel mais recommandé) | +| Enables the **optimize inference GPU** step. | + +Si vous n'avez pas encore installé le SDK, exécutez : + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![measure inference time diagram](https://example.com/measure-inference-time.png){alt="diagramme de mesure du temps d'inférence"} + +## Étape 1 : Charger le modèle GGUF – Configurer le modèle HuggingFace + +La première chose dont vous avez besoin est un objet de configuration approprié qui indique à Aspose AI où récupérer le modèle et comment le traiter. C'est ici que nous **chargeons un modèle GGUF** et **configurons les paramètres du modèle huggingface**. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Pourquoi c'est important :** +- `hugging_face_repo_id` pointe vers le fichier GGUF exact sur le Hub. +- `fp16` réduit la bande passante mémoire tout en conservant la plupart de la fidélité du modèle. +- `gpu_layers` est le paramètre que vous ajustez lorsque vous souhaitez **optimiser le GPU d'inférence** ; plus de couches sur le GPU signifient généralement une latence plus rapide, à condition d'avoir suffisamment de VRAM. + +## Étape 2 : Créer l'instance Aspose AI + +Maintenant que le modèle est décrit, nous créons un objet `AsposeAI`. Cette étape est simple, mais c'est là que le SDK télécharge réellement le fichier GGUF (s'il n'est pas en cache) et prépare le runtime. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Astuce :** La première exécution prendra quelques secondes de plus car le modèle est téléchargé et compilé pour le GPU. Les exécutions suivantes sont ultra‑rapides. + +## Étape 3 : Exécuter l'inférence et **mesurer le temps d'inférence** + +Voici le cœur du tutoriel : encapsuler l'appel d'inférence avec `time.time()` pour **mesurer le temps d'inférence**. Nous alimentons également un petit résultat OCR juste pour que l'exemple soit autonome. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Ce que vous devriez voir :** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Si le nombre semble élevé, vous exécutez probablement la plupart des couches sur le CPU. Cela nous amène à l'étape suivante. + +## Étape 4 : **Optimiser le GPU d'inférence** – Ajuster `gpu_layers` + +Parfois, la valeur par défaut `gpu_layers=40` est soit trop agressive (causant un OOM) soit trop conservatrice (laissant des performances sur la table). Voici une boucle rapide que vous pouvez utiliser pour trouver le point optimal : + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Pourquoi cela fonctionne :** +- Chaque appel reconstruit le runtime avec une allocation GPU différente, vous permettant de voir instantanément le compromis de latence. +- La boucle montre également **time python code** de manière réutilisable, que vous pouvez adapter à d'autres tests de performance. + +Une sortie typique sur un RTX 3080 de 16 Go pourrait ressembler à : + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +À partir de cela, vous choisiriez `gpu_layers=40` comme point optimal pour ce matériel. + +## Exemple complet fonctionnel + +En rassemblant tout, voici un script unique que vous pouvez placer dans un fichier (`measure_inference.py`) et exécuter : + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Exécutez-le avec : + +```bash +python measure_inference.py +``` + +Vous devriez voir une latence inférieure à une seconde sur un GPU correct, confirmant que vous avez réussi à **mesurer le temps d'inférence** et à **optimiser le GPU d'inférence**. + +--- + +## Questions fréquemment posées (FAQ) + +**Q : Cela fonctionne-t-il avec d'autres formats de quantification ?** +R : Absolument. Remplacez `hugging_face_quantization="int8"` (ou `q4_0`, etc.) dans la configuration et relancez le benchmark. Attendez-vous à un compromis : moins de mémoire utilisée contre une légère perte de précision. + +**Q : Et si je n’ai pas de GPU ?** +R : Définissez `gpu_layers=0`. Le code reviendra entièrement sur le CPU, et vous pourrez toujours **mesurer le temps d'inférence** — attendez simplement des valeurs plus élevées. + +**Q : Puis-je chronométrer uniquement le passage avant du modèle, en excluant le post‑traitement ?** +R : Oui. Appelez directement `ai_engine.run_model(...)` (ou la méthode équivalente) et encapsulez cet appel avec `time.time()`. Le modèle pour **time python code** reste le même. + +## Conclusion + +Vous disposez maintenant d'une solution complète, prête à copier‑coller, pour **mesurer le temps d'inférence** d'un modèle GGUF, **charger le modèle gguf** depuis Hugging Face, et affiner les paramètres d'**optimisation du GPU d'inférence**. En ajustant `gpu_layers` et en expérimentant avec la quantification, vous pouvez extraire chaque milliseconde de performance. + +Ensuite, vous pourriez vouloir : + +- Intégrer cette logique de chronométrage dans un pipeline CI pour détecter les régressions. +- Explorer l'inférence par lots pour améliorer davantage le débit. +- Combiner le modèle avec un vrai pipeline OCR au lieu du texte factice que nous avons utilisé ici. + +Bon codage, et que vos chiffres de latence restent toujours bas ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/french/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..0f58966c9 --- /dev/null +++ b/ocr/french/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-04-26 +description: Reconnaître le texte manuscrit à l'aide du moteur OCR de Python. Apprenez + comment extraire le texte d’une image, activer le mode manuscrit et lire rapidement + les notes manuscrites. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: fr +og_description: Reconnaître le texte manuscrit avec Python. Ce tutoriel montre comment + extraire le texte d’une image, activer le mode manuscrit et lire les notes manuscrites + à l’aide d’un moteur OCR simple. +og_title: Reconnaître le texte manuscrit en Python – Guide complet d’OCR +tags: +- OCR +- Python +- Handwriting Recognition +title: Reconnaître le texte manuscrit en Python – Tutoriel du moteur OCR +url: /fr/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# reconnaître le texte manuscrit en Python – Tutoriel du moteur OCR + +Vous avez déjà eu besoin de **reconnaître le texte manuscrit** mais vous êtes resté bloqué au stade « par où commencer ? » ? Vous n'êtes pas le seul. Que vous numérisiez des griffonnages de réunion ou extrayiez des données d'un formulaire scanné, obtenir un résultat OCR fiable peut donner l'impression de poursuivre une licorne. + +Bonne nouvelle : avec seulement quelques lignes de Python, vous pouvez **extraire du texte d'une image**, **activer le mode manuscrit**, et enfin **lire les notes manuscrites** sans chercher des bibliothèques obscures. Dans ce guide, nous parcourrons l’ensemble du processus, depuis la configuration de style **create OCR engine python** jusqu’à l’affichage du résultat à l’écran. + +## Ce que vous apprendrez + +- Comment créer une instance **create OCR engine python** en utilisant le package `ocr`. +- Quel paramètre de langue vous offre un support intégré pour l'écriture manuscrite. +- L’appel exact pour **turn on handwritten mode** afin que le moteur sache que vous traitez de l’écriture cursive. +- Comment fournir une image d’une note et **recognize handwritten text** à partir de celle‑ci. +- Conseils pour gérer différents formats d’image, dépanner les problèmes courants et étendre la solution. + +Pas de fioritures, pas de « voir la documentation » sans issue — juste un script complet et exécutable que vous pouvez copier‑coller et tester dès aujourd’hui. + +## Prérequis + +1. Python 3.8+ installé (le code utilise des f‑strings). +2. La bibliothèque hypothétique `ocr` (`pip install ocr‑engine` – remplacez par le nom réel du paquet que vous utilisez). +3. Un fichier image clair d’une note manuscrite (JPEG, PNG ou TIFF fonctionne). +4. Une petite dose de curiosité — tout le reste est couvert ci‑dessous. + +> **Astuce :** Si votre image est bruitée, effectuez une étape de prétraitement rapide avec Pillow (par ex., `Image.open(...).convert('L')`) avant de l’envoyer au moteur OCR. Cela améliore souvent la précision. + +## Comment reconnaître le texte manuscrit avec Python + +Voici le script complet qui **creates OCR engine python** des objets, les configure pour l’écriture manuscrite, et affiche la chaîne extraite. Enregistrez‑le sous le nom `handwriting_ocr.py` et exécutez‑le depuis votre terminal. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Sortie attendue + +Lorsque le script s’exécute correctement, vous verrez quelque chose comme : + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Si le moteur OCR ne détecte aucun caractère, le champ `text` sera une chaîne vide. Dans ce cas, revérifiez la qualité de l’image ou essayez un scan à plus haute résolution. + +## Explication étape par étape + +### Étape 1 – Instance **create OCR engine python** + +La classe `OcrEngine` est le point d’entrée. Pensez‑y comme à un cahier vierge — rien ne se passe tant que vous ne lui indiquez pas la langue attendue et si vous traitez de l’écriture manuscrite. + +### Étape 2 – Choisissez une langue qui prend en charge l’écriture manuscrite + +`ocr.Language.EXTENDED_LATIN` n’est pas seulement « English ». Il regroupe un ensemble d’écritures basées sur le latin et, surtout, inclut des modèles entraînés sur des échantillons cursifs. Sauter cette étape conduit souvent à une sortie brouillée car le moteur utilise par défaut un modèle de texte imprimé. + +### Étape 3 – **turn on handwritten mode** + +Appeler `enable_handwritten_mode(True)` bascule un drapeau interne. Le moteur passe alors à son réseau neuronal ajusté pour les espacements irréguliers et les largeurs de traits variables que l’on trouve dans les notes du monde réel. Oublier cette ligne est une erreur courante ; le moteur traitera vos griffonnages comme du bruit. + +### Étape 4 – Fournissez l’image et **recognize handwritten text** + +`recognize_image` fait le travail lourd : il prétraite le bitmap, le fait passer par le modèle d’écriture manuscrite, et renvoie un objet avec l’attribut `text`. Vous pouvez également inspecter `handwritten_result.confidence` si vous avez besoin d’une métrique de qualité. + +### Étape 5 – Imprimez le résultat et **read handwritten notes** + +`print(handwritten_result.text)` est la façon la plus simple de vérifier que vous avez bien **extract text from image**. En production, vous stockeriez probablement la chaîne dans une base de données ou la transmettriez à un autre service. + +## Gestion des cas limites et variations courantes + +| Situation | Action | +|-----------|--------| +| **L'image est tournée** | Utilisez Pillow pour faire pivoter (`Image.rotate(angle)`) avant d’appeler `recognize_image`. | +| **Faible contraste** | Convertissez en niveaux de gris et appliquez un seuillage adaptatif (`Image.point(lambda p: p > 128 and 255)`). | +| **Pages multiples** | Bouclez sur une liste de chemins de fichiers et concaténez les résultats. | +| **Écritures non latines** | Remplacez `EXTENDED_LATIN` par `ocr.Language.CHINESE` (ou approprié) et conservez `enable_handwritten_mode(True)`. | +| **Problèmes de performance** | Réutilisez la même instance `ocr_engine` pour de nombreuses images ; l’initialiser à chaque fois ajoute une surcharge. | + +### Astuce sur l’utilisation de la mémoire + +Si vous traitez des centaines de notes en lot, appelez `ocr_engine.dispose()` une fois terminé. Cela libère les ressources natives que le wrapper Python peut retenir. + +## Récapitulatif visuel rapide + +![exemple de reconnaissance de texte manuscrit](https://example.com/handwritten-note.png "exemple de reconnaissance de texte manuscrit") + +*L’image ci‑dessus montre une note manuscrite typique que notre script peut transformer en texte brut.* + +## Exemple complet fonctionnel (script monofichier) + +Pour ceux qui aiment la simplicité du copier‑coller, voici le script complet à nouveau, sans les commentaires explicatifs : + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Exécutez‑le avec : + +```bash +python handwriting_ocr.py +``` + +Vous devriez maintenant voir la sortie **recognize handwritten text** dans votre console. + +## Conclusion + +Nous venons de couvrir tout ce dont vous avez besoin pour **recognize handwritten text** en Python — en partant d’un appel frais **create OCR engine python**, en sélectionnant la bonne langue, **turn on handwritten mode**, et enfin **extract text from image** pour **read handwritten notes**. + +Dans un script unique et autonome, vous pouvez passer d’une photo floue d’un gribouillage de réunion à du texte propre et interrogeable. Ensuite, pensez à injecter la sortie dans un pipeline de traitement du langage naturel, à la stocker dans un index interrogeable, ou même à la renvoyer à un service de transcription pour la génération de voix off. + +### Où aller à partir d’ici ? + +- **Batch processing** : Enveloppez le script dans une boucle pour gérer un dossier de scans. +- **Confidence filtering** : Utilisez `result.confidence` pour éliminer les lectures de faible qualité. +- **Alternative libraries** : Si `ocr` n’est pas parfaitement adapté, explorez `pytesseract` avec `--psm 13` pour le mode manuscrit. +- **UI integration** : Combinez avec Flask ou FastAPI pour offrir un service de téléchargement web. + +Des questions sur un format d’image particulier ou besoin d’aide pour ajuster le modèle ? Laissez un commentaire ci‑dessous, et bon codage ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/german/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..c5a86400a --- /dev/null +++ b/ocr/german/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-04-26 +description: Erfahren Sie, wie Sie das HuggingFace‑Modell in Python herunterladen + und Text aus einem Bild in Python extrahieren, während Sie die OCR‑Genauigkeit in + Python mit Aspose OCR Cloud verbessern. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: de +og_description: Lade das Huggingface‑Modell für Python herunter und verbessere deine + OCR‑Pipeline. Folge dieser Anleitung, um Text aus Bildern mit Python zu extrahieren + und die OCR‑Genauigkeit mit Python zu erhöhen. +og_title: huggingface‑Modell Python herunterladen – Vollständiges OCR‑Verbesserungs‑Tutorial +tags: +- OCR +- HuggingFace +- Python +- AI +title: Huggingface‑Modell Python herunterladen – Schritt‑für‑Schritt OCR‑Boost‑Anleitung +url: /de/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – Komplettes OCR‑Verbesserungs‑Tutorial + +Haben Sie schon einmal versucht, **download HuggingFace model python** herunterzuladen und waren dabei etwas ratlos? Sie sind nicht allein. In vielen Projekten ist der größte Engpass, ein gutes Modell auf Ihren Rechner zu bekommen und dann die OCR‑Ergebnisse tatsächlich nutzbar zu machen. + +In diesem Leitfaden gehen wir Schritt für Schritt durch ein praktisches Beispiel, das Ihnen genau zeigt, wie Sie **download HuggingFace model python** ausführen, Text aus einem Bild mit **extract text from image python** extrahieren und anschließend **improve OCR accuracy python** mithilfe des AI‑Post‑Processors von Aspose verbessern. Am Ende haben Sie ein einsatzbereites Skript, das ein verrauschtes Rechnungsbild in sauberen, lesbaren Text verwandelt – kein Zauber, nur klare Schritte. + +## What You’ll Need + +- Python 3.9+ (der Code funktioniert auch mit 3.11) +- Eine Internetverbindung für den einmaligen Modell‑Download +- Das Paket `asposeocrcloud` (`pip install asposeocrcloud`) +- Ein Beispielbild (z. B. `sample_invoice.png`) in einem von Ihnen verwalteten Ordner + +Das ist alles – keine schweren Frameworks, keine GPU‑spezifischen Treiber, es sei denn, Sie möchten die Verarbeitung beschleunigen. + +Jetzt tauchen wir in die eigentliche Implementierung ein. + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## Step 1: Set Up the OCR Engine and Choose a Language +*(Hier beginnen wir mit **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Why this matters:** +Die OCR‑Engine ist die erste Verteidigungslinie; die Wahl des richtigen Sprachpakets reduziert sofort Zeichen­erkennungs‑Fehler, was ein zentraler Teil von **improve OCR accuracy python** ist. + +## Step 2: Configure the AsposeAI Model – Downloading from HuggingFace +*(Hier führen wir tatsächlich **download HuggingFace model python** aus.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**What’s happening under the hood?** +Wenn `allow_auto_download` auf `true` gesetzt ist, kontaktiert das SDK HuggingFace, holt das Modell `Qwen2.5‑3B‑Instruct‑GGUF` und speichert es im angegebenen Ordner. Das ist der Kern von **download huggingface model python** – das SDK übernimmt die schwere Arbeit, sodass Sie keine `git clone`‑ oder `wget`‑Befehle selbst schreiben müssen. + +*Pro tip:* Platzieren Sie `directory_model_path` auf einer SSD für schnellere Ladezeiten; das Modell ist selbst in `int8`‑Form etwa 3 GB groß. + +## Step 3: Attach the AI Engine to the OCR Engine +*(Verknüpfen der beiden Komponenten, damit wir **improve OCR accuracy python** können.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Why bind them?** +Die OCR‑Engine liefert Rohtext, der Rechtschreibfehler, Zeilenumbrüche oder falsche Interpunktion enthalten kann. Die AI‑Engine wirkt als intelligenter Editor und bereinigt diese Probleme – genau das, was Sie benötigen, um **improve OCR accuracy python** zu erreichen. + +## Step 4: Run OCR on Your Image +*(Der Moment, in dem wir endlich **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` enthält nun ein `text`‑Attribut mit den rohen Zeichen, die die Engine erkannt hat. In der Praxis werden Sie ein paar Stolpersteine bemerken – vielleicht wird „Invoice“ zu „Inv0ice“ oder ein Zeilenumbruch erscheint mitten im Satz. + +## Step 5: Clean Up with the AI Post‑Processor +*(Dieser Schritt verbessert direkt **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +Das AI‑Modell schreibt den Text neu und wendet sprachspezifische Korrekturen an. Da wir ein instruktions‑feinabgestimmtes Modell von HuggingFace verwenden, ist die Ausgabe in der Regel flüssig und bereit für nachgelagerte Verarbeitung. + +## Step 6: Show the Before and After +*(Ein kurzer Plausibilitäts‑Check, um zu sehen, wie gut wir **extract text from image python** und **improve OCR accuracy python**.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Expected Output + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Beachten Sie, wie die KI „Inv0ice“ zu „Invoice“ korrigiert und überflüssige Zeilenumbrüche entfernt hat. Das ist das greifbare Ergebnis von **improve OCR accuracy python** mit einem heruntergeladenen HuggingFace‑Modell. + +## Frequently Asked Questions (FAQ) + +### Do I need a GPU to run the model? +No. The `gpu_layers=20` setting tells the SDK to use up to 20 GPU layers if a compatible GPU is present; otherwise it falls back to CPU. On a modern laptop the CPU path still processes a few hundred tokens per second—perfect for occasional **invoice** parsing. + +### What if the model fails to download? +Make sure your environment can reach `https://huggingface.co`. If you’re behind a corporate proxy, set the `HTTP_PROXY` and `HTTPS_PROXY` environment variables. The SDK will retry automatically, but you can also manually `git lfs pull` the repo into `directory_model_path`. + +### Can I swap the model for a smaller one? +Absolutely. Just replace `hugging_face_repo_id` with another repo (e.g., `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) and adjust `hugging_face_quantization` accordingly. Smaller models download faster and consume less RAM, though you may lose a bit of correction quality. + +### How does this help me **extract text from image python** in other domains? +The same pipeline works for receipts, passports, or handwritten notes. The only change is the language pack (`ocr.Language.FRENCH`, etc.) and possibly a domain‑specific fine‑tuned model from HuggingFace. + +## Bonus: Automating Multiple Files + +If you have a folder full of images, wrap the OCR call in a simple loop: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +This tiny addition lets you **download huggingface model python** once, then batch‑process dozens of files—great for scaling your document‑automation pipeline. + +## Conclusion + +We’ve just walked through a complete, end‑to‑end example that shows you how to **download HuggingFace model python**, **extract text from image python**, and **improve OCR accuracy python** using Aspose’s OCR Cloud and an AI post‑processor. The script is ready to run, the concepts are explained, and you’ve seen the before‑and‑after output so you know it works. + +What’s next? Try swapping in a different HuggingFace model, experiment with other language packs, or feed the cleaned text into a downstream NLP pipeline (e.g., entity extraction for invoice line items). The sky’s the limit, and the foundation you just built is solid. + +Got questions or a tricky image that still trips the OCR? Drop a comment below, and let’s troubleshoot together. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/german/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..2aeeeadad --- /dev/null +++ b/ocr/german/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-04-26 +description: Laden Sie das OCR‑Modell schnell mit Aspose OCR Python herunter. Erfahren + Sie, wie Sie das Modelldirectory festlegen, den Modellpfad konfigurieren und das + Modell in wenigen Zeilen herunterladen. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: de +og_description: Download OCR‑Modell in Sekunden mit Aspose OCR Python. Dieser Leitfaden + zeigt, wie man das Modelldirectory festlegt, den Modellpfad konfiguriert und das + Modell sicher herunterlädt. +og_title: OCR‑Modell herunterladen – Vollständiges Aspose OCR Python‑Tutorial +tags: +- OCR +- Python +- Aspose +title: OCR‑Modell mit Aspose OCR Python herunterladen – Schritt‑für‑Schritt‑Anleitung +url: /de/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – Vollständiges Aspose OCR Python Tutorial + +Haben Sie sich schon einmal gefragt, wie man **download ocr model** mit Aspose OCR in Python herunterlädt, ohne endlos durch die Dokumentation zu wühlen? Sie sind nicht allein. Viele Entwickler stoßen auf ein Problem, wenn das Modell nicht lokal vorhanden ist und das SDK einen kryptischen Fehler wirft. Die gute Nachricht? Die Lösung besteht aus ein paar Zeilen Code, und Sie haben das Modell in wenigen Minuten einsatzbereit. + +In diesem Tutorial gehen wir alles durch, was Sie wissen müssen: vom Import der richtigen Klassen über das **set model directory** bis hin zum eigentlichen **how to download model** und schließlich der Pfad‑Verifizierung. Am Ende können Sie OCR auf jedem Bild mit einem einzigen Funktionsaufruf ausführen und verstehen die **configure model path**‑Optionen, die Ihr Projekt aufgeräumt halten. Kein Schnickschnack, nur ein praktisches, ausführbares Beispiel für **aspose ocr python**‑Nutzer. + +## What You’ll Learn + +- Wie man die Aspose OCR Cloud‑Klassen korrekt importiert. +- Die genauen Schritte, um **download ocr model** automatisch zu **download ocr model**. +- Möglichkeiten, **set model directory** und **configure model path** für reproduzierbare Builds zu setzen. +- Wie man überprüft, dass das Modell initialisiert ist und wo es auf der Festplatte liegt. +- Häufige Stolperfallen (Berechtigungen, fehlende Verzeichnisse) und schnelle Lösungen. + +### Prerequisites + +- Python 3.8+ auf Ihrem Rechner installiert. +- `asposeocrcloud`‑Paket (`pip install asposeocrcloud`). +- Schreibrechte für einen Ordner, in dem Sie das Modell speichern möchten (z. B. `C:\models` oder `~/ocr_models`). + +--- + +## Step 1: Import Aspose OCR Cloud Classes + +Das Erste, was Sie benötigen, ist die richtige Import‑Anweisung. Sie lädt die Klassen, die die Modellkonfiguration und OCR‑Operationen verwalten. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Warum das wichtig ist:* `AsposeAI` ist die Engine, die OCR ausführt, während `AsposeAIModelConfig` der Engine sagt, **wo** das Modell zu finden ist und **ob** es automatisch heruntergeladen werden soll. Das Überspringen dieses Schritts oder das Importieren des falschen Moduls führt zu einem `ModuleNotFoundError`, bevor Sie überhaupt zum Download‑Teil kommen. + +--- + +## Step 2: Define the Model Configuration (Set Model Directory & Configure Model Path) + +Jetzt teilen wir Aspose mit, wo die Modelldateien abgelegt werden sollen. Hier setzen Sie **set model directory** und **configure model path**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Tipps & Fallen** + +- **Absolute Pfade** vermeiden Verwirrung, wenn das Skript aus einem anderen Arbeitsverzeichnis ausgeführt wird. +- Unter Linux/macOS können Sie `"/home/you/ocr_models"` verwenden; unter Windows setzen Sie ein Präfix `r`, um Backslashes wörtlich zu behandeln. +- Das Setzen von `allow_auto_download="true"` ist der Schlüssel zu **how to download model**, ohne zusätzlichen Code zu schreiben. + +--- + +## Step 3: Create the AsposeAI Instance Using the Configuration + +Mit der fertigen Konfiguration erzeugen Sie die OCR‑Engine. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Warum das wichtig ist:* Das Objekt `ocr_ai` enthält nun die gerade definierte Konfiguration. Wenn das Modell nicht vorhanden ist, löst der nächste Aufruf den automatischen Download aus — das ist das Kernstück von **how to download model** in einer hands‑off‑Weise. + +--- + +## Step 4: Trigger the Model Download (If Needed) + +Bevor Sie OCR ausführen können, müssen Sie sicherstellen, dass das Modell tatsächlich auf der Festplatte liegt. Die Methode `is_initialized()` prüft und initiiert gleichzeitig. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**Was im Hintergrund passiert** + +- Der erste Aufruf von `is_initialized()` liefert `False`, weil der Modellordner leer ist. +- Der `print` informiert den Nutzer, dass ein Download bevorsteht. +- Der zweite Aufruf zwingt Aspose, das Modell aus dem zuvor angegebenen Hugging Face‑Repo zu holen. +- Nach dem Download gibt die Methode bei nachfolgenden Prüfungen `True` zurück. + +**Randfall:** Wenn Ihr Netzwerk Hugging Face blockiert, erhalten Sie eine Ausnahme. In diesem Fall laden Sie das Modell‑ZIP manuell herunter, entpacken es in `directory_model_path` und führen das Skript erneut aus. + +--- + +## Step 5: Report the Local Path Where the Model Is Now Available + +Nachdem der Download abgeschlossen ist, möchten Sie wahrscheinlich wissen, wo die Dateien gelandet sind. Das hilft beim Debuggen und beim Einrichten von CI‑Pipelines. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Typische Ausgabe sieht so aus: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Jetzt haben Sie erfolgreich **download ocr model** durchgeführt, das Verzeichnis gesetzt und den Pfad bestätigt. + +--- + +## Visual Overview + +Unten sehen Sie ein einfaches Diagramm, das den Ablauf von der Konfiguration bis zum einsatzbereiten Modell zeigt. + +![Download‑OCR‑Modell‑Flussdiagramm, das Konfiguration, automatischen Download und lokalen Pfad zeigt](/images/download-ocr-model-flow.png) + +*Alt‑Text enthält das Haupt‑Keyword für SEO.* + +--- + +## Common Variations & How to Handle Them + +### 1. Using a Different Model Repository + +Wenn Sie ein anderes Modell als `openai/gpt2` benötigen, ersetzen Sie einfach den Wert von `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Stellen Sie sicher, dass das Repository öffentlich ist oder dass Sie das erforderliche Token in Ihrer Umgebung gesetzt haben. + +### 2. Disabling Automatic Download + +Manchmal möchten Sie den Download selbst steuern (z. B. in luft‑abgesperrten Umgebungen). Setzen Sie `allow_auto_download` auf `"false"` und führen Sie ein eigenes Download‑Skript aus, bevor Sie initialisieren: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Changing the Model Directory at Runtime + +Sie können den Pfad neu konfigurieren, ohne das `AsposeAI`‑Objekt neu zu erstellen: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Pro Tips for Production Use + +- **Cache the model**: Legen Sie das Verzeichnis auf einem gemeinsamen Netzlaufwerk ab, wenn mehrere Services dasselbe Modell benötigen. So vermeiden Sie redundante Downloads. +- **Version pinning**: Das Hugging Face‑Repo kann sich ändern. Um eine bestimmte Version zu fixieren, hängen Sie `@v1.0.0` an die Repo‑ID an (`"openai/gpt2@v1.0.0"`). +- **Permissions**: Stellen Sie sicher, dass der Benutzer, der das Skript ausführt, Lese‑/Schreibrechte für `directory_model_path` hat. Unter Linux reicht meist `chmod 755`. +- **Logging**: Ersetzen Sie die einfachen `print`‑Anweisungen durch das Python‑`logging`‑Modul für bessere Beobachtbarkeit in größeren Anwendungen. + +--- + +## Full Working Example (Copy‑Paste Ready) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Erwartete Ausgabe** (der erste Durchlauf lädt das Modell herunter, spätere Durchläufe überspringen den Download): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Führen Sie das Skript erneut aus; Sie sehen nur die Zeile mit dem Pfad, weil das Modell bereits im Cache ist. + +--- + +## Conclusion + +Wir haben den kompletten Prozess zum **download ocr model** mit Aspose OCR Python behandelt, gezeigt, wie man **set model directory** setzt, und die Feinheiten von **configure model path** erklärt. Mit nur wenigen Code‑Zeilen können Sie den Download automatisieren, manuelle Schritte vermeiden und Ihre OCR‑Pipeline reproduzierbar halten. + +Als Nächstes könnten Sie den eigentlichen OCR‑Aufruf (`ocr_ai.recognize_image(...)`) erkunden oder ein anderes Hugging Face‑Modell testen, um die Genauigkeit zu verbessern. Wie auch immer, das Fundament, das Sie hier gebaut haben — klare Konfiguration, automatischer Download und Pfad‑Verifizierung — macht jede zukünftige Integration zum Kinderspiel. + +Haben Sie Fragen zu Randfällen oder möchten teilen, wie Sie das Modell‑Verzeichnis für Cloud‑Deployments angepasst haben? Hinterlassen Sie einen Kommentar unten, und happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/german/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..8c9cb699f --- /dev/null +++ b/ocr/german/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-04-26 +description: Wie man OCR‑Ergebnisse nachbearbeitet und Text mit Koordinaten extrahiert. + Lernen Sie eine Schritt‑für‑Schritt‑Lösung mit strukturierten Ausgaben und KI‑Korrektur. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: de +og_description: Wie man OCR‑Ergebnisse nachbearbeitet und Text mit Koordinaten extrahiert. + Folgen Sie diesem umfassenden Tutorial für einen zuverlässigen Arbeitsablauf. +og_title: Wie man OCR nachbearbeitet – Vollständiger Leitfaden +tags: +- OCR +- Python +- AI +- Text Extraction +title: Wie man OCR nachbearbeitet – Text mit Koordinaten in Python extrahieren +url: /de/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man OCR nachbearbeitet – Text mit Koordinaten in Python extrahiert + +Hast du jemals **wie man OCR nachbearbeitet** Ergebnisse benötigt, weil die Rohausgabe verrauscht oder fehlerhaft ausgerichtet war? Du bist nicht allein. In vielen realen Projekten — Rechnungs‑Scanning, Beleg‑Digitalisierung oder sogar die Erweiterung von AR‑Erlebnissen — liefert die OCR‑Engine rohe Wörter, aber du musst sie trotzdem bereinigen und verfolgen, wo jedes Wort auf der Seite liegt. Genau hier glänzt ein strukturierter Ausgabemodus kombiniert mit einem KI‑gesteuerten Nachbearbeiter. + +> **Pro‑Tipp:** Wenn du eine andere OCR‑Bibliothek nutzt, suche nach einem „structured“ oder „layout“ Modus; die Konzepte bleiben gleich. + +--- + +## Voraussetzungen + +Bevor wir loslegen, stelle sicher, dass du Folgendes hast: + +| Anforderung | Warum es wichtig ist | +|-------------|----------------------| +| Python 3.9+ | Moderne Syntax und Type Hints | +| `ocr`‑Bibliothek, die `OutputMode.STRUCTURED` unterstützt (z. B. ein fiktives `myocr`) | Benötigt für Begrenzungs‑Box‑Daten | +| Ein KI‑Nachbearbeitungs‑Modul (kann OpenAI, HuggingFace oder ein eigenes Modell sein) | Verbessert die Genauigkeit nach der OCR | +| Eine Bilddatei (`input.png`) in deinem Arbeitsverzeichnis | Die Quelle, die wir einlesen werden | + +Falls dir etwas unbekannt vorkommt, installiere einfach die Platzhalter‑Pakete mit `pip install myocr ai‑postproc`. Der Code unten enthält außerdem Fallback‑Stubs, sodass du den Ablauf ohne die echten Bibliotheken testen kannst. + +--- + +## Schritt 1: Strukturierte Ausgabemodus für die OCR‑Engine aktivieren + +Das Erste, was wir tun, ist der OCR‑Engine mitzuteilen, dass sie uns mehr als nur reinen Text liefern soll. Strukturierte Ausgabe liefert jedes Wort zusammen mit seiner Begrenzungs‑Box und dem Vertrauens‑Score, was später für **Text mit Koordinaten extrahieren** unerlässlich ist. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Warum das wichtig ist:* Ohne strukturierten Modus würdest du nur einen langen String erhalten und die räumlichen Informationen verlieren, die du für das Überlagern von Text auf Bildern oder für nachgelagerte Layout‑Analysen brauchst. + +--- + +## Schritt 2: Bild erkennen und Wörter, Boxen sowie Vertrauenswerte erfassen + +Jetzt übergeben wir das Bild an die Engine. Das Ergebnis ist ein Objekt, das eine Liste von Wort‑Objekten enthält, wobei jedes `text`, `x`, `y`, `width`, `height` und `confidence` bereitstellt. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Randfall:* Wenn das Bild leer oder nicht lesbar ist, wird `structured_result.words` eine leere Liste sein. Es ist gute Praxis, das zu prüfen und elegant zu behandeln. + +--- + +## Schritt 3: KI‑basierte Nachbearbeitung durchführen und Positionen beibehalten + +Selbst die besten OCR‑Engines machen Fehler — z. B. „O“ vs. „0“ oder fehlende Diakritika. Ein KI‑Modell, das auf domänenspezifischen Text trainiert ist, kann diese Fehler korrigieren. Wichtig ist, dass wir die ursprünglichen Koordinaten beibehalten, damit das räumliche Layout intakt bleibt. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Warum wir die Koordinaten beibehalten:* Viele nachgelagerte Aufgaben (z. B. PDF‑Erstellung, AR‑Beschriftung) benötigen die exakte Platzierung. Die KI berührt nur das Feld `text` und lässt `x`, `y`, `width`, `height` unverändert. + +--- + +## Schritt 4: Durch die korrigierten Wörter iterieren und deren Text mit Koordinaten anzeigen + +Abschließend durchlaufen wir die korrigierten Wörter und geben jedes Wort zusammen mit seiner oberen linken Ecke `(x, y)` aus. Das erfüllt das Ziel **Text mit Koordinaten extrahieren**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Erwartete Ausgabe (Beispiel):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Jede Zeile zeigt das korrigierte Wort und seine genaue Position im Originalbild. + +--- + +## Vollständiges funktionierendes Beispiel + +Unten findest du ein einzelnes Skript, das alles zusammenführt. Du kannst es kopieren, die Import‑Anweisungen an deine tatsächlichen Bibliotheken anpassen und direkt ausführen. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Ausführen des Skripts** + +```bash +python ocr_postprocess_demo.py +``` + +Wenn du die echten Bibliotheken installiert hast, verarbeitet das Skript dein `input.png`. Andernfalls lässt dich die Stub‑Implementierung den erwarteten Ablauf und die Ausgabe sehen, ohne externe Abhängigkeiten. + +--- + +## Häufig gestellte Fragen (FAQ) + +| Frage | Antwort | +|----------|--------| +| *Funktioniert das mit Tesseract?* | Tesseract selbst stellt keinen strukturierten Modus out‑of‑the‑box bereit, aber Wrapper wie `pytesseract.image_to_data` geben Begrenzungs‑Boxen zurück, die du in dieselbe KI‑Nachbearbeitung einspeisen kannst. | +| *Was, wenn ich die rechte untere Ecke statt der oberen linken benötige?* | Jedes Wort‑Objekt liefert auch `width` und `height`. Berechne `x2 = x + width` und `y2 = y + height`, um die gegenüberliegende Ecke zu erhalten. | +| *Kann ich mehrere Bilder stapelweise verarbeiten?* | Absolut. Packe die Schritte in eine `for image_path in Path("folder").glob("*.png"):` Schleife und sammle die Ergebnisse pro Datei. | +| *Wie wähle ich ein KI‑Modell für die Korrektur aus?* | Für generischen Text funktioniert ein kleiner, auf OCR‑Fehler feinabgestimmter GPT‑2. Für domänenspezifische Daten (z. B. medizinische Rezepte) trainiere ein Sequence‑to‑Sequence‑Modell auf gepaarten Rauschen‑Sauber‑Daten. | +| *Ist der Vertrauens‑Score nach der KI‑Korrektur noch nützlich?* | Du kannst den ursprünglichen Score weiterhin zum Debuggen behalten, aber die KI kann ihren eigenen Score ausgeben, falls das Modell das unterstützt. | + +--- + +## Randfälle & bewährte Methoden + +1. **Leere oder beschädigte Bilder** – prüfe immer, dass `structured_result.words` nicht leer ist, bevor du fortfährst. +2. **Nicht‑lateinische Schriften** – stelle sicher, dass deine OCR‑Engine für die Zielsprache konfiguriert ist; die KI‑Nachbearbeitung muss auf derselben Schrift trainiert sein. +3. **Performance** – KI‑Korrektur kann teuer sein. Cache Ergebnisse, wenn du dasselbe Bild wiederverwendest, oder führe den KI‑Schritt asynchron aus. +4. **Koordinatensystem** – OCR‑Bibliotheken können unterschiedliche Ursprünge verwenden (oben‑links vs. unten‑links). Passe das beim Überlagern auf PDFs oder Canvas‑Elemente an. + +--- + +## Fazit + +Du hast jetzt ein solides, End‑zu‑End‑Rezept, um **wie man OCR nachbearbeitet** und zuverlässig **Text mit Koordinaten extrahiert**. Durch das Aktivieren der strukturierten Ausgabe, das Durchlaufen des Ergebnisses über eine KI‑Korrekturschicht und das Beibehalten der ursprünglichen Begrenzungs‑Boxen kannst du verrauschte OCR‑Scans in sauberen, räumlich‑bewussten Text verwandeln, der für nachgelagerte Aufgaben wie PDF‑Erstellung, Daten‑Entry‑Automatisierung oder Augmented‑Reality‑Overlays bereitsteht. + +Bereit für den nächsten Schritt? Versuche, die Stub‑KI durch einen OpenAI `gpt‑4o‑mini` Aufruf zu ersetzen oder integriere die Pipeline in ein FastAPI‑Projekt. + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/german/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..3f3837e74 --- /dev/null +++ b/ocr/german/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-04-26 +description: Wie man Bilder schnell mit Python erkennt. Lernen Sie eine Bilderkennungspipeline, + Stapelverarbeitung und automatisieren Sie die Bilderkennung mithilfe von KI. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: de +og_description: Wie man Bilder schnell mit Python erkennt. Dieser Leitfaden führt + durch eine Bild­erkennungs‑Pipeline, Batch‑Verarbeitung und Automatisierung mit + KI. +og_title: Wie man Bilder erkennt – Automatisieren einer Bild­erkennungs-Pipeline +tags: +- image-processing +- python +- ai +title: Wie man Bilder erkennt – Automatisieren einer Bild­erkennungs‑Pipeline +url: /de/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man Bilder erkennt – Automatisieren einer Bild‑Erkennungs‑Pipeline + +Haben Sie sich jemals gefragt, **wie man Bilder erkennt**, ohne tausende Zeilen Code zu schreiben? Sie sind nicht allein – viele Entwickler stoßen an dieselbe Grenze, wenn sie zum ersten Mal Dutzende oder Hunderte von Bildern verarbeiten müssen. Die gute Nachricht? Mit ein paar übersichtlichen Schritten können Sie eine vollwertige Bild‑Erkennungs‑Pipeline aufsetzen, die Stapel verarbeitet, ausführt und sich selbst aufräumt. + +In diesem Tutorial gehen wir ein vollständiges, ausführbares Beispiel durch, das zeigt, **wie man Bilder stapelt**, jedes Bild an eine KI‑Engine übergibt, die Ergebnisse nachverarbeitet und schließlich Ressourcen freigibt. Am Ende haben Sie ein eigenständiges Skript, das Sie in jedes Projekt einbinden können, egal ob Sie einen Foto‑Tagger, ein Qualitäts‑Kontroll‑System oder einen Forschungs‑Datensatz‑Generator bauen. + +## Was Sie lernen werden + +- **Wie man Bilder erkennt** mithilfe einer Mock‑KI‑Engine (das Muster ist identisch für echte Dienste wie TensorFlow, PyTorch oder Cloud‑APIs). +- Wie man eine **Bild‑Erkennungs‑Pipeline** erstellt, die Stapel effizient verarbeitet. +- Der beste Weg, **Bild‑Erkennung zu automatisieren**, sodass Sie nicht jedes Mal manuell über Dateien iterieren müssen. +- Tipps zum Skalieren der Pipeline und zum sicheren Freigeben von Ressourcen. + +> **Voraussetzungen:** Python 3.8+, Grundkenntnisse von Funktionen und Schleifen sowie ein paar Bilddateien (oder Pfade), die Sie verarbeiten möchten. Für das Kernbeispiel sind keine externen Bibliotheken nötig, wir erwähnen jedoch, wo Sie echte KI‑SDKs einbinden könnten. + +![Diagramm, wie man Bilder in einer Stapel‑Verarbeitungspipeline erkennt](pipeline.png "Diagramm, wie man Bilder erkennt") + +## Schritt 1: Bilder stapeln – Wie man Bilder effizient stapelt + +Bevor die KI irgendeine schwere Arbeit übernimmt, benötigen Sie eine Sammlung von Bildern, die Sie ihr zuführen. Denken Sie dabei an Ihre Einkaufsliste; die Engine wird später jedes Element nacheinander von der Liste nehmen. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Warum stapeln?** +Stapeln reduziert die Menge an Boiler‑Plate‑Code, die Sie schreiben müssen, und macht es trivial, später Parallelität hinzuzufügen. Wenn Sie jemals 10 000 Bilder verarbeiten müssen, ändern Sie nur die Quelle von `image_batch` – der Rest der Pipeline bleibt unverändert. + +## Schritt 2: Bild‑Erkennungs‑Pipeline ausführen (Bilder mit KI erkennen) + +Jetzt verbinden wir den Stapel mit dem eigentlichen Erkenner. In einem realen Szenario würden Sie `torchvision.models` oder einen Cloud‑Endpoint aufrufen; hier simulieren wir das Verhalten, damit das Tutorial eigenständig bleibt. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Erklärung:** +- `engine.recognize_image` ist das Herzstück der **Bild‑Erkennungs‑Pipeline**; es könnte ein Aufruf zu einem Deep‑Learning‑Modell oder einer REST‑API sein. +- `postprocessor.run` demonstriert **Bild‑Erkennung automatisieren**, indem rohe Vorhersagen in ein sauberes Dictionary normalisiert werden, das Sie speichern oder streamen können. +- Wir sammeln jedes `corrected`‑Dictionary in `recognized_results`, sodass nachgelagerte Schritte (z. B. Datenbank‑Einfügung) unkompliziert sind. + +## Schritt 3: Nachverarbeiten und speichern – Ergebnisse der Bild‑Erkennung automatisieren + +Nachdem Sie eine ordentliche Liste von Vorhersagen haben, möchten Sie diese typischerweise persistieren. Das Beispiel unten schreibt eine CSV‑Datei; Sie können leicht eine Datenbank oder Message‑Queue einsetzen. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Warum CSV?** +CSV ist universell lesbar – Excel, pandas und sogar reine Text‑Editoren können sie öffnen. Wenn Sie später **Bild‑Erkennung automatisieren** in großem Maßstab benötigen, ersetzen Sie den Schreib‑Block durch einen Bulk‑Insert in Ihren Data‑Lake. + +## Schritt 4: Aufräumen – KI‑Ressourcen sicher freigeben + +Viele KI‑SDKs reservieren GPU‑Speicher oder starten Worker‑Threads. Das Vergessen, diese freizugeben, kann zu Speicher‑Leaks und unangenehmen Abstürzen führen. Auch wenn unsere Mock‑Objekte das nicht benötigen, zeigen wir das korrekte Muster. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +Das Ausführen des Skripts gibt eine freundliche Bestätigung aus und signalisiert, dass die Pipeline sauber beendet wurde. + +## Voll funktionsfähiges Skript + +Alles zusammengefügt, hier das komplette, copy‑and‑paste‑bereite Programm: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Erwartete Ausgabe + +Wenn Sie das Skript ausführen (vorausgesetzt, die drei Platzhalter‑Pfade existieren), sehen Sie etwa Folgendes: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +Und die erzeugte `recognition_results.csv` enthält: + +| Bild | Label | Vertrauen | +|---------------------|-------|-----------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Fazit + +Sie haben nun ein solides End‑zu‑End‑Beispiel, **wie man Bilder erkennt** in Python, komplett mit einer **Bild‑Erkennungs‑Pipeline**, Stapel‑Handling und automatisierter Nachverarbeitung. Das Muster skaliert: Ersetzen Sie die Mock‑Klassen durch ein echtes Modell, geben Sie ein größeres `image_batch` ein, und Sie haben eine produktionsreife Lösung. + +Möchten Sie weitergehen? Probieren Sie die nächsten Schritte aus: + +- Ersetzen Sie `MockEngine` durch ein TensorFlow‑ oder PyTorch‑Modell für echte Vorhersagen. +- Parallelisieren Sie die Schleife mit `concurrent.futures.ThreadPoolExecutor`, um große Stapel zu beschleunigen. +- Binden Sie den CSV‑Writer in einen Cloud‑Storage‑Bucket ein, um **Bild‑Erkennung zu automatisieren** über verteilte Worker hinweg. + +Experimentieren Sie, brechen Sie Dinge und reparieren Sie sie anschließend – so meistern Sie Bild‑Erkennungs‑Pipelines wirklich. Wenn Sie auf Probleme stoßen oder Ideen für Verbesserungen haben, hinterlassen Sie einen Kommentar unten. Viel Spaß beim Coden! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/german/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..f56f05ee7 --- /dev/null +++ b/ocr/german/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-26 +description: Kreditkartennummern schnell maskieren mit AsposeAI OCR‑Nachbearbeitung. + Lernen Sie PCI‑Konformität, Maskierung mit regulären Ausdrücken und Datenbereinigung + in einer Schritt‑für‑Schritt‑Anleitung. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: de +og_description: Maskieren Sie Kreditkartennummern in OCR‑Ergebnissen mit AsposeAI. + Dieses Tutorial behandelt PCI‑Konformität, das Maskieren mit regulären Ausdrücken + und Datenbereinigung. +og_title: Kreditkartennummern maskieren – Vollständiger Leitfaden zur Nachbearbeitung + von Python‑OCR. +tags: +- OCR +- Python +- security +title: Kreditkartennummern im OCR-Ausgabe maskieren – Vollständiger Python-Leitfaden +url: /de/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Kreditkartennummern maskieren – Vollständiger Python‑Leitfaden + +Haben Sie jemals **Kreditkartennummern maskieren** müssen in Text, der direkt von einer OCR‑Engine stammt? Sie sind nicht allein. In regulierten Branchen kann die Offenlegung einer vollständigen PAN (Primary Account Number) zu Problemen mit PCI‑Compliance‑Auditoren führen. Die gute Nachricht? Mit ein paar Zeilen Python und dem Post‑Processing‑Hook von AsposeAI können Sie automatisch die mittleren acht Ziffern verbergen und auf der sicheren Seite bleiben. + +In diesem Tutorial gehen wir ein reales Szenario durch: OCR auf ein Beleg‑Bild anwenden und dann eine benutzerdefinierte **OCR‑Post‑Processing**‑Funktion einsetzen, die alle PCI‑Daten bereinigt. Am Ende haben Sie ein wiederverwendbares Snippet, das Sie in jeden AsposeAI‑Workflow einbinden können, sowie einige praktische Tipps zum Umgang mit Randfällen und zur Skalierung der Lösung. + +## Was Sie lernen werden + +- Wie man einen benutzerdefinierten Post‑Processor mit **AsposeAI** registriert. +- Warum ein **Regular‑Expression‑Maskierungs**‑Ansatz sowohl schnell als auch zuverlässig ist. +- Die Grundlagen der **PCI‑Compliance** im Zusammenhang mit Daten‑Sanitisierung. +- Möglichkeiten, das Muster für mehrere Kartenformate oder internationale Nummern zu erweitern. +- Erwartete Ausgabe und wie man überprüft, dass die Maskierung funktioniert hat. + +> **Voraussetzungen** – Sie sollten eine funktionierende Python 3‑Umgebung haben, das Aspose.AI‑für‑OCR‑Paket installiert haben (`pip install aspose-ocr`), und ein Beispielbild (z. B. `receipt.png`) besitzen, das eine Kreditkartennummer enthält. Keine weiteren externen Dienste sind erforderlich. + +--- + +## Schritt 1: Definieren Sie einen Post‑Processor, der Kreditkartennummern maskiert + +Das Herz der Lösung steckt in einer winzigen Funktion, die das OCR‑Ergebnis erhält, eine **Regular‑Expression‑Maskierungs**‑Routine ausführt und den bereinigten Text zurückgibt. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Warum das funktioniert:** +- Der reguläre Ausdruck `(\d{4})\d{8}(\d{4})` trifft exakt 16 aufeinanderfolgende Ziffern, das gängige Format für Visa, MasterCard und viele andere. +- Durch das Erfassen der ersten und letzten vier Ziffern (`\1` und `\2`) bewahren wir genügend Informationen für die Fehlersuche, während wir den **PCI‑Compliance**‑Regeln entsprechen, die das Speichern der vollständigen PAN verbieten. +- Die Ersetzung `\1****\2` verbirgt die sensiblen mittleren acht Ziffern und wandelt `1234567812345678` in `1234****5678` um. + +> **Pro‑Tipp:** Wenn Sie 15‑stellige American‑Express‑Nummern unterstützen müssen, fügen Sie ein zweites Muster wie `r'(\d{4})\d{6}(\d{5})'` hinzu und führen beide Ersetzungen nacheinander aus. + +--- + +## Schritt 2: Initialisieren Sie die AsposeAI‑Engine + +Bevor wir unseren Post‑Processor anhängen können, benötigen wir eine Instanz der OCR‑Engine. AsposeAI bündelt das OCR‑Modell und eine einfache API für benutzerdefinierte Verarbeitung. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Warum hier initialisieren?** +Das einmalige Erzeugen des `AsposeAI`‑Objekts und dessen Wiederverwendung über mehrere Bilder hinweg reduziert den Overhead. Die Engine cached zudem Sprachmodelle, was nachfolgende Aufrufe beschleunigt – praktisch, wenn Sie Stapel von Belegen scannen. + +--- + +## Schritt 3: Registrieren Sie die benutzerdefinierte Maskierungsfunktion + +AsposeAI stellt die Methode `set_post_processor` bereit, mit der Sie jede aufrufbare Einheit einbinden können. Wir übergeben unsere `mask_pci`‑Funktion zusammen mit einem optionalen Settings‑Dictionary (vorerst leer). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**Was im Hintergrund passiert:** +Wenn Sie später `run_postprocessor` aufrufen, übergibt AsposeAI das rohe OCR‑Ergebnis an `mask_pci`. Die Funktion erhält ein leichtgewichtiges Objekt (`data`), das den erkannten Text enthält, und gibt einen neuen String zurück. Dieses Design lässt das Kern‑OCR unverändert, während Sie **Daten‑Sanitisierungs**‑Richtlinien an einer einzigen Stelle durchsetzen können. + +--- + +## Schritt 4: OCR auf das Beleg‑Bild anwenden + +Jetzt, wo die Engine weiß, wie die Ausgabe zu bereinigen ist, übergeben wir ihr ein Bild. Für dieses Tutorial gehen wir davon aus, dass Sie bereits ein `engine`‑Objekt mit den richtigen Sprach‑ und Auflösungseinstellungen konfiguriert haben. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Tipp:** Wenn Sie kein vorab konfiguriertes Objekt haben, können Sie eines erstellen mit: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +Der Aufruf `recognize_image` liefert ein Objekt zurück, dessen Attribut `text` den rohen, unmaskierten String enthält. + +--- + +## Schritt 5: Registrierten Post‑Processor anwenden + +Mit den rohen OCR‑Daten in der Hand geben wir sie an die AI‑Instanz weiter. Die Engine führt automatisch die zuvor registrierte `mask_pci`‑Funktion aus. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Warum `run_postprocessor` statt eines manuellen Funktionsaufrufs verwenden?** +Damit bleibt der Workflow konsistent, besonders wenn Sie mehrere Post‑Processor haben (z. B. Rechtschreibprüfung, Spracherkennung). AsposeAI stellt sie in der Reihenfolge ihrer Registrierung in eine Warteschlange, was deterministische Ausgaben garantiert. + +--- + +## Schritt 6: Verifizieren Sie die bereinigte Ausgabe + +Zum Schluss geben wir den bereinigten Text aus und prüfen, ob alle Kreditkartennummern korrekt maskiert wurden. + +```python +print(final_result.text) +``` + +**Erwartete Ausgabe** (Auszug): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Enthielt der Beleg keine Kartennummer, bleibt der Text unverändert – nichts zu maskieren, nichts zu befürchten. + +--- + +## Umgang mit Randfällen und gängigen Variationen + +### Mehrere Kartennummern in einem Dokument +Enthält ein Beleg mehr als eine PAN (z. B. eine Treuekarte plus eine Zahlungskarte), führt der reguläre Ausdruck global aus und maskiert automatisch alle Treffer. Kein zusätzlicher Code nötig. + +### Nicht‑standardmäßige Formatierung +Manchmal fügt OCR Leerzeichen oder Bindestriche ein (`1234 5678 1234 5678` oder `1234-5678-1234-5678`). Erweitern Sie das Muster, um diese Zeichen zu ignorieren: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +Das hinzugefügte `[ -]?` toleriert optionale Leerzeichen oder Bindestriche zwischen den Ziffernblöcken. + +### Internationale Karten +Für 19‑stellige PANs, die in manchen Regionen verwendet werden, können Sie das Muster verbreitern: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Denken Sie daran, dass **PCI‑Compliance** weiterhin das Maskieren der mittleren Ziffern vorschreibt, unabhängig von der Länge. + +### Maskierte Werte protokollieren (optional) +Falls Sie Audit‑Logs benötigen, übergeben Sie ein Flag über `custom_settings` und passen die Funktion an: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Anschließend registrieren Sie mit: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Vollständiges funktionierendes Beispiel (zum Kopieren und Einfügen bereit) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Führt man dieses Skript auf einem Beleg aus, der `4111111111111111` enthält, entsteht: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +Damit ist die gesamte Pipeline – vom rohen OCR‑Ergebnis bis zur **Daten‑Sanitisierung** – in wenigen klaren Python‑Zeilen umgesetzt. + +--- + +## Fazit + +Wir haben Ihnen gezeigt, wie Sie **Kreditkartennummern** in OCR‑Ergebnissen mithilfe des Post‑Processing‑Hooks von AsposeAI, einer kompakten Regular‑Expression‑Routine und einigen Best‑Practice‑Hinweisen zur **PCI‑Compliance** maskieren können. Die Lösung ist komplett eigenständig, funktioniert mit jedem Bild, das die OCR‑Engine lesen kann, und lässt sich leicht erweitern, um komplexere Kartenformate oder Protokollierungsanforderungen abzudecken. + +Bereit für den nächsten Schritt? Kombinieren Sie diese Maske mit einer **Datenbank‑Einfüge‑Routine**, die nur die letzten vier Ziffern zur Referenz speichert, oder integrieren Sie einen **Batch‑Processor**, der über Nacht einen ganzen Ordner mit Belegen scannt. Sie können zudem weitere **OCR‑Post‑Processing**‑Aufgaben erkunden, etwa Adressstandardisierung oder Spracherkennung – jedes folgt dem gleichen Muster, das wir hier verwendet haben. + +Haben Sie Fragen zu Randfällen, Performance oder zur Anpassung des Codes für eine andere OCR‑Bibliothek? Hinterlassen Sie einen Kommentar unten, und wir setzen das Gespräch fort. Viel Spaß beim Coden und bleiben Sie sicher! + + + +![Diagram illustrating how mask credit card numbers works in an OCR pipeline](https://example.com/images/ocr-mask-flow.png "Diagram of OCR post‑processing masking flow") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/german/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..8633f3d1a --- /dev/null +++ b/ocr/german/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-04-26 +description: Lernen Sie, wie Sie die Inferenzzeit in Python messen, ein GGUF‑Modell + von Hugging Face laden und die GPU‑Nutzung für schnellere Ergebnisse optimieren. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: de +og_description: Messen Sie die Inferenzzeit in Python, indem Sie ein GGUF‑Modell von + Hugging Face laden und die GPU‑Schichten für optimale Leistung abstimmen. +og_title: Messung der Inferenzzeit – GGUF‑Modell laden & GPU optimieren +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Messung der Inferenzzeit – GGUF-Modell laden & GPU optimieren +url: /de/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Inference‑Zeit messen – GGUF‑Modell laden & GPU optimieren + +Haben Sie jemals **Inference‑Zeit messen** müssen für ein großes Sprachmodell, wussten aber nicht, wo Sie anfangen sollen? Sie sind nicht allein – viele Entwickler stoßen auf das gleiche Problem, wenn sie zum ersten Mal eine GGUF‑Datei von Hugging Face holen und versuchen, sie in einer gemischten CPU/GPU‑Umgebung auszuführen. + +In diesem Leitfaden zeigen wir Ihnen **wie man ein GGUF‑Modell lädt**, es für Hugging Face konfiguriert und **Inference‑Zeit misst** mit einem sauberen Python‑Snippet. Außerdem zeigen wir Ihnen, wie Sie **Inference‑GPU optimieren**, damit Ihre Durchläufe so schnell wie möglich sind. Keine Umschweife, nur eine praktische End‑to‑End‑Lösung, die Sie noch heute copy‑pasten können. + +## Was Sie lernen werden + +- Wie man ein **HuggingFace‑Modell konfiguriert** mit `AsposeAIModelConfig`. +- Die genauen Schritte, um ein **GGUF‑Modell zu laden** (`fp16`‑Quantisierung) vom Hugging Face Hub. +- Ein wiederverwendbares Muster für **timing Python code** rund um einen Inferenzaufruf. +- Tipps, um **Inference‑GPU zu optimieren**, indem `gpu_layers` angepasst wird. +- Erwartete Ausgabe und wie Sie überprüfen, ob Ihre Messungen sinnvoll sind. + +### Voraussetzungen + +| Anforderung | Warum es wichtig ist | +|-------------|----------------------| +| Python 3.9+ | Moderne Syntax und Typ‑Hints. | +| `asposeai` package (or the equivalent SDK) | Stellt `AsposeAI` und `AsposeAIModelConfig` bereit. | +| Access to the Hugging Face repo `bartowski/Qwen2.5-3B-Instruct-GGUF` | Das GGUF‑Modell, das wir laden werden. | +| A GPU with at least 8 GB VRAM (optional but recommended) | Ermöglicht den **optimize inference GPU**‑Schritt. | + +Wenn Sie das SDK noch nicht installiert haben, führen Sie aus: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![Diagramm zur Messung der Inferenzzeit](https://example.com/measure-inference-time.png){alt="Diagramm zur Messung der Inferenzzeit"} + +## Schritt 1: GGUF‑Modell laden – HuggingFace‑Modell konfigurieren + +Das Erste, was Sie benötigen, ist ein korrektes Konfigurationsobjekt, das Aspose AI mitteilt, wo das Modell abgerufen werden soll und wie es behandelt wird. Hier laden wir ein **GGUF‑Modell** und **konfigurieren huggingface‑Modell**‑Parameter. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Warum das wichtig ist:** +- `hugging_face_repo_id` verweist auf die genaue GGUF‑Datei im Hub. +- `fp16` reduziert den Speicher‑Durchsatz, während die meisten Modell‑Fidelität erhalten bleibt. +- `gpu_layers` ist der Regler, den Sie anpassen, wenn Sie **Inference‑GPU optimieren** möchten; mehr Schichten auf der GPU bedeuten in der Regel geringere Latenz, vorausgesetzt, Sie haben genug VRAM. + +## Schritt 2: Aspose AI‑Instanz erstellen + +Jetzt, wo das Modell beschrieben ist, erzeugen wir ein `AsposeAI`‑Objekt. Dieser Schritt ist unkompliziert, aber hier lädt das SDK tatsächlich die GGUF‑Datei (falls sie nicht im Cache ist) und bereitet die Laufzeit vor. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Pro‑Tipp:** Der erste Durchlauf dauert ein paar Sekunden länger, weil das Modell heruntergeladen und für die GPU kompiliert wird. Nachfolgende Durchläufe sind blitzschnell. + +## Schritt 3: Inferenz ausführen und **Inference‑Zeit messen** + +Hier ist das Herzstück des Tutorials: Den Inferenzaufruf mit `time.time()` umhüllen, um **Inference‑Zeit zu messen**. Wir geben außerdem ein winziges OCR‑Ergebnis ein, damit das Beispiel eigenständig bleibt. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Was Sie sehen sollten:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Wenn die Zahl hoch erscheint, laufen wahrscheinlich die meisten Schichten auf der CPU. Das führt uns zum nächsten Schritt. + +## Schritt 4: **Inference‑GPU optimieren** – `gpu_layers` anpassen + +Manchmal ist das Standard‑`gpu_layers=40` entweder zu aggressiv (verursacht OOM) oder zu konservativ (lässt Leistung ungenutzt). Hier ein kurzer Loop, mit dem Sie den optimalen Punkt finden können: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Warum das funktioniert:** +- Jeder Aufruf baut die Laufzeit mit einer anderen GPU‑Zuweisung neu auf, sodass Sie den Latenz‑Trade‑off sofort sehen. +- Der Loop demonstriert zudem **time python code** auf wiederverwendbare Weise, die Sie für andere Performance‑Tests anpassen können. + +Typische Ausgabe auf einer 16 GB RTX 3080 könnte etwa so aussehen: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +Daraus würden Sie `gpu_layers=40` als optimalen Wert für diese Hardware auswählen. + +## Vollständiges funktionierendes Beispiel + +Alles zusammengeführt, hier ein einzelnes Skript, das Sie in eine Datei (`measure_inference.py`) legen und ausführen können: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Ausführen mit: + +```bash +python measure_inference.py +``` + +Sie sollten eine Sub‑Sekunden‑Latenz auf einer ordentlichen GPU sehen, was bestätigt, dass Sie erfolgreich **measure inference time** und **optimize inference GPU** durchgeführt haben. + +--- + +## Häufig gestellte Fragen (FAQs) + +**Q: Funktioniert das mit anderen Quantisierungsformaten?** +A: Absolut. Tauschen Sie `hugging_face_quantization="int8"` (oder `q4_0` usw.) in der Konfiguration aus und führen Sie den Benchmark erneut aus. Erwarten Sie einen Kompromiss: geringerer Speicherverbrauch vs. ein leichter Genauigkeitsverlust. + +**Q: Was, wenn ich keine GPU habe?** +A: Setzen Sie `gpu_layers=0`. Der Code fällt vollständig auf die CPU zurück, und Sie können weiterhin **Inference‑Zeit messen** – erwarten Sie jedoch höhere Werte. + +**Q: Kann ich nur den Forward‑Pass des Modells timen, ohne Nachbearbeitung?** +A: Ja. Rufen Sie `ai_engine.run_model(...)` (oder die entsprechende Methode) direkt auf und umhüllen Sie diesen Aufruf mit `time.time()`. Das Muster für **time python code** bleibt gleich. + +--- + +## Fazit + +Sie haben nun eine komplette Copy‑and‑Paste‑Lösung, um **Inference‑Zeit zu messen** für ein GGUF‑Modell, **gguf‑Modell zu laden** von Hugging Face und **Inference‑GPU zu optimieren**. Durch Anpassen von `gpu_layers` und Experimentieren mit Quantisierung können Sie jede Millisekunde Leistung herausholen. + +Als Nächstes könnten Sie: + +- Diese Timing‑Logik in eine CI‑Pipeline integrieren, um Regressionen zu erkennen. +- Batch‑Inference untersuchen, um den Durchsatz weiter zu steigern. +- Das Modell mit einer echten OCR‑Pipeline kombinieren statt des hier verwendeten Dummy‑Texts. + +Viel Spaß beim Coden, und mögen Ihre Latenz‑Zahlen stets niedrig bleiben! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/german/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..7a0188791 --- /dev/null +++ b/ocr/german/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-26 +description: Erkennen Sie handgeschriebenen Text mit Pythons OCR‑Engine. Erfahren + Sie, wie Sie Text aus einem Bild extrahieren, den handschriftlichen Modus aktivieren + und handschriftliche Notizen schnell lesen. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: de +og_description: Erkennen Sie handgeschriebenen Text mit Python. Dieses Tutorial zeigt, + wie man Text aus einem Bild extrahiert, den handgeschriebenen Modus aktiviert und + handgeschriebene Notizen mit einer einfachen OCR‑Engine liest. +og_title: Handschriftlichen Text in Python erkennen – Vollständiger OCR-Leitfaden +tags: +- OCR +- Python +- Handwriting Recognition +title: Handgeschriebenen Text in Python erkennen – OCR‑Engine‑Tutorial +url: /de/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# handgeschriebenen Text in Python erkennen – OCR‑Engine‑Tutorial + +Hast du jemals **handgeschriebenen Text** erkennen wollen, wusstest aber nicht, wo du anfangen sollst? Du bist nicht allein. Ob du Meeting‑Notizen digitalisieren oder Daten aus einem gescannten Formular extrahieren willst, ein zuverlässiges OCR‑Ergebnis zu erhalten kann sich anfühlen, als würdest du nach einem Einhorn jagen. + +Gute Neuigkeiten: Mit nur wenigen Zeilen Python kannst du **Text aus Bild**‑Dateien **extrahieren**, den **Handschrift‑Modus aktivieren** und endlich **handgeschriebene Notizen lesen**, ohne obscure Bibliotheken zu suchen. In diesem Leitfaden gehen wir den gesamten Prozess durch – vom **create OCR engine python**‑Setup bis zum Ausgeben des Ergebnisses auf dem Bildschirm. + +## Was du lernen wirst + +- Wie du eine **create OCR engine python**‑Instanz mit dem `ocr`‑Paket erstellst. +- Welche Spracheinstellung dir integrierte Handschrift‑Unterstützung bietet. +- Der genaue Aufruf, um **turn on handwritten mode** zu aktivieren, damit die Engine weiß, dass du Kursive hast. +- Wie du ein Bild einer Notiz übergibst und **handgeschriebenen Text erkennen** lässt. +- Tipps zum Umgang mit verschiedenen Bildformaten, Fehlersuche bei gängigen Stolperfallen und Erweiterungen der Lösung. + +Kein Schnickschnack, keine “siehe Docs”‑Dead‑Ends – nur ein vollständiges, ausführbares Skript, das du heute kopieren‑und‑einsetzen kannst. + +## Voraussetzungen + +Bevor wir starten, stelle sicher, dass du Folgendes hast: + +1. Python 3.8+ installiert (der Code verwendet f‑Strings). +2. Die hypothetische `ocr`‑Bibliothek (`pip install ocr‑engine` – ersetze sie durch den tatsächlichen Paketnamen, den du nutzt). +3. Eine klare Bilddatei einer handgeschriebenen Notiz (JPEG, PNG oder TIFF funktionieren). +4. Ein bisschen Neugier – alles andere wird unten erklärt. + +> **Pro Tipp:** Wenn dein Bild rauscht, führe einen kurzen Vorverarbeitungsschritt mit Pillow aus (z. B. `Image.open(...).convert('L')`), bevor du es an die OCR‑Engine sendest. Das erhöht oft die Genauigkeit. + +## Wie man handgeschriebenen Text mit Python erkennt + +Unten steht das komplette Skript, das **create OCR engine python**‑Objekte erstellt, sie für Handschrift konfiguriert und den extrahierten String ausgibt. Speichere es als `handwriting_ocr.py` und führe es im Terminal aus. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Erwartete Ausgabe + +Wenn das Skript erfolgreich läuft, siehst du etwa Folgendes: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Kann die OCR‑Engine keine Zeichen erkennen, ist das Feld `text` ein leerer String. Prüfe in diesem Fall die Bildqualität oder versuche einen Scan mit höherer Auflösung. + +## Schritt‑für‑Schritt‑Erklärung + +### Schritt 1 – **create OCR engine python**‑Instanz + +Die Klasse `OcrEngine` ist der Einstiegspunkt. Stell dir das vor wie ein leeres Notizbuch – nichts passiert, bis du ihr sagst, welche Sprache zu erwarten ist und ob du Handschrift hast. + +### Schritt 2 – Wähle eine Sprache, die Handschrift unterstützt + +`ocr.Language.EXTENDED_LATIN` ist nicht nur “Englisch”. Es bündelt eine Reihe von lateinbasierten Schriften und enthält zudem Modelle, die auf Kursive trainiert wurden. Das Überspringen dieses Schritts führt häufig zu wirren Ausgaben, weil die Engine standardmäßig ein Drucktext‑Modell verwendet. + +### Schritt 3 – **turn on handwritten mode** + +Der Aufruf `enable_handwritten_mode(True)` setzt ein internes Flag. Die Engine schaltet dann zu ihrem neuronalen Netz, das für unregelmäßige Abstände und variable Strichbreiten in echten Notizen optimiert ist. Diese Zeile zu vergessen ist ein häufiger Fehler; die Engine behandelt deine Kritzeleien sonst als Rauschen. + +### Schritt 4 – Bild übergeben und **handgeschriebenen Text erkennen** + +`recognize_image` erledigt die schwere Arbeit: Es preprocesses das Bitmap, führt es durch das Handschrift‑Modell und liefert ein Objekt mit dem Attribut `text` zurück. Du kannst außerdem `handwritten_result.confidence` prüfen, wenn du eine Qualitätsmetrik brauchst. + +### Schritt 5 – Ergebnis ausgeben und **handgeschriebene Notizen lesen** + +`print(handwritten_result.text)` ist der einfachste Weg zu überprüfen, dass du erfolgreich **extract text from image** hast. In der Produktion würdest du den String wahrscheinlich in einer Datenbank speichern oder an einen anderen Service weitergeben. + +## Umgang mit Randfällen & gängigen Variationen + +| Situation | Was zu tun ist | +|-----------|----------------| +| **Bild ist gedreht** | Verwende Pillow, um es zu rotieren (`Image.rotate(angle)`) bevor du `recognize_image` aufrufst. | +| **Geringer Kontrast** | In Graustufen konvertieren und adaptives Thresholding anwenden (`Image.point(lambda p: p > 128 and 255)`). | +| **Mehrere Seiten** | Über eine Liste von Dateipfaden iterieren und die Ergebnisse zusammenfügen. | +| **Nicht‑lateinische Schriften** | `EXTENDED_LATIN` durch `ocr.Language.CHINESE` (oder passend) ersetzen und `enable_handwritten_mode(True)` beibehalten. | +| **Performance‑Bedenken** | dieselbe `ocr_engine`‑Instanz für viele Bilder wiederverwenden; jedes Mal neu zu initialisieren kostet Overhead. | + +### Pro Tipp zum Speicherverbrauch + +Wenn du Hunderte von Notizen stapelweise verarbeitest, rufe `ocr_engine.dispose()` auf, sobald du fertig bist. Das gibt native Ressourcen frei, die der Python‑Wrapper möglicherweise hält. + +## Kurze visuelle Zusammenfassung + +![recognize handwritten text example](https://example.com/handwritten-note.png "recognize handwritten text example") + +*Das obige Bild zeigt eine typische handgeschriebene Notiz, die unser Skript in Klartext umwandeln kann.* + +## Vollständiges funktionierendes Beispiel (Ein‑Datei‑Skript) + +Für alle, die Copy‑Paste‑Einfachheit lieben, hier das gesamte Skript noch einmal ohne erklärende Kommentare: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Ausführen mit: + +```bash +python handwriting_ocr.py +``` + +Du solltest jetzt die **recognize handwritten text**‑Ausgabe in deiner Konsole sehen. + +## Fazit + +Wir haben alles behandelt, was du brauchst, um **handgeschriebenen Text** in Python zu **recognize handwritten text** – beginnend mit einem frischen **create OCR engine python**‑Aufruf, der richtigen Sprache, **turn on handwritten mode** und schließlich **extract text from image**, um **handwritten notes** zu **read handwritten notes**. + +In einem einzigen, eigenständigen Skript kannst du von einem verschwommenen Foto einer Meeting‑Skizze zu sauberem, durchsuchbarem Text gelangen. Als nächstes könntest du die Ausgabe in eine Natural‑Language‑Pipeline einspeisen, in einem durchsuchbaren Index speichern oder zurück in einen Transkriptions‑Service für Voice‑Over‑Generierung geben. + +### Wie geht es weiter? + +- **Batch‑Verarbeitung:** Das Skript in eine Schleife einbetten, um einen Ordner mit Scans zu bearbeiten. +- **Confidence‑Filterung:** `result.confidence` nutzen, um niedrig‑qualitative Lesungen zu verwerfen. +- **Alternative Bibliotheken:** Wenn `ocr` nicht perfekt passt, `pytesseract` mit `--psm 13` für den Handschrift‑Modus ausprobieren. +- **UI‑Integration:** Mit Flask oder FastAPI kombinieren, um einen webbasierten Upload‑Service anzubieten. + +Hast du Fragen zu einem bestimmten Bildformat oder brauchst Hilfe beim Tuning des Modells? Hinterlasse einen Kommentar unten, und happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/greek/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..96cd2b971 --- /dev/null +++ b/ocr/greek/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-04-26 +description: Μάθετε πώς να κατεβάσετε το μοντέλο HuggingFace σε Python και να εξάγετε + κείμενο από εικόνα σε Python, βελτιώνοντας ταυτόχρονα την ακρίβεια OCR σε Python + με το Aspose OCR Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: el +og_description: Κατεβάστε το μοντέλο HuggingFace για Python και ενισχύστε τη διαδικασία + OCR σας. Ακολουθήστε αυτόν τον οδηγό για να εξάγετε κείμενο από εικόνα με Python + και να βελτιώσετε την ακρίβεια του OCR με Python. +og_title: Λήψη μοντέλου HuggingFace Python – Πλήρης Οδηγός Βελτίωσης OCR +tags: +- OCR +- HuggingFace +- Python +- AI +title: Λήψη μοντέλου HuggingFace σε Python – Οδηγός βήμα‑βήμα για ενίσχυση OCR +url: /el/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – Πλήρης Οδηγός Βελτίωσης OCR + +Προσπαθήσατε ποτέ να **download HuggingFace model python** και νιώσατε λίγο χαμένοι; Δεν είστε οι μόνοι. Σε πολλά έργα το μεγαλύτερο εμπόδιο είναι η λήψη ενός καλού μοντέλου στον υπολογιστή σας και στη συνέχεια η μετατροπή των αποτελεσμάτων OCR σε κάτι πραγματικά χρήσιμο. + +Σε αυτόν τον οδηγό θα περάσουμε από ένα πρακτικό παράδειγμα που σας δείχνει ακριβώς πώς να **download HuggingFace model python**, να εξάγετε κείμενο από μια εικόνα με **extract text from image python**, και στη συνέχεια να **improve OCR accuracy python** χρησιμοποιώντας τον AI post‑processor της Aspose. Στο τέλος θα έχετε ένα έτοιμο‑για‑εκτέλεση script που μετατρέπει μια θορυβώδη εικόνα τιμολογίου σε καθαρό, αναγνώσιμο κείμενο—χωρίς μαγεία, μόνο σαφή βήματα. + +## Τι Θα Χρειαστείτε + +- Python 3.9+ (ο κώδικας λειτουργεί επίσης σε 3.11) +- Σύνδεση στο διαδίκτυο για τη μία λήψη του μοντέλου +- Το πακέτο `asposeocrcloud` (`pip install asposeocrcloud`) +- Μια δείγμα εικόνας (π.χ., `sample_invoice.png`) τοποθετημένη σε φάκελο που ελέγχετε + +Αυτό είναι όλο—χωρίς βαριά frameworks, χωρίς οδηγούς ειδικά για GPU εκτός αν θέλετε να επιταχύνετε τη διαδικασία. + +Τώρα, ας βουτήξουμε στην πραγματική υλοποίηση. + +![ροή εργασίας download huggingface model python](image.png "διαγράφημα download huggingface model python") + +## Βήμα 1: Ρύθμιση της Μηχανής OCR και Επιλογή Γλώσσας +*(Εδώ ξεκινάμε να **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Γιατί αυτό είναι σημαντικό:** +Η μηχανή OCR είναι η πρώτη γραμμή άμυνας· η επιλογή του σωστού πακέτου γλώσσας μειώνει άμεσα τα σφάλματα αναγνώρισης χαρακτήρων, κάτι που αποτελεί βασικό μέρος του **improve OCR accuracy python**. + +## Βήμα 2: Διαμόρφωση του Μοντέλου AsposeAI – Λήψη από HuggingFace +*(Εδώ πραγματικά **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**Τι συμβαίνει στο παρασκήνιο;** +Όταν το `allow_auto_download` είναι true, το SDK επικοινωνεί με το HuggingFace, κατεβάζει το μοντέλο `Qwen2.5‑3B‑Instruct‑GGUF` και το αποθηκεύει στον φάκελο που καθορίσατε. Αυτό είναι ο πυρήνας του **download huggingface model python**—το SDK αναλαμβάνει το βαρύ έργο, ώστε να μην χρειαστεί να γράψετε εντολές `git clone` ή `wget` μόνοι σας. + +*Συμβουλή:* Κρατήστε το `directory_model_path` σε SSD για ταχύτερους χρόνους φόρτωσης· το μοντέλο είναι ~3 GB ακόμη και σε μορφή `int8`. + +## Βήμα 3: Σύνδεση της Μηχανής AI με τη Μηχανή OCR +*(Συνδέουμε τα δύο κομμάτια ώστε να μπορούμε να **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Γιατί να τα συνδέσουμε;** +Η μηχανή OCR μας δίνει ακατέργαστο κείμενο, το οποίο μπορεί να περιέχει ορθογραφικά λάθη, σπασμένες γραμμές ή λανθασμένη στίξη. Η μηχανή AI λειτουργεί ως έξυπνος επεξεργαστής, καθαρίζοντας αυτά τα προβλήματα—ακριβώς ό,τι χρειάζεστε για **improve OCR accuracy python**. + +## Βήμα 4: Εκτέλεση OCR στην Εικόνα Σας +*(Η στιγμή που τελικά **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +Το `ocr_result` τώρα περιέχει ένα χαρακτηριστικό `text` με τους ακατέργαστους χαρακτήρες που είδε η μηχανή. Στην πράξη θα παρατηρήσετε μερικά σπασίματα—ίσως το “Invoice” να μετατράπηκε σε “Inv0ice” ή να υπάρχει αλλαγή γραμμής στη μέση μιας πρότασης. + +## Βήμα 5: Καθαρισμός με τον AI Post‑Processor +*(Αυτό το βήμα βελτιώνει άμεσα το **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +Το μοντέλο AI ξαναγράφει το κείμενο, εφαρμόζοντας διορθώσεις που γνωρίζουν τη γλώσσα. Επειδή χρησιμοποιούμε ένα instruction‑tuned μοντέλο από το HuggingFace, η έξοδος είναι συνήθως ρέουσα και έτοιμη για επεξεργασία downstream. + +## Βήμα 6: Εμφάνιση Πριν και Μετά +*(Γρήγορος έλεγχος για να δούμε πόσο καλά **extract text from image python** και **improve OCR accuracy python**.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Αναμενόμενο Αποτέλεσμα + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Παρατηρήστε πώς η AI διόρθωσε το “Inv0ice” σε “Invoice” και εξομάλυνσε τυχόν ανεπιθύμητες αλλαγές γραμμής. Αυτό είναι το απτό αποτέλεσμα του **improve OCR accuracy python** χρησιμοποιώντας ένα ληφθέν μοντέλο HuggingFace. + +## Συχνές Ερωτήσεις (FAQ) + +### Χρειάζομαι GPU για να τρέξω το μοντέλο; +Όχι. Η ρύθμιση `gpu_layers=20` λέει στο SDK να χρησιμοποιήσει έως και 20 GPU layers αν υπάρχει συμβατό GPU· διαφορετικά επιστρέφει στην CPU. Σε ένα σύγχρονο laptop η διαδρομή CPU επεξεργάζεται ακόμα μερικές εκατοντάδες tokens ανά δευτερόλεπτο—ιδανικό για περιστασιακή ανάλυση τιμολογίων. + +### Τι γίνεται αν το μοντέλο αποτύχει να κατέβει; +Βεβαιωθείτε ότι το περιβάλλον σας μπορεί να φτάσει στο `https://huggingface.co`. Αν βρίσκεστε πίσω από εταιρικό proxy, ορίστε τις μεταβλητές περιβάλλοντος `HTTP_PROXY` και `HTTPS_PROXY`. Το SDK θα προσπαθήσει ξανά αυτόματα, αλλά μπορείτε επίσης να κάνετε χειροκίνητο `git lfs pull` το repo στο `directory_model_path`. + +### Μπορώ να αντικαταστήσω το μοντέλο με ένα μικρότερο; +Απολύτως. Απλώς αντικαταστήστε το `hugging_face_repo_id` με άλλο repo (π.χ., `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) και προσαρμόστε το `hugging_face_quantization` αναλόγως. Τα μικρότερα μοντέλα κατεβαίνουν πιο γρήγορα και καταναλώνουν λιγότερη RAM, αν και μπορεί να χάσετε λίγο στην ποιότητα διόρθωσης. + +### Πώς με βοηθά αυτό να **extract text from image python** σε άλλους τομείς; +Η ίδια ροή λειτουργεί για αποδείξεις, διαβατήρια ή χειρόγραφα σημειώματα. Η μόνη αλλαγή είναι το πακέτο γλώσσας (`ocr.Language.FRENCH`, κ.λπ.) και πιθανώς ένα domain‑specific fine‑tuned μοντέλο από το HuggingFace. + +## Μπόνους: Αυτοματοποίηση Πολλαπλών Αρχείων + +Αν έχετε έναν φάκελο γεμάτο εικόνες, τυλίξτε την κλήση OCR σε έναν απλό βρόχο: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +Αυτή η μικρή προσθήκη σας επιτρέπει να **download huggingface model python** μία φορά, και στη συνέχεια να επεξεργαστείτε κατά παρτίδες δεκάδες αρχεία—ιδανικό για κλιμάκωση της γραμμής αυτοματοποίησης εγγράφων. + +## Συμπέρασμα + +Μόλις περάσαμε από ένα πλήρες, end‑to‑end παράδειγμα που δείχνει πώς να **download HuggingFace model python**, **extract text from image python**, και **improve OCR accuracy python** χρησιμοποιώντας το Aspose OCR Cloud και έναν AI post‑processor. Το script είναι έτοιμο για εκτέλεση, οι έννοιες εξηγήθηκαν, και είδατε το αποτέλεσμα πριν‑και‑μετά ώστε να ξέρετε ότι λειτουργεί. + +Τι ακολουθεί; Δοκιμάστε να αντικαταστήσετε το μοντέλο HuggingFace με κάποιο άλλο, πειραματιστείτε με άλλα πακέτα γλώσσας, ή τροφοδοτήστε το καθαρισμένο κείμενο σε μια downstream NLP pipeline (π.χ., εξαγωγή οντοτήτων για στοιχεία τιμολογίου). Ο ουρανός είναι το όριο, και το θεμέλιο που μόλις χτίσατε είναι σταθερό. + +Έχετε ερωτήσεις ή μια δύσκολη εικόνα που ακόμα μπλοκάρει το OCR; Αφήστε ένα σχόλιο παρακάτω και ας το αντιμετωπίσουμε μαζί. Καλή κωδικοποίηση! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/greek/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..015b94d3a --- /dev/null +++ b/ocr/greek/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-04-26 +description: Κατεβάστε το μοντέλο OCR γρήγορα χρησιμοποιώντας το Aspose OCR Python. + Μάθετε πώς να ορίσετε τον φάκελο μοντέλου, να διαμορφώσετε τη διαδρομή του μοντέλου + και πώς να κατεβάσετε το μοντέλο σε λίγες γραμμές. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: el +og_description: Κατεβάστε το μοντέλο OCR σε δευτερόλεπτα με το Aspose OCR Python. + Αυτός ο οδηγός δείχνει πώς να ορίσετε τον φάκελο μοντέλου, να διαμορφώσετε τη διαδρομή + του μοντέλου και πώς να κατεβάσετε το μοντέλο με ασφάλεια. +og_title: Λήψη μοντέλου OCR – Πλήρης οδηγός Aspose OCR Python +tags: +- OCR +- Python +- Aspose +title: Κατεβάστε το μοντέλο OCR με Aspose OCR Python – Οδηγός βήμα‑βήμα +url: /el/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – Πλήρες Μάθημα Aspose OCR Python + +Έχετε αναρωτηθεί ποτέ πώς να **download ocr model** χρησιμοποιώντας το Aspose OCR σε Python χωρίς να ψάχνετε σε ατέλειωτες τεκμηριώσεις; Δεν είστε οι μόνοι. Πολλοί προγραμματιστές συναντούν πρόβλημα όταν το μοντέλο δεν υπάρχει τοπικά και το SDK ρίχνει ένα ασαφές σφάλμα. Τα καλά νέα; Η λύση είναι μερικές γραμμές κώδικα, και θα έχετε το μοντέλο έτοιμο σε λίγα λεπτά. + +Σε αυτό το μάθημα θα περάσουμε από όλα όσα χρειάζεται να γνωρίζετε: από την εισαγωγή των σωστών κλάσεων, μέχρι το **set model directory**, μέχρι πραγματικά το **how to download model**, και τέλος την επαλήθευση της διαδρομής. Στο τέλος θα μπορείτε να εκτελείτε OCR σε οποιαδήποτε εικόνα με μία μόνο κλήση συνάρτησης, και θα κατανοήσετε τις επιλογές **configure model path** που διατηρούν το έργο σας τακτοποιημένο. Χωρίς περιττές πληροφορίες, μόνο ένα πρακτικό, εκτελέσιμο παράδειγμα για χρήστες **aspose ocr python**. + +## Τι Θα Μάθετε + +- Πώς να εισάγετε σωστά τις κλάσεις Aspose OCR Cloud. +- Τα ακριβή βήματα για **download ocr model** αυτόματα. +- Τρόποι για **set model directory** και **configure model path** για αναπαραγώγιμες εκδόσεις. +- Πώς να επαληθεύσετε ότι το μοντέλο έχει αρχικοποιηθεί και πού βρίσκεται στο δίσκο. +- Κοινά προβλήματα (δικαιώματα, ελλιπείς φάκελοι) και γρήγορες λύσεις. + +### Προαπαιτούμενα + +- Python 3.8+ εγκατεστημένο στο σύστημά σας. +- Πακέτο `asposeocrcloud` (`pip install asposeocrcloud`). +- Δικαίωμα εγγραφής σε φάκελο όπου θέλετε να αποθηκεύσετε το μοντέλο (π.χ., `C:\models` ή `~/ocr_models`). + +--- + +## Βήμα 1: Εισαγωγή Κλάσεων Aspose OCR Cloud + +Το πρώτο που χρειάζεστε είναι η σωστή δήλωση εισαγωγής. Αυτό φέρνει τις κλάσεις που διαχειρίζονται τη ρύθμιση του μοντέλου και τις λειτουργίες OCR. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Γιατί είναι σημαντικό:* `AsposeAI` είναι η μηχανή που θα εκτελεί OCR, ενώ `AsposeAIModelConfig` λέει στη μηχανή **where** να ψάξει για το μοντέλο και **whether** πρέπει να το κατεβάσει αυτόματα. Η παράλειψη αυτού του βήματος ή η εισαγωγή του λανθασμένου module θα προκαλέσει `ModuleNotFoundError` πριν φτάσετε στο τμήμα λήψης. + +--- + +## Βήμα 2: Ορισμός Ρυθμίσεων Μοντέλου (Set Model Directory & Configure Model Path) + +Τώρα λέμε στο Aspose πού να αποθηκεύει τα αρχεία του μοντέλου. Εδώ είναι που κάνετε **set model directory** και **configure model path**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Συμβουλές & Προειδοποιήσεις** + +- **Absolute paths** αποφεύγουν τη σύγχυση όταν το script εκτελείται από διαφορετικό φάκελο εργασίας. +- Σε Linux/macOS μπορείτε να χρησιμοποιήσετε `"/home/you/ocr_models"`; στα Windows, προσθέστε πρόθεμα `r` για να αντιμετωπιστούν οι ανάστροφοι κάθετοι ως κυριολεκτικοί. +- Ο ορισμός `allow_auto_download="true"` είναι το κλειδί για **how to download model** χωρίς επιπλέον κώδικα. + +--- + +## Βήμα 3: Δημιουργία Αντικειμένου AsposeAI Χρησιμοποιώντας τη Ρύθμιση + +Με τη ρύθμιση έτοιμη, δημιουργήστε την μηχανή OCR. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Γιατί είναι σημαντικό:* Το αντικείμενο `ocr_ai` τώρα περιέχει τη ρύθμιση που μόλις ορίσαμε. Αν το μοντέλο δεν υπάρχει, η επόμενη κλήση θα ενεργοποιήσει αυτόματα τη λήψη — αυτό είναι το βασικό στοιχείο του **how to download model** με αυτόματο τρόπο. + +--- + +## Βήμα 4: Ενεργοποίηση Λήψης Μοντέλου (Αν Απαιτείται) + +Πριν μπορέσετε να εκτελέσετε OCR, πρέπει να βεβαιωθείτε ότι το μοντέλο υπάρχει πραγματικά στο δίσκο. Η μέθοδος `is_initialized()` ελέγχει και ενεργοποιεί την αρχικοποίηση. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**Τι συμβαίνει στο παρασκήνιο;** + +- Η πρώτη κλήση `is_initialized()` επιστρέφει `False` επειδή ο φάκελος του μοντέλου είναι κενός. +- Το `print` ενημερώνει τον χρήστη ότι η λήψη πρόκειται να ξεκινήσει. +- Η δεύτερη κλήση αναγκάζει το Aspose να κατεβάσει το μοντέλο από το αποθετήριο Hugging Face που καθορίσατε νωρίτερα. +- Μόλις ληφθεί, η μέθοδος επιστρέφει `True` στις επόμενες κλήσεις. + +**Edge case:** Αν το δίκτυό σας μπλοκάρει το Hugging Face, θα δείτε μια εξαίρεση. Σε αυτήν την περίπτωση, κατεβάστε χειροκίνητα το zip του μοντέλου, εξάγετε το στο `directory_model_path` και ξανατρέξτε το script. + +--- + +## Βήμα 5: Αναφορά Τοπικής Διαδρομής όπου το Μοντέλο είναι Τώρα Διαθέσιμο + +Μετά το τέλος της λήψης, πιθανότατα θέλετε να ξέρετε πού αποθηκεύτηκαν τα αρχεία. Αυτό βοηθά στον εντοπισμό σφαλμάτων και στη ρύθμιση pipelines CI. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Η τυπική έξοδος μοιάζει με: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Τώρα έχετε επιτυχώς **download ocr model**, ορίσει τον φάκελο και επιβεβαιώσει τη διαδρομή. + +--- + +## Οπτική Επισκόπηση + +Παρακάτω υπάρχει ένα απλό διάγραμμα που δείχνει τη ροή από τη ρύθμιση μέχρι ένα έτοιμο προς χρήση μοντέλο. + +![download ocr model flow diagram showing configuration, automatic download, and local path](/images/download-ocr-model-flow.png) + +*Το κείμενο alt περιλαμβάνει τη βασική λέξη-κλειδί για SEO.* + +--- + +## Συνηθισμένες Παραλλαγές & Πώς να τις Διαχειριστείτε + +### 1. Χρήση Διαφορετικού Αποθετηρίου Μοντέλου + +Αν χρειάζεστε μοντέλο διαφορετικό από `openai/gpt2`, απλώς αντικαταστήστε την τιμή `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Βεβαιωθείτε ότι το αποθετήριο είναι δημόσιο ή ότι έχετε ορίσει το απαραίτητο token στο περιβάλλον σας. + +### 2. Απενεργοποίηση Αυτόματης Λήψης + +Μερικές φορές θέλετε να ελέγχετε τη λήψη μόνοι σας (π.χ., σε περιβάλλοντα χωρίς σύνδεση). Ορίστε το `allow_auto_download` σε `"false"` και καλέστε ένα προσαρμοσμένο script λήψης πριν την αρχικοποίηση: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Αλλαγή του Φακέλου Μοντέλου κατά το Runtime + +Μπορείτε να επαναρυθμίσετε τη διαδρομή χωρίς να δημιουργήσετε ξανά το αντικείμενο `AsposeAI`: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Επαγγελματικές Συμβουλές για Χρήση σε Παραγωγή + +- **Cache the model**: Κρατήστε το φάκελο σε κοινόχρηστο δίκτυο αν πολλές υπηρεσίες χρειάζονται το ίδιο μοντέλο. Αυτό αποτρέπει περιττές λήψεις. +- **Version pinning**: Το αποθετήριο Hugging Face μπορεί να ενημερωθεί. Για να κλειδώσετε σε συγκεκριμένη έκδοση, προσθέστε `@v1.0.0` στο repo ID (`"openai/gpt2@v1.0.0"`). +- **Permissions**: Βεβαιωθείτε ότι ο χρήστης που εκτελεί το script έχει δικαιώματα ανάγνωσης/εγγραφής στο `directory_model_path`. Σε Linux, το `chmod 755` συνήθως αρκεί. +- **Logging**: Αντικαταστήστε τις απλές δηλώσεις `print` με το module `logging` της Python για καλύτερη παρακολούθηση σε μεγαλύτερες εφαρμογές. + +--- + +## Πλήρες Παράδειγμα Εργασίας (Έτοιμο για Αντιγραφή‑Επικόλληση) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Αναμενόμενη έξοδος** (η πρώτη εκτέλεση θα κατεβάσει, οι επόμενες θα παραλείψουν τη λήψη): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Τρέξτε ξανά το script· θα δείτε μόνο τη γραμμή με τη διαδρομή επειδή το μοντέλο είναι ήδη στην cache. + +--- + +## Συμπέρασμα + +Μόλις καλύψαμε τη πλήρη διαδικασία για **download ocr model** χρησιμοποιώντας Aspose OCR Python, δείξαμε πώς να **set model directory**, και εξηγήσαμε τις λεπτομέρειες του **configure model path**. Με λίγες μόνο γραμμές κώδικα μπορείτε να αυτοματοποιήσετε τη λήψη, να αποφύγετε χειροκίνητα βήματα και να διατηρήσετε το pipeline OCR αναπαραγώγιμο. + +Στη συνέχεια, ίσως θέλετε να εξερευνήσετε την πραγματική κλήση OCR (`ocr_ai.recognize_image(...)`) ή να πειραματιστείτε με διαφορετικό μοντέλο Hugging Face για βελτιωμένη ακρίβεια. Σε κάθε περίπτωση, η βάση που δημιουργήσατε εδώ — σαφής ρύθμιση, αυτόματη λήψη και επαλήθευση διαδρομής — θα κάνει οποιαδήποτε μελλοντική ενσωμάτωση εύκολη. + +Έχετε ερωτήσεις για ειδικές περιπτώσεις, ή θέλετε να μοιραστείτε πώς προσαρμόσατε το φάκελο μοντέλου για αναπτύξεις στο cloud; Αφήστε ένα σχόλιο παρακάτω, και καλή προγραμματιστική! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/greek/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..c128443ee --- /dev/null +++ b/ocr/greek/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-04-26 +description: Πώς να μετα-επεξεργαστείτε τα αποτελέσματα OCR και να εξάγετε κείμενο + με συντεταγμένες. Μάθετε μια λύση βήμα‑βήμα χρησιμοποιώντας δομημένη έξοδο και διόρθωση + AI. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: el +og_description: Πώς να επεξεργαστείτε τα αποτελέσματα OCR και να εξάγετε κείμενο με + συντεταγμένες. Ακολουθήστε αυτό το ολοκληρωμένο σεμινάριο για μια αξιόπιστη ροή + εργασίας. +og_title: Πώς να επεξεργαστείτε μετά το OCR – Πλήρης οδηγός +tags: +- OCR +- Python +- AI +- Text Extraction +title: Πώς να επεξεργαστείτε το OCR μετά την εκτέλεση – Εξαγωγή κειμένου με συντεταγμένες + σε Python +url: /el/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να επεξεργαστείτε μετά το OCR – Εξαγωγή κειμένου με συντεταγμένες σε Python + +Έχετε χρειαστεί ποτέ να **how to post‑process OCR** τα αποτελέσματα επειδή η ακατέργαστη έξοδος ήταν θορυβώδης ή μη ευθυγραμμισμένη; Δεν είστε μόνοι. Σε πολλά πραγματικά έργα—σάρωση τιμολογίων, ψηφιοποίηση αποδείξεων ή ακόμη και ενίσχυση εμπειριών AR—η μηχανή OCR σας δίνει ακατέργαστες λέξεις, αλλά πρέπει ακόμη να τις καθαρίσετε και να παρακολουθείτε πού βρίσκεται κάθε λέξη στη σελίδα. Εκεί που ξεχωρίζει μια λειτουργία δομημένης εξόδου σε συνδυασμό με έναν AI‑οδηγούμενο μετα‑επεξεργαστή. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από ένα πλήρες, εκτελέσιμο pipeline σε Python που **extracts text with coordinates** από μια εικόνα, εκτελεί ένα βήμα διόρθωσης με AI και εκτυπώνει κάθε λέξη μαζί με τη θέση της (x, y). Χωρίς ελλιπείς εισαγωγές, χωρίς ασαφείς «δείτε την τεκμηρίωση» συντομεύσεις—απλώς μια αυτόνομη λύση που μπορείτε να ενσωματώσετε στο πρότζεκτ σας σήμερα. + +> **Συμβουλή:** Αν χρησιμοποιείτε διαφορετική βιβλιοθήκη OCR, ψάξτε για λειτουργία «structured» ή «layout»· οι έννοιες παραμένουν ίδιες. + +--- + +## Προαπαιτήσεις + +Πριν προχωρήσουμε, βεβαιωθείτε ότι έχετε: + +| Απαίτηση | Γιατί είναι σημαντικό | +|----------|------------------------| +| Python 3.9+ | Σύγχρονη σύνταξη και υποδείξεις τύπων | +| `ocr` library that supports `OutputMode.STRUCTURED` (e.g., a fictional `myocr`) | Απαιτείται για δεδομένα πλαισίων περιγράμματος | +| An AI post‑processing module (could be OpenAI, HuggingFace, or a custom model) | Βελτιώνει την ακρίβεια μετά το OCR | +| An image file (`input.png`) in your working directory | Η πηγή που θα διαβάσουμε | + +Αν κάποια από αυτά σας είναι άγνωστη, απλώς εγκαταστήστε τα placeholder πακέτα με `pip install myocr ai‑postproc`. Ο κώδικας παρακάτω περιλαμβάνει επίσης fallback stubs ώστε να μπορείτε να δοκιμάσετε τη ροή χωρίς τις πραγματικές βιβλιοθήκες. + +--- + +## Βήμα 1: Ενεργοποίηση λειτουργίας δομημένης εξόδου για τη μηχανή OCR + +Το πρώτο που κάνουμε είναι να πούμε στη μηχανή OCR να μας δώσει περισσότερα από απλό κείμενο. Η δομημένη έξοδος επιστρέφει κάθε λέξη μαζί με το πλαίσιο περιγράμματος και το σκορ εμπιστοσύνης, κάτι που είναι απαραίτητο για **extract text with coordinates** αργότερα. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Γιατί είναι σημαντικό:* Χωρίς τη δομημένη λειτουργία θα λάβετε μόνο μια μακριά συμβολοσειρά και θα χάσετε τις χωρικές πληροφορίες που χρειάζεστε για επικάλυψη κειμένου πάνω σε εικόνες ή για downstream ανάλυση διάταξης. + +--- + +## Βήμα 2: Αναγνώριση της εικόνας και σύλληψη λέξεων, πλαισίων και εμπιστοσύνης + +Τώρα τροφοδοτούμε την εικόνα στη μηχανή. Το αποτέλεσμα είναι ένα αντικείμενο που περιέχει μια λίστα από αντικείμενα λέξεων, το καθένα εκθέτει `text`, `x`, `y`, `width`, `height` και `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Περίπτωση:* Αν η εικόνα είναι κενή ή μη αναγνώσιμη, το `structured_result.words` θα είναι μια κενή λίστα. Είναι καλή πρακτική να ελέγχετε για αυτό και να το διαχειρίζεστε με χάρη. + +--- + +## Βήμα 3: Εκτέλεση AI‑βασισμένης μετα‑επεξεργασίας διατηρώντας τις θέσεις + +Ακόμη και οι καλύτερες μηχανές OCR κάνουν λάθη—π.χ. “O” vs. “0” ή λείπουν διακριτικά. Ένα μοντέλο AI εκπαιδευμένο σε κείμενο συγκεκριμένου τομέα μπορεί να διορθώσει αυτά τα σφάλματα. Σημαντικό είναι ότι διατηρούμε τις αρχικές συντεταγμένες ώστε η χωρική διάταξη να παραμένει αμετάβλητη. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Γιατί διατηρούμε τις συντεταγμένες:* Πολλές downstream εργασίες (π.χ. δημιουργία PDF, ετικετοθέτηση AR) εξαρτώνται από ακριβή τοποθέτηση. Το AI επηρεάζει μόνο το πεδίο `text`, αφήνοντας αμετάβλητα τα `x`, `y`, `width`, `height`. + +--- + +## Βήμα 4: Επανάληψη πάνω στις διορθωμένες λέξεις και εμφάνιση του κειμένου τους με συντεταγμένες + +Τέλος, κάνουμε βρόχο στις διορθωμένες λέξεις και εκτυπώνουμε κάθε λέξη μαζί με την πάνω‑αριστερή γωνία της `(x, y)`. Αυτό ικανοποιεί τον στόχο **extract text with coordinates**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Αναμενόμενη έξοδος (παράδειγμα):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Κάθε γραμμή δείχνει τη διορθωμένη λέξη και την ακριβή της θέση στην αρχική εικόνα. + +--- + +## Πλήρες λειτουργικό παράδειγμα + +Παρακάτω υπάρχει ένα ενιαίο script που ενώνει όλα τα παραπάνω. Μπορείτε να το αντιγράψετε‑επικολλήσετε, να προσαρμόσετε τις δηλώσεις εισαγωγής ώστε να ταιριάζουν με τις πραγματικές βιβλιοθήκες σας και να το τρέξετε άμεσα. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Εκτέλεση του script** + +```bash +python ocr_postprocess_demo.py +``` + +Αν έχετε εγκαταστήσει τις πραγματικές βιβλιοθήκες, το script θα επεξεργαστεί το `input.png`. Διαφορετικά, η υλοποίηση stub σας επιτρέπει να δείτε τη ροή και την έξοδο χωρίς εξωτερικές εξαρτήσεις. + +--- + +## Συχνές Ερωτήσεις (FAQ) + +| Ερώτηση | Απάντηση | +|----------|----------| +| *Does this work with Tesseract?* | Το Tesseract από μόνο του δεν εκθέτει λειτουργία δομημένης εξόδου, αλλά wrappers όπως `pytesseract.image_to_data` επιστρέφουν πλαίσια περιγράμματος που μπορείτε να τροφοδοτήσετε στον ίδιο AI μετα‑επεξεργαστή. | +| *What if I need the bottom‑right corner instead of top‑left?* | Κάθε αντικείμενο λέξης παρέχει επίσης `width` και `height`. Υπολογίστε `x2 = x + width` και `y2 = y + height` για να πάρετε την αντίθετη γωνία. | +| *Can I batch‑process multiple images?* | Απόλυτα. Τυλίξτε τα βήματα σε έναν βρόχο `for image_path in Path("folder").glob("*.png"):` και συλλέξτε τα αποτελέσματα ανά αρχείο. | +| *How do I choose an AI model for correction?* | Για γενικό κείμενο, ένα μικρό GPT‑2 που έχει fine‑tuned σε σφάλματα OCR λειτουργεί. Για δεδομένα ειδικού τομέα (π.χ. ιατρικές συνταγές), εκπαιδεύστε ένα μοντέλο sequence‑to‑sequence σε ζευγάρια «θορυβώδη‑καθαρά» δεδομένα. | +| *Is the confidence score useful after AI correction?* | Μπορείτε ακόμη να διατηρήσετε την αρχική εμπιστοσύνη για debugging, αλλά το AI μπορεί να εκδώσει τη δική του εμπιστοσύνη αν το μοντέλο το υποστηρίζει. | + +--- + +## Περιπτώσεις Άκρων & Καλές Πρακτικές + +1. **Empty or corrupted images** – πάντα επαληθεύετε ότι το `structured_result.words` δεν είναι κενό πριν προχωρήσετε. +2. **Non‑Latin scripts** – βεβαιωθείτε ότι η μηχανή OCR είναι ρυθμισμένη για τη γλώσσα-στόχο· ο AI μετα‑επεξεργαστής πρέπει να είναι εκπαιδευμένος στο ίδιο σύστημα γραφής. +3. **Performance** – η διόρθωση με AI μπορεί να είναι δαπανηρή. Κρυπτογραφήστε (cache) τα αποτελέσματα αν θα ξαναχρησιμοποιήσετε την ίδια εικόνα ή εκτελέστε το βήμα AI ασύγχρονα. +4. **Coordinate system** – βιβλιοθήκες OCR μπορεί να χρησιμοποιούν διαφορετικές αρχές (πάνω‑αριστερά vs. κάτω‑αριστερά). Προσαρμόστε ανάλογα όταν επικάθετε σε PDF ή καμβά. + +--- + +## Συμπέρασμα + +Τώρα έχετε μια στιβαρή, end‑to‑end συνταγή για **how to post‑process OCR** και αξιόπιστη **extract text with coordinates**. Ενεργοποιώντας τη δομημένη έξοδο, τροφοδοτώντας το αποτέλεσμα σε ένα επίπεδο διόρθωσης AI και διατηρώντας τα αρχικά πλαίσια περιγράμματος, μπορείτε να μετατρέψετε θορυβώδεις σκαναρίσματα OCR σε καθαρό, χωρικά‑συνειδητοποιημένο κείμενο έτοιμο για downstream εργασίες όπως δημιουργία PDF, αυτοματοποίηση εισαγωγής δεδομένων ή επαυξημένες πραγματικότητες. + +Έτοιμοι για το επόμενο βήμα; Δοκιμάστε να αντικαταστήσετε το stub AI με μια κλήση OpenAI `gpt‑4o‑mini`, ή ενσωματώστε το pipeline σε ένα FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/greek/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..2abab07a7 --- /dev/null +++ b/ocr/greek/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-04-26 +description: Πώς να αναγνωρίζετε εικόνες γρήγορα με την Python. Μάθετε μια αλυσίδα + αναγνώρισης εικόνων, επεξεργασία παρτίδων και αυτοματοποιήστε την αναγνώριση εικόνων + χρησιμοποιώντας AI. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: el +og_description: Πώς να αναγνωρίζετε εικόνες γρήγορα με την Python. Αυτός ο οδηγός + περιγράφει μια αλυσίδα αναγνώρισης εικόνων, τη δέσμευση (batching) και τον αυτοματισμό + με χρήση AI. +og_title: Πώς να Αναγνωρίζετε Εικόνες – Αυτοματοποιήστε μια Διαδικασία Αναγνώρισης + Εικόνων +tags: +- image-processing +- python +- ai +title: Πώς να Αναγνωρίζετε Εικόνες – Αυτοματοποιήστε μια Διαδικασία Αναγνώρισης Εικόνων +url: /el/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να Αναγνωρίζετε Εικόνες – Αυτοματοποιήστε μια Διαδικασία Αναγνώρισης Εικόνας + +Έχετε αναρωτηθεί ποτέ **πώς να αναγνωρίζετε εικόνες** χωρίς να γράψετε χιλιάδες γραμμές κώδικα; Δεν είστε μόνοι—πολλοί προγραμματιστές αντιμετωπίζουν το ίδιο εμπόδιο όταν χρειάζεται για πρώτη φορά να επεξεργαστούν δεκάδες ή εκατοντάδες φωτογραφίες. Τα καλά νέα; Με μερικά απλά βήματα μπορείτε να δημιουργήσετε μια πλήρη διαδικασία αναγνώρισης εικόνας που ομαδοποιεί, εκτελεί και καθαρίζει όλα αυτόματα. + +Σε αυτό το tutorial θα περάσουμε από ένα πλήρες, εκτελέσιμο παράδειγμα που δείχνει **πώς να ομαδοποιείτε εικόνες**, να τις τροφοδοτείτε σε μια μηχανή AI, να επεξεργάζεστε τα αποτελέσματα και, τέλος, να απελευθερώνετε πόρους. Στο τέλος θα έχετε ένα αυτόνομο script που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο, είτε χτίζετε έναν ετικετοποιητή φωτογραφιών, ένα σύστημα ελέγχου ποιότητας ή έναν γεννήτορα συνόλων δεδομένων για έρευνα. + +## Τι Θα Μάθετε + +- **Πώς να αναγνωρίζετε εικόνες** χρησιμοποιώντας μια ψεύτικη μηχανή AI (το μοτίβο είναι ίδιο για πραγματικές υπηρεσίες όπως TensorFlow, PyTorch ή cloud APIs). +- Πώς να δημιουργήσετε μια **διαδικασία αναγνώρισης εικόνας** που διαχειρίζεται ομάδες αποδοτικά. +- Ο καλύτερος τρόπος για **να αυτοματοποιήσετε την αναγνώριση εικόνων** ώστε να μην χρειάζεται να κάνετε χειροκίνητους βρόχους πάνω σε αρχεία κάθε φορά. +- Συμβουλές για κλιμάκωση της διαδικασίας και ασφαλή απελευθέρωση πόρων. + +> **Προαπαιτούμενα:** Python 3.8+, βασική εξοικείωση με συναρτήσεις και βρόχους, και μερικά αρχεία εικόνας (ή διαδρομές) που θέλετε να επεξεργαστείτε. Δεν απαιτούνται εξωτερικές βιβλιοθήκες για το κύριο παράδειγμα, αλλά θα αναφέρουμε πού μπορείτε να ενσωματώσετε πραγματικά SDK AI. + +![Διάγραμμα του πώς να αναγνωρίζετε εικόνες σε μια διαδικασία επεξεργασίας ομάδων](pipeline.png "Διάγραμμα πώς να αναγνωρίζετε εικόνες") + +## Βήμα 1: Ομαδοποιήστε τις Εικόνες Σας – Πώς να Ομαδοποιείτε Εικόνες Αποδοτικά + +Πριν η AI κάνει οποιαδήποτε βαριά δουλειά, χρειάζεστε μια συλλογή εικόνων για να τη τροφοδοτήσετε. Σκεφτείτε το ως τη λίστα αγορών σας· η μηχανή θα πάρει κάθε στοιχείο από τη λίστα ένα-ένα. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Γιατί ομαδοποίηση;** +Η ομαδοποίηση μειώνει την ποσότητα του επαναλαμβανόμενου κώδικα που γράφετε και καθιστά εύκολο το προσθήκη παραλληλισμού αργότερα. Αν χρειαστεί ποτέ να επεξεργαστείτε 10 000 εικόνες, θα αλλάξετε μόνο την πηγή του `image_batch`—το υπόλοιπο της διαδικασίας παραμένει αμετάβλητο. + +## Βήμα 2: Εκτελέστε τη Διαδικασία Αναγνώρισης Εικόνας (Αναγνώριση Εικόνων με AI) + +Τώρα ενώνουμε την ομάδα με τον πραγματικό αναγνωριστή. Σε ένα πραγματικό σενάριο μπορεί να καλέσετε `torchvision.models` ή ένα cloud endpoint· εδώ προσομοιώνουμε τη συμπεριφορά ώστε το tutorial να παραμείνει αυτόνομο. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Επεξήγηση:** +- `engine.recognize_image` είναι η καρδιά της **διαδικασίας αναγνώρισης εικόνας**· μπορεί να είναι κλήση σε μοντέλο deep‑learning ή σε REST API. +- `postprocessor.run` δείχνει **πώς να αυτοματοποιήσετε την αναγνώριση εικόνων** κανονικοποιώντας τις ακατέργαστες προβλέψεις σε ένα καθαρό λεξικό που μπορείτε να αποθηκεύσετε ή να μεταδώσετε. +- Συλλέγουμε κάθε λεξικό `corrected` στο `recognized_results` ώστε τα επόμενα βήματα (π.χ. εισαγωγή σε βάση δεδομένων) να είναι απλά. + +## Βήμα 3: Μετα-επεξεργασία και Αποθήκευση – Αυτοματοποιήστε τα Αποτελέσματα Αναγνώρισης Εικόνας + +Αφού έχετε μια τακτοποιημένη λίστα προβλέψεων, συνήθως θέλετε να τις αποθηκεύσετε. Το παρακάτω παράδειγμα γράφει ένα αρχείο CSV· μπορείτε να το αντικαταστήσετε με βάση δεδομένων ή ουρά μηνυμάτων. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Γιατί CSV;** +Το CSV είναι καθολικά αναγνώσιμο—Excel, pandas, ακόμη και απλοί επεξεργαστές κειμένου μπορούν να το ανοίξουν. Αν αργότερα χρειαστεί να **αυτοματοποιήσετε την αναγνώριση εικόνων** σε κλίμακα, αντικαταστήστε το τμήμα εγγραφής με μια μαζική εισαγωγή στο data lake σας. + +## Βήμα 4: Καθαρισμός – Αποδέσμευση Πόρων AI με Ασφάλεια + +Πολλά SDK AI δεσμεύουν μνήμη GPU ή δημιουργούν νήματα εργασίας. Η παράλειψη της απελευθέρωσής τους μπορεί να οδηγήσει σε διαρροές μνήμης και σφαλματα. Παρόλο που τα ψεύτικα αντικείμενά μας δεν το χρειάζονται, θα δείξουμε το σωστό μοτίβο. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +Η εκτέλεση του script εκτυπώνει μια φιλική επιβεβαίωση, ενημερώνοντάς σας ότι η διαδικασία ολοκληρώθηκε καθαρά. + +## Πλήρες Εργαζόμενο Script + +Συνδυάζοντας τα πάντα, εδώ είναι το πλήρες, έτοιμο για αντιγραφή πρόγραμμα: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Αναμενόμενη Εξαγωγή + +Όταν τρέξετε το script (υπό την προϋπόθεση ότι υπάρχουν οι τρεις υποκαταστάτες διαδρομές), θα δείτε κάτι όπως: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +Και το παραγόμενο `recognition_results.csv` θα περιέχει: + +| image | label | confidence | +|---------------------|-------|------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Συμπέρασμα + +Τώρα έχετε ένα στέρεο, ολοκληρωμένο παράδειγμα **πώς να αναγνωρίζετε εικόνες** σε Python, με πλήρη **διαδικασία αναγνώρισης εικόνας**, διαχείριση ομάδων και αυτοματοποιημένη μετα‑επεξεργασία. Το μοτίβο κλιμακώνεται: αντικαταστήστε τις ψεύτικες κλάσεις με ένα πραγματικό μοντέλο, τροφοδοτήστε το με μεγαλύτερο `image_batch`, και έχετε μια λύση έτοιμη για παραγωγή. + +Θέλετε να προχωρήσετε περαιτέρω; Δοκιμάστε τα επόμενα βήματα: + +- Αντικαταστήστε το `MockEngine` με μοντέλο TensorFlow ή PyTorch για πραγματικές προβλέψεις. +- Παράλληλο τρέξιμο του βρόχου με `concurrent.futures.ThreadPoolExecutor` για επιτάχυνση μεγάλων ομάδων. +- Συνδέστε τον CSV writer με ένα cloud storage bucket για **να αυτοματοποιήσετε την αναγνώριση εικόνων** σε κατανεμημένους εργαζόμενους. + +Πειραματιστείτε, σπάστε πράγματα και μετά διορθώστε τα—αυτή είναι η πραγματική μάθηση των pipelines αναγνώρισης εικόνας. Αν αντιμετωπίσετε δυσκολίες ή έχετε ιδέες για βελτιώσεις, αφήστε ένα σχόλιο παρακάτω. Καλή προγραμματιστική! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/greek/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..6e1708a92 --- /dev/null +++ b/ocr/greek/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-04-26 +description: Καλύψτε γρήγορα τους αριθμούς πιστωτικών καρτών χρησιμοποιώντας την επεξεργασία + μετά‑από‑OCR του AsposeAI. Μάθετε για τη συμμόρφωση PCI, τη μάσκα με κανονικές εκφράσεις + και τον καθαρισμό δεδομένων σε έναν βήμα‑βήμα οδηγό. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: el +og_description: Απόκρυψη αριθμών πιστωτικών καρτών στα αποτελέσματα OCR με το AsposeAI. + Αυτό το σεμινάριο καλύπτει τη συμμόρφωση με το PCI, την απόκρυψη με κανονικές εκφράσεις + και την απολύμανση δεδομένων. +og_title: Απόκρυψη αριθμών πιστωτικών καρτών – Πλήρης οδηγός επεξεργασίας μετά την + OCR με Python +tags: +- OCR +- Python +- security +title: Απόκρυψη αριθμών πιστωτικών καρτών στην έξοδο OCR – Πλήρης οδηγός Python +url: /el/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Απόκρυψη Αριθμών Πιστωτικών Καρτών – Πλήρης Οδηγός Python + +Έχετε ποτέ χρειαστεί να **αποκρύψετε αριθμούς πιστωτικών καρτών** σε κείμενο που προέρχεται απευθείας από μια μηχανή OCR; Δεν είστε μόνοι. Σε ρυθμιζόμενους κλάδους, η αποκάλυψη ενός πλήρους PAN (Primary Account Number) μπορεί να σας βάλει σε πρόβλημα με τους ελεγκτές συμμόρφωσης PCI. Τα καλά νέα; Με λίγες γραμμές Python και το hook post‑processing του AsposeAI, μπορείτε αυτόματα να κρύψετε τα μεσαία οκτώ ψηφία και να παραμείνετε ασφαλείς. + +Σε αυτό το tutorial θα περάσουμε από ένα πραγματικό σενάριο: εκτέλεση OCR σε εικόνα απόδειξης, έπειτα εφαρμογή μιας προσαρμοσμένης λειτουργίας **OCR post‑processing** που εξαλείφει τυχόν δεδομένα PCI. Στο τέλος θα έχετε ένα επαναχρησιμοποιήσιμο snippet που μπορείτε να ενσωματώσετε σε οποιαδήποτε ροή εργασίας AsposeAI, καθώς και μια σειρά πρακτικών συμβουλών για τη διαχείριση edge cases και την κλιμάκωση της λύσης. + +## Τι Θα Μάθετε + +- Πώς να καταχωρίσετε έναν προσαρμοσμένο post‑processor με **AsposeAI**. +- Γιατί η προσέγγιση **regular expression masking** είναι γρήγορη και αξιόπιστη. +- Τα βασικά της **PCI compliance** που σχετίζονται με την εξάλειψη δεδομένων. +- Τρόποι επέκτασης του μοτίβου για πολλαπλές μορφές καρτών ή διεθνείς αριθμούς. +- Αναμενόμενο αποτέλεσμα και πώς να επαληθεύσετε ότι η απόκρυψη λειτούργησε. + +> **Prerequisites** – Θα πρέπει να έχετε ένα λειτουργικό περιβάλλον Python 3, το πακέτο Aspose.AI for OCR εγκατεστημένο (`pip install aspose-ocr`), και ένα δείγμα εικόνας (π.χ., `receipt.png`) που περιέχει αριθμό πιστωτικής κάρτας. Δεν απαιτούνται άλλες εξωτερικές υπηρεσίες. + +--- + +## Step 1: Define a Post‑Processor that Masks Credit Card Numbers + +Η καρδιά της λύσης βρίσκεται σε μια μικρή συνάρτηση που λαμβάνει το αποτέλεσμα του OCR, εκτελεί μια ρουτίνα **regular expression masking**, και επιστρέφει το εξαγορευμένο κείμενο. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Why this works:** +- Η κανονική έκφραση `(\d{4})\d{8}(\d{4})` ταιριάζει ακριβώς με 16 διαδοχικά ψηφία, τη συνήθη μορφή για Visa, MasterCard και πολλές άλλες. +- Καταγράφοντας τα πρώτα και τα τελευταία τέσσερα ψηφία (`\1` και `\2`) διατηρούμε αρκετές πληροφορίες για debugging, ενώ συμμορφωνόμαστε με τους κανόνες **PCI compliance** που απαγορεύουν την αποθήκευση του πλήρους PAN. +- Η αντικατάσταση `\1****\2` κρύβει τα ευαίσθητα μεσαία οκτώ ψηφία, μετατρέποντας το `1234567812345678` σε `1234****5678`. + +> **Pro tip:** Αν χρειάζεται να υποστηρίξετε 15‑ψηφιακούς αριθμούς American Express, προσθέστε ένα δεύτερο μοτίβο όπως `r'(\d{4})\d{6}(\d{5})'` και εκτελέστε και τις δύο αντικαταστάσεις διαδοχικά. + +--- + +## Step 2: Initialise the AsposeAI Engine + +Πριν μπορέσουμε να συνδέσουμε τον post‑processor, χρειαζόμαστε μια παρουσία του OCR engine. Το AsposeAI περιλαμβάνει το μοντέλο OCR και ένα απλό API για προσαρμοσμένη επεξεργασία. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Why initialise here?** +Δημιουργώντας το αντικείμενο `AsposeAI` μία φορά και επαναχρησιμοποιώντας το για πολλές εικόνες μειώνουμε το κόστος. Η μηχανή επίσης αποθηκεύει στην κρυφή μνήμη (cache) τα μοντέλα γλώσσας, κάτι που επιταχύνει τις επόμενες κλήσεις — χρήσιμο όταν σαρώνετε δέσμες αποδείξεων. + +--- + +## Step 3: Register the Custom Masking Function + +Το AsposeAI εκθέτει τη μέθοδο `set_post_processor` που σας επιτρέπει να συνδέσετε οποιοδήποτε callable. Περνάμε τη συνάρτηση `mask_pci` μαζί με ένα προαιρετικό λεξικό ρυθμίσεων (αρχικά κενό). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**What’s happening behind the scenes?** +Όταν αργότερα καλέσετε `run_postprocessor`, το AsposeAI θα παραδώσει το ακατέργαστο αποτέλεσμα OCR στη `mask_pci`. Η συνάρτηση λαμβάνει ένα ελαφρύ αντικείμενο (`data`) που περιέχει το αναγνωρισμένο κείμενο, και επιστρέφετε μια νέα συμβολοσειρά. Αυτός ο σχεδιασμός διατηρεί το βασικό OCR αμετάβλητο, ενώ σας επιτρέπει να επιβάλετε πολιτικές **data sanitization** σε ένα μόνο σημείο. + +--- + +## Step 4: Run OCR on the Receipt Image + +Τώρα που η μηχανή ξέρει πώς να καθαρίζει το αποτέλεσμα, της παρέχουμε μια εικόνα. Για το σκοπό του tutorial υποθέτουμε ότι έχετε ήδη ένα αντικείμενο `engine` ρυθμισμένο με τη σωστή γλώσσα και ανάλυση. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Tip:** Αν δεν έχετε προ‑ρυθμισμένο αντικείμενο, μπορείτε να δημιουργήσετε ένα με: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +Η κλήση `recognize_image` επιστρέφει ένα αντικείμενο του οποίου η ιδιότητα `text` περιέχει τη ακατέργαστη, μη αποκρυπτογραφημένη συμβολοσειρά. + +--- + +## Step 5: Apply the Registered Post‑Processor + +Με τα ακατέργαστα δεδομένα OCR στα χέρια, τα παραδίδουμε στην παρουσία AI. Η μηχανή εκτελεί αυτόματα τη συνάρτηση `mask_pci` που καταχωρήσαμε νωρίτερα. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Why use `run_postprocessor` instead of calling the function manually?** +Κάνοντας έτσι διατηρείται η ροή εργασίας συνεπής, ειδικά όταν έχετε πολλαπλούς post‑processors (π.χ., spell‑checking, language detection). Το AsposeAI τα τοποθετεί στη σειρά που τα καταχωρίσατε, εξασφαλίζοντας ντετερμινιστικό αποτέλεσμα. + +--- + +## Step 6: Verify the Sanitized Output + +Τέλος, ας εκτυπώσουμε το εξαγορευμένο κείμενο και ας επιβεβαιώσουμε ότι τυχόν αριθμοί πιστωτικών καρτών έχουν αποκρυφτεί σωστά. + +```python +print(final_result.text) +``` + +**Expected output** (excerpt): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Αν η απόδειξη δεν περιείχε αριθμό κάρτας, το κείμενο παραμένει αμετάβλητο — τίποτα προς απόκρυψη, τίποτα για ανησυχία. + +--- + +## Handling Edge Cases and Common Variations + +### Multiple Card Numbers in One Document +Αν μια απόδειξη περιλαμβάνει περισσότερα από ένα PAN (π.χ., κάρτα πιστότητας συν αριθμό πληρωμής), η κανονική έκφραση εκτελείται παγκοσμίως, αποκρύπτοντας αυτόματα όλα τα ταιριάσματα. Δεν απαιτείται επιπλέον κώδικας. + +### Non‑Standard Formatting +Μερικές φορές το OCR εισάγει κενά ή παύλες (`1234 5678 1234 5678` ή `1234-5678-1234-5678`). Επεκτείνετε το μοτίβο ώστε να αγνοεί αυτούς τους χαρακτήρες: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +Η προσθήκη `[ -]?` επιτρέπει προαιρετικά κενά ή παύλες μεταξύ των ομάδων ψηφίων. + +### International Cards +Για PAN 19‑ψηφίων που χρησιμοποιούνται σε ορισμένες περιοχές, μπορείτε να διευρύνετε το μοτίβο: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Απλώς θυμηθείτε ότι η **PCI compliance** εξακολουθεί να απαιτεί την απόκρυψη των μεσαίων ψηφίων, ανεξάρτητα από το μήκος. + +### Logging Masked Values (Optional) +Αν χρειάζεστε ίχνη ελέγχου, περάστε μια σημαία μέσω `custom_settings` και προσαρμόστε τη συνάρτηση: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Στη συνέχεια καταχωρίστε με: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Full Working Example (Copy‑Paste Ready) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Εκτελώντας αυτό το script σε μια απόδειξη που περιέχει `4111111111111111` θα παραχθεί: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +Αυτή είναι η πλήρης αλυσίδα — από ακατέργαστο OCR μέχρι **data sanitization** — τυλιγμένη σε λίγες καθαρές γραμμές Python. + +--- + +## Conclusion + +Σας δείξαμε πώς να **αποκρύψετε αριθμούς πιστωτικών καρτών** σε αποτελέσματα OCR χρησιμοποιώντας το hook post‑processing του AsposeAI, μια σύντομη ρουτίνα regular‑expression, και μια σειρά βέλτιστων πρακτικών για **PCI compliance**. Η λύση είναι πλήρως αυτοσυντηρούμενη, λειτουργεί με οποιαδήποτε εικόνα μπορεί να διαβάσει η μηχανή OCR, και μπορεί να επεκταθεί για πιο σύνθετες μορφές καρτών ή απαιτήσεις καταγραφής. + +Έτοιμοι για το επόμενο βήμα; Δοκιμάστε να συνδυάσετε αυτήν την απόκρυψη με μια διαδικασία **database insertion** που αποθηκεύει μόνο τα τελευταία τέσσερα ψηφία για αναφορά, ή ενσωματώστε έναν **batch processor** που σαρώνει ολόκληρο φάκελο αποδείξεων κατά τη νύχτα. Μπορείτε επίσης να εξερευνήσετε άλλες εργασίες **OCR post‑processing** όπως τυποποίηση διευθύνσεων ή ανίχνευση γλώσσας — κάθε μία ακολουθεί το ίδιο μοτίβο που χρησιμοποιήσαμε εδώ. + +Έχετε ερωτήσεις σχετικά με edge cases, απόδοση ή πώς να προσαρμόσετε τον κώδικα για διαφορετική βιβλιοθήκη OCR; Αφήστε ένα σχόλιο παρακάτω και ας συνεχίσουμε τη συζήτηση. Καλό coding και παραμείνετε ασφαλείς! + +![Διάγραμμα που απεικονίζει πώς λειτουργεί η απόκρυψη αριθμών πιστωτικών καρτών σε μια διαδικασία OCR](https://example.com/images/ocr-mask-flow.png "Διάγραμμα της ροής απόκρυψης στην επεξεργασία μετά το OCR") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/greek/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..f3486a587 --- /dev/null +++ b/ocr/greek/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-04-26 +description: Μάθετε πώς να μετράτε το χρόνο εκτέλεσης σε Python, να φορτώνετε ένα + μοντέλο GGUF από το Hugging Face και να βελτιστοποιείτε τη χρήση του GPU για ταχύτερα + αποτελέσματα. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: el +og_description: Μετρήστε τον χρόνο εκτέλεσης σε Python φορτώνοντας ένα μοντέλο GGUF + από το Hugging Face και ρυθμίζοντας τα επίπεδα GPU για βέλτιστη απόδοση. +og_title: Μέτρηση Χρόνου Συμπερασμού – Φόρτωση Μοντέλου GGUF & Βελτιστοποίηση GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Μέτρηση Χρόνου Συμπερασμού – Φόρτωση Μοντέλου GGUF & Βελτιστοποίηση GPU +url: /el/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Μέτρηση Χρόνου Εκτέλεσης – Φόρτωση Μοντέλου GGUF & Βελτιστοποίηση GPU + +Κάποτε χρειάστηκε να **μετρήσετε τον χρόνο εκτέλεσης** για ένα μεγάλο μοντέλο γλώσσας αλλά δεν ήξερες από πού να ξεκινήσεις; Δεν είσαι μόνος—πολλοί προγραμματιστές αντιμετωπίζουν το ίδιο πρόβλημα όταν πρώτα κατεβάζουν ένα αρχείο GGUF από το Hugging Face και προσπαθούν να το τρέξουν σε ένα μεικτό περιβάλλον CPU/GPU. + +Σε αυτόν τον οδηγό θα δούμε **πώς να φορτώσουμε ένα μοντέλο GGUF**, να το ρυθμίσουμε για το Hugging Face, και **πώς να μετρήσουμε τον χρόνο εκτέλεσης** με ένα καθαρό απόσπασμα Python. Καθ' όλη τη διάρκεια, θα σας δείξουμε επίσης πώς να **βελτιστοποιήσετε τη χρήση GPU** ώστε οι εκτελέσεις σας να είναι όσο πιο γρήγορες γίνεται. Χωρίς περιττές πληροφορίες, μόνο μια πρακτική, ολοκληρωμένη λύση που μπορείτε να αντιγράψετε‑και‑επικολλήσετε σήμερα. + +## Τι Θα Μάθετε + +- Πώς να **ρυθμίσετε ένα μοντέλο HuggingFace** με `AsposeAIModelConfig`. +- Τα ακριβή βήματα για **φόρτωση μοντέλου GGUF** (`fp16` ποσοτικοποίηση) από το Hugging Face hub. +- Ένα επαναχρησιμοποιήσιμο μοτίβο για **χρονισμό κώδικα Python** γύρω από μια κλήση inference. +- Συμβουλές για **βελτιστοποίηση inference GPU** με την προσαρμογή του `gpu_layers`. +- Αναμενόμενο αποτέλεσμα και πώς να επαληθεύσετε ότι ο χρονισμός έχει νόημα. + +### Προαπαιτούμενα + +| Απαίτηση | Γιατί είναι σημαντικό | +|-------------|----------------| +| Python 3.9+ | Σύγχρονη σύνταξη και type hints. | +| `asposeai` package (ή το ισοδύναμο SDK) | Παρέχει `AsposeAI` και `AsposeAIModelConfig`. | +| Πρόσβαση στο αποθετήριο Hugging Face `bartowski/Qwen2.5-3B-Instruct-GGUF` | Το μοντέλο GGUF που θα φορτώσουμε. | +| GPU με τουλάχιστον 8 GB VRAM (προαιρετικό αλλά συνιστάται) | Ενεργοποιεί το βήμα **βελτιστοποίησης inference GPU**. | + +Αν δεν έχετε εγκαταστήσει ακόμη το SDK, τρέξτε: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![διάγραμμα μέτρησης χρόνου inference](https://example.com/measure-inference-time.png){alt="διάγραμμα μέτρησης χρόνου inference"} + +## Βήμα 1: Φόρτωση του Μοντέλου GGUF – Ρύθμιση Μοντέλου HuggingFace + +Το πρώτο που χρειάζεστε είναι ένα σωστό αντικείμενο ρύθμισης που λέει στην Aspose AI πού να πάρει το μοντέλο και πώς να το χειριστεί. Εδώ **φορτώνουμε ένα μοντέλο GGUF** και **ρυθμίζουμε τις παραμέτρους του huggingface model**. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Γιατί είναι σημαντικό:** +- `hugging_face_repo_id` δείχνει στο ακριβές αρχείο GGUF στο Hub. +- `fp16` μειώνει το εύρος ζώνης μνήμης διατηρώντας την πλειονότητα της πιστότητας του μοντέλου. +- `gpu_layers` είναι η ρύθμιση που τροποποιείτε όταν θέλετε να **βελτιστοποιήσετε το inference GPU**· περισσότερα layers στην GPU συνήθως σημαίνουν χαμηλότερη καθυστέρηση, εφόσον έχετε αρκετό VRAM. + +## Βήμα 2: Δημιουργία του Αντικειμένου Aspose AI + +Τώρα που το μοντέλο περιγράφηκε, δημιουργούμε ένα αντικείμενο `AsposeAI`. Αυτό το βήμα είναι απλό, αλλά είναι εκεί που το SDK κατεβάζει πραγματικά το αρχείο GGUF (αν δεν είναι στην cache) και προετοιμάζει το runtime. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Pro tip:** Η πρώτη εκτέλεση θα διαρκέσει λίγα δευτερόλεπτα παραπάνω επειδή το μοντέλο κατεβαίνει και συντίθεται για την GPU. Οι επόμενες εκτελέσεις είναι αστραπιαία. + +## Βήμα 3: Εκτέλεση Inference και **Μέτρηση Χρόνου Inference** + +Εδώ είναι η καρδιά του tutorial: τυλίγουμε την κλήση inference με `time.time()` για **μέτρηση χρόνου inference**. Επιπλέον, τροφοδοτούμε ένα μικρό αποτέλεσμα OCR μόνο για να κρατήσουμε το παράδειγμα αυτόνομα. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Τι πρέπει να δείτε:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Αν ο αριθμός φαίνεται υψηλός, πιθανότατα εκτελείτε τα περισσότερα layers στην CPU. Αυτό μας οδηγεί στο επόμενο βήμα. + +## Βήμα 4: **Βελτιστοποίηση Inference GPU** – Ρύθμιση `gpu_layers` + +Μερικές φορές το προεπιλεγμένο `gpu_layers=40` είναι είτε πολύ επιθετικό (προκαλεί OOM) είτε πολύ συντηρητικό (αφήνει απόδοση στην άκρη). Εδώ είναι ένας γρήγορος βρόχος που μπορείτε να χρησιμοποιήσετε για να βρείτε το ιδανικό σημείο: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Γιατί λειτουργεί:** +- Κάθε κλήση ξαναχτίζει το runtime με διαφορετική κατανομή GPU, επιτρέποντάς σας να δείτε αμέσως την ανταλλαγή latency. +- Ο βρόχος επίσης δείχνει **χρονισμό κώδικα Python** με επαναχρησιμοποιήσιμο τρόπο, που μπορείτε να προσαρμόσετε για άλλες δοκιμές απόδοσης. + +Τυπικό αποτέλεσμα σε μια RTX 3080 με 16 GB μπορεί να είναι: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +Από αυτό, θα επιλέξετε `gpu_layers=40` ως το βέλτιστο σημείο για αυτό το υλικό. + +## Πλήρες Παράδειγμα Εργασίας + +Συνδυάζοντας τα παραπάνω, εδώ είναι ένα ενιαίο script που μπορείτε να αποθηκεύσετε σε αρχείο (`measure_inference.py`) και να τρέξετε: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Τρέξτε το με: + +```bash +python measure_inference.py +``` + +Θα πρέπει να δείτε latency κάτω του δευτερολέπτου σε μια αξιοπρεπή GPU, επιβεβαιώνοντας ότι έχετε επιτυχώς **μετρήσει χρόνο inference** και **βελτιστοποιήσει το inference GPU**. + +--- + +## Συχνές Ερωτήσεις (FAQs) + +**Ε: Λειτουργεί αυτό με άλλες μορφές ποσοτικοποίησης;** +Α: Απόλυτα. Αλλάξτε `hugging_face_quantization="int8"` (ή `q4_0`, κλπ.) στη ρύθμιση και ξανατρέξτε το benchmark. Περιμένετε ανταλλαγή: χαμηλότερη χρήση μνήμης έναντι μικρής απώλειας ακρίβειας. + +**Ε: Τι γίνεται αν δεν έχω GPU;** +Α: Ορίστε `gpu_layers=0`. Ο κώδικας θα πέσει εξ ολοκλήρου στην CPU, και θα μπορείτε ακόμη να **μετρήσετε χρόνο inference**—απλώς περιμένετε υψηλότερους αριθμούς. + +**Ε: Μπορώ να χρονίσω μόνο το forward pass του μοντέλου, εξαιρώντας το post‑processing;** +Α: Ναι. Καλέστε απευθείας `ai_engine.run_model(...)` (ή την ισοδύναμη μέθοδο) και τυλίξτε αυτήν την κλήση με `time.time()`. Το μοτίβο για **χρονισμό κώδικα Python** παραμένει το ίδιο. + +--- + +## Συμπέρασμα + +Τώρα έχετε μια πλήρη, αντιγραφή‑και‑επικόλληση λύση για **μέτρηση χρόνου inference** ενός μοντέλου GGUF, **φόρτωση gguf μοντέλου** από το Hugging Face, και λεπτομερή **βελτιστοποίηση inference GPU**. Ρυθμίζοντας τα `gpu_layers` και πειραματιζόμενοι με ποσοτικοποίηση, μπορείτε να εξαγάγετε κάθε χιλιοστό του δευτερολέπτου απόδοσης. + +Επόμενα βήματα, ίσως: + +- Ενσωματώστε αυτή τη λογική χρονισμού σε pipeline CI για να εντοπίζετε regressions. +- Εξερευνήστε batch inference για περαιτέρω βελτίωση throughput. +- Συνδυάστε το μοντέλο με μια πραγματική ροή OCR αντί του ψεύτικου κειμένου που χρησιμοποιήσαμε εδώ. + +Καλή προγραμματιστική δουλειά, και εύχομαι οι αριθμοί latency σας να παραμένουν πάντα χαμηλοί! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/greek/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..d1b3a3411 --- /dev/null +++ b/ocr/greek/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-26 +description: Αναγνωρίστε χειρόγραφο κείμενο χρησιμοποιώντας τη μηχανή OCR της Python. + Μάθετε πώς να εξάγετε κείμενο από εικόνα, να ενεργοποιήσετε τη λειτουργία χειρογράφου + και να διαβάζετε γρήγορα χειρόγραφες σημειώσεις. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: el +og_description: Αναγνωρίστε χειρόγραφο κείμενο με την Python. Αυτός ο οδηγός δείχνει + πώς να εξάγετε κείμενο από εικόνα, να ενεργοποιήσετε τη λειτουργία χειρογράφου και + να διαβάσετε χειρόγραφες σημειώσεις χρησιμοποιώντας μια απλή μηχανή OCR. +og_title: Αναγνώριση χειρόγραφου κειμένου σε Python – Πλήρης Οδηγός OCR +tags: +- OCR +- Python +- Handwriting Recognition +title: Αναγνώριση χειρόγραφου κειμένου σε Python – Οδηγός Μηχανής OCR +url: /el/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Αναγνώριση χειρόγραφου κειμένου σε Python – Οδηγός Μηχανής OCR + +Έχετε ποτέ χρειαστεί να **αναγνωρίσετε χειρόγραφο κείμενο** αλλά νιώσατε κολλημένοι στο “πού ξεκινάω;”; Δεν είστε μόνοι. Είτε ψηφιοποιείτε σημειώσεις από συναντήσεις είτε εξάγετε δεδομένα από σαρωμένη φόρμα, η λήψη αξιόπιστου αποτελέσματος OCR μπορεί να μοιάζει με κυνήγι μονόκερου. + +Καλά νέα: με λίγες μόνο γραμμές Python μπορείτε να **εξάγετε κείμενο από εικόνα** αρχεία, **ενεργοποιήσετε τη λειτουργία χειρογράφου**, και τελικά **διαβάσετε χειρόγραφες σημειώσεις** χωρίς να ψάχνετε obscure βιβλιοθήκες. Σε αυτόν τον οδηγό θα περάσουμε από όλη τη διαδικασία, από τη ρύθμιση τύπου **create OCR engine python** μέχρι την εκτύπωση του αποτελέσματος στην οθόνη. + +## Τι Θα Μάθετε + +- Πώς να δημιουργήσετε ένα στιγμιότυπο **create OCR engine python** χρησιμοποιώντας το πακέτο `ocr`. +- Ποια ρύθμιση γλώσσας σας παρέχει ενσωματωμένη υποστήριξη χειρογράφου. +- Η ακριβής κλήση για **turn on handwritten mode** ώστε η μηχανή να γνωρίζει ότι αντιμετωπίζει πλάγιο κείμενο. +- Πώς να τροφοδοτήσετε μια εικόνα σημείωσης και να **recognize handwritten text** από αυτήν. +- Συμβουλές για διαχείριση διαφορετικών μορφών εικόνας, αντιμετώπιση κοινών προβλημάτων, και επέκταση της λύσης. + +Χωρίς περιττά, χωρίς “δείτε την τεκμηρίωση” αδιέξοδα—απλώς ένα πλήρες, εκτελέσιμο script που μπορείτε να αντιγράψετε‑επικολλήσετε και να δοκιμάσετε σήμερα. + +## Προαπαιτούμενα + +Πριν βουτήξουμε, βεβαιωθείτε ότι έχετε: + +1. Python 3.8+ εγκατεστημένο (ο κώδικας χρησιμοποιεί f‑strings). +2. Τη θεωρητική βιβλιοθήκη `ocr` (`pip install ocr‑engine` – αντικαταστήστε με το πραγματικό όνομα πακέτου που χρησιμοποιείτε). +3. Ένα καθαρό αρχείο εικόνας μιας χειρόγραφης σημείωσης (λειτουργούν JPEG, PNG ή TIFF). +4. Μια μέτρια δόση περιέργειας—τα υπόλοιπα καλύπτονται παρακάτω. + +> **Pro tip:** Αν η εικόνα σας είναι θορυβώδης, εκτελέστε ένα γρήγορο βήμα προεπεξεργασίας με το Pillow (π.χ., `Image.open(...).convert('L')`) πριν τη στείλετε στη μηχανή OCR. Συχνά βελτιώνει την ακρίβεια. + +## Πώς να αναγνωρίσετε χειρόγραφο κείμενο με Python + +Παρακάτω είναι το πλήρες script που **creates OCR engine python** αντικείμενα, τα ρυθμίζει για χειρόγραφο και εκτυπώνει το εξαγόμενο κείμενο. Αποθηκεύστε το ως `handwriting_ocr.py` και εκτελέστε το από το τερματικό σας. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Αναμενόμενο Αποτέλεσμα + +Όταν το script εκτελεστεί επιτυχώς, θα δείτε κάτι όπως: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Αν η μηχανή OCR δεν μπορεί να εντοπίσει χαρακτήρες, το πεδίο `text` θα είναι μια κενή συμβολοσειρά. Σε αυτήν την περίπτωση, ελέγξτε ξανά την ποιότητα της εικόνας ή δοκιμάστε σάρωση υψηλότερης ανάλυσης. + +## Εξήγηση Βήμα‑προς‑Βήμα + +### Βήμα 1 – **create OCR engine python** στιγμιότυπο + +Η κλάση `OcrEngine` είναι το σημείο εισόδου. Σκεφτείτε το σαν ένα κενό σημειωματάριο—δεν συμβαίνει τίποτα μέχρι να του πείτε ποια γλώσσα να περιμένει και αν αντιμετωπίζει χειρόγραφο. + +### Βήμα 2 – Επιλέξτε γλώσσα που υποστηρίζει χειρόγραφο + +`ocr.Language.EXTENDED_LATIN` δεν είναι μόνο “English”. Συμπεριλαμβάνει ένα σύνολο λατινικών γραφών και, κρίσιμα, μοντέλα εκπαιδευμένα σε δείγματα πλάγιου κειμένου. Η παράλειψη αυτού του βήματος συχνά οδηγεί σε ακατανόητο αποτέλεσμα επειδή η μηχανή προεπιλέγει μοντέλο τυπωμένου κειμένου. + +### Βήμα 3 – **turn on handwritten mode** + +Καλώντας `enable_handwritten_mode(True)` ενεργοποιείται μια εσωτερική σημαία. Η μηχανή τότε μεταβαίνει στο νευρωνικό δίκτυό της που είναι ρυθμισμένο για την ακανόνιστη απόσταση και τις μεταβλητές πλάτους γραμμής που βλέπετε σε πραγματικές σημειώσεις. Η παράλειψη αυτής της γραμμής είναι κοινό λάθος· η μηχανή θα θεωρήσει τις σημειώσεις σας ως θόρυβο. + +### Βήμα 4 – Τροφοδοτήστε την εικόνα και **recognize handwritten text** + +`recognize_image` κάνει τη βαριά δουλειά: προεπεξεργάζεται το bitmap, το τρέχει μέσω του μοντέλου χειρογράφου, και επιστρέφει ένα αντικείμενο με το χαρακτηριστικό `text`. Μπορείτε επίσης να ελέγξετε το `handwritten_result.confidence` αν χρειάζεστε μέτρο ποιότητας. + +### Βήμα 5 – Εκτυπώστε το αποτέλεσμα και **read handwritten notes** + +`print(handwritten_result.text)` είναι ο πιο απλός τρόπος να επαληθεύσετε ότι έχετε επιτυχώς **extract text from image**. Σε παραγωγή πιθανότατα θα αποθηκεύσετε τη συμβολοσειρά σε βάση δεδομένων ή θα τη μεταβιβάσετε σε άλλη υπηρεσία. + +## Διαχείριση Περιπτώσεων Άκρων & Κοινών Παραλλαγών + +| Κατάσταση | Τι να κάνετε | +|-----------|--------------| +| **Η εικόνα είναι περιστραμμένη** | Χρησιμοποιήστε το Pillow για περιστροφή (`Image.rotate(angle)`) πριν καλέσετε το `recognize_image`. | +| **Χαμηλή αντίθεση** | Μετατρέψτε σε κλίμακα του γκρι και εφαρμόστε προσαρμοστική διόρθωση κατωφλίου (`Image.point(lambda p: p > 128 and 255)`). | +| **Πολλές σελίδες** | Κάντε βρόχο πάνω σε μια λίστα διαδρομών αρχείων και συνενώστε τα αποτελέσματα. | +| **Μη‑λατινικά σενάρια** | Αντικαταστήστε το `EXTENDED_LATIN` με `ocr.Language.CHINESE` (ή κατάλληλο) και διατηρήστε το `enable_handwritten_mode(True)`. | +| **Ανησυχίες απόδοσης** | Επαναχρησιμοποιήστε το ίδιο στιγμιότυπο `ocr_engine` για πολλές εικόνες· η εκκίνηση του κάθε φορά προσθέτει επιβάρυνση. | + +### Συμβουλή για χρήση μνήμης + +Αν επεξεργάζεστε εκατοντάδες σημειώσεις σε παρτίδα, καλέστε `ocr_engine.dispose()` μετά το τέλος. Απελευθερώνει τους εγγενείς πόρους που μπορεί να κρατά το Python wrapper. + +## Σύντομη Οπτική Ανασκόπηση + +![recognize handwritten text example](https://example.com/handwritten-note.png "recognize handwritten text example") + +*Η παραπάνω εικόνα δείχνει μια τυπική χειρόγραφη σημείωση που το script μας μπορεί να μετατρέψει σε απλό κείμενο.* + +## Πλήρες Παράδειγμα Εργασίας (Script ενός Αρχείου) + +Για όσους αγαπούν την απλότητα του copy‑paste, εδώ είναι ολόκληρο το script ξανά χωρίς τα επεξηγηματικά σχόλια: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Τρέξτε το με: + +```bash +python handwriting_ocr.py +``` + +Τώρα θα πρέπει να δείτε το αποτέλεσμα **recognize handwritten text** στην κονσόλα σας. + +## Συμπέρασμα + +Μόλις καλύψαμε όλα όσα χρειάζεστε για να **recognize handwritten text** σε Python—από μια φρέσκια κλήση **create OCR engine python**, επιλογή της σωστής γλώσσας, **turn on handwritten mode**, και τελικά **extract text from image** για **read handwritten notes**. + +Σε ένα ενιαίο, αυτόνομο script μπορείτε να μετατρέψετε μια θολή φωτογραφία μιας σημείωσης συνάντησης σε καθαρό, αναζητήσιμο κείμενο. Στη συνέχεια, σκεφτείτε να τροφοδοτήσετε το αποτέλεσμα σε μια αλυσίδα επεξεργασίας φυσικής γλώσσας, να το αποθηκεύσετε σε ευρετήριο αναζήτησης, ή ακόμη να το στείλετε πίσω σε υπηρεσία μεταγραφής για δημιουργία φωνητικού overlay. + +### Πού να Πηγαίνετε Από Εδώ; + +- **Batch processing:** Τυλίξτε το script σε βρόχο για να διαχειριστείτε έναν φάκελο σκαναρισμάτων. +- **Confidence filtering:** Χρησιμοποιήστε το `result.confidence` για να απορρίψετε αναγνώσεις χαμηλής ποιότητας. +- **Alternative libraries:** Αν το `ocr` δεν είναι τέλειο, εξερευνήστε το `pytesseract` με `--psm 13` για λειτουργία χειρογράφου. +- **UI integration:** Συνδυάστε με Flask ή FastAPI για να προσφέρετε μια υπηρεσία ανεβάσματος μέσω web. + +Έχετε ερωτήσεις σχετικά με συγκεκριμένη μορφή εικόνας ή χρειάζεστε βοήθεια στη ρύθμιση του μοντέλου; Αφήστε ένα σχόλιο παρακάτω, και καλή προγραμματιστική! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/hindi/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..73c473545 --- /dev/null +++ b/ocr/hindi/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,188 @@ +--- +category: general +date: 2026-04-26 +description: HuggingFace मॉडल पायथन को डाउनलोड करना और पायथन में इमेज से टेक्स्ट निकालना + सीखें, साथ ही Aspose OCR क्लाउड के साथ OCR सटीकता को पायथन में सुधारें। +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: hi +og_description: हगिंगफ़ेस मॉडल पायथन डाउनलोड करें और अपने OCR पाइपलाइन को बूस्ट करें। + इस गाइड का पालन करके पायथन में इमेज से टेक्स्ट निकालें और OCR की सटीकता में सुधार + करें। +og_title: हगिंगफ़ेस मॉडल पायथन डाउनलोड – पूर्ण OCR सुधार ट्यूटोरियल +tags: +- OCR +- HuggingFace +- Python +- AI +title: हगिंगफ़ेस मॉडल पायथन डाउनलोड – चरण‑दर‑चरण OCR बूस्ट गाइड +url: /hi/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – पूर्ण OCR सुधार ट्यूटोरियल + +क्या आपने कभी **download HuggingFace model python** करने की कोशिश की है और थोड़ा भ्रमित महसूस किया? आप अकेले नहीं हैं। कई प्रोजेक्ट्स में सबसे बड़ी बाधा एक अच्छा मॉडल आपके मशीन पर लाना और फिर OCR परिणामों को वास्तव में उपयोगी बनाना है। + +इस गाइड में हम एक व्यावहारिक उदाहरण के माध्यम से चलेंगे जो आपको बिल्कुल दिखाएगा कि कैसे **download HuggingFace model python**, चित्र से टेक्स्ट निकालें **extract text from image python** के साथ, और फिर Aspose के AI पोस्ट‑प्रोसेसर का उपयोग करके **improve OCR accuracy python** करें। अंत तक आपके पास एक तैयार‑चलाने‑योग्य स्क्रिप्ट होगी जो शोरयुक्त इनवॉइस इमेज को साफ़, पठनीय टेक्स्ट में बदल देगी—कोई जादू नहीं, सिर्फ स्पष्ट कदम। + +## आपको क्या चाहिए + +- Python 3.9+ (कोड 3.11 पर भी काम करता है) +- एक इंटरनेट कनेक्शन एक‑बार मॉडल डाउनलोड के लिए +- `asposeocrcloud` पैकेज (`pip install asposeocrcloud`) +- एक सैंपल इमेज (जैसे, `sample_invoice.png`) जिसे आप नियंत्रित फ़ोल्डर में रखें + +बस इतना ही—कोई भारी फ्रेमवर्क नहीं, कोई GPU‑विशिष्ट ड्राइवर नहीं जब तक आप गति बढ़ाना न चाहें। + +अब, चलिए वास्तविक कार्यान्वयन में डुबकी लगाते हैं। + +![download huggingface model python कार्यप्रवाह](image.png "download huggingface model python आरेख") + +## चरण 1: OCR इंजन सेट अप करें और भाषा चुनें *(यह वह जगह है जहाँ हम **extract text from image python** शुरू करते हैं।)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**यह क्यों महत्वपूर्ण है:** +OCR इंजन पहली रक्षा की पंक्ति है; सही भाषा पैक चुनने से अक्षर‑पहचान त्रुटियों को तुरंत कम किया जा सकता है, जो **improve OCR accuracy python** का मुख्य भाग है। + +## चरण 2: AsposeAI मॉडल कॉन्फ़िगर करें – HuggingFace से डाउनलोड *(यहाँ हम वास्तव में **download HuggingFace model python** करते हैं।)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**आंतरिक रूप से क्या हो रहा है?** +जब `allow_auto_download` true होता है, तो SDK HuggingFace से संपर्क करता है, `Qwen2.5‑3B‑Instruct‑GGUF` मॉडल को प्राप्त करता है, और उसे आपके निर्दिष्ट फ़ोल्डर में संग्रहीत करता है। यह **download huggingface model python** का मूल है—SDK भारी काम संभालता है, इसलिए आपको स्वयं कोई `git clone` या `wget` कमांड लिखने की ज़रूरत नहीं है। + +*Pro tip:* `directory_model_path` को तेज़ लोड समय के लिए SSD पर रखें; मॉडल `int8` रूप में भी लगभग 3 GB है। + +## चरण 3: AI इंजन को OCR इंजन से जोड़ें *(दोनों हिस्सों को लिंक करके हम **improve OCR accuracy python** कर सकते हैं।)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**इन्हें क्यों बाइंड करें?** +OCR इंजन हमें कच्चा टेक्स्ट देता है, जिसमें वर्तनी त्रुटियां, टूटे हुए लाइनें, या गलत विराम चिह्न हो सकते हैं। AI इंजन एक स्मार्ट एडिटर की तरह काम करता है, उन समस्याओं को साफ़ करता है—बिल्कुल वही जो आपको **improve OCR accuracy python** चाहिए। + +## चरण 4: अपनी इमेज पर OCR चलाएँ *(वह क्षण जब हम अंततः **extract text from image python** करते हैं।)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` अब एक `text` एट्रिब्यूट रखता है जिसमें इंजन द्वारा देखे गए कच्चे अक्षर होते हैं। वास्तविक उपयोग में आपको कुछ गड़बड़ियां दिख सकती हैं—शायद “Invoice” “Inv0ice” बन गया हो या वाक्य के बीच में लाइन ब्रेक हो। + +## चरण 5: AI पोस्ट‑प्रोसेसर से साफ़‑सफ़ाई करें *(यह चरण सीधे **improve OCR accuracy python** करता है।)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +AI मॉडल टेक्स्ट को पुनः लिखता है, भाषा‑सचेत सुधार लागू करता है। क्योंकि हमने HuggingFace से एक instruction‑tuned मॉडल इस्तेमाल किया है, आउटपुट आमतौर पर प्रवाहपूर्ण और डाउनस्ट्रीम प्रोसेसिंग के लिए तैयार रहता है। + +## चरण 6: पहले और बाद को दिखाएँ *(एक त्वरित सत्यापन कि हम कितनी अच्छी तरह **extract text from image python** और **improve OCR accuracy python** कर रहे हैं।)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### अपेक्षित आउटपुट + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +ध्यान दें कि AI ने “Inv0ice” को “Invoice” में सुधार दिया और किसी भी अनावश्यक लाइन ब्रेक को सुगम बना दिया। यह **improve OCR accuracy python** का ठोस परिणाम है, जो डाउनलोड किए गए HuggingFace मॉडल का उपयोग करके प्राप्त हुआ। + +## अक्सर पूछे जाने वाले प्रश्न (FAQ) + +### क्या मॉडल चलाने के लिए मुझे GPU की आवश्यकता है? + +नहीं। `gpu_layers=20` सेटिंग SDK को बताती है कि यदि संगत GPU मौजूद है तो अधिकतम 20 GPU लेयर्स का उपयोग करे; अन्यथा यह CPU पर वापस आ जाता है। एक आधुनिक लैपटॉप पर CPU पाथ अभी भी प्रति सेकंड कुछ सौ टोकन प्रोसेस करता है—अवधिक इनवॉइस पार्सिंग के लिए उपयुक्त। + +### अगर मॉडल डाउनलोड नहीं होता तो क्या करें? + +सुनिश्चित करें कि आपका वातावरण `https://huggingface.co` तक पहुँच सकता है। यदि आप कॉरपोरेट प्रॉक्सी के पीछे हैं, तो `HTTP_PROXY` और `HTTPS_PROXY` पर्यावरण वेरिएबल सेट करें। SDK स्वचालित रूप से पुनः प्रयास करेगा, लेकिन आप मैन्युअली भी `git lfs pull` करके रेपो को `directory_model_path` में ला सकते हैं। + +### क्या मैं मॉडल को छोटे मॉडल से बदल सकता हूँ? + +बिल्कुल। बस `hugging_face_repo_id` को किसी अन्य रेपो (जैसे, `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) से बदलें और `hugging_face_quantization` को उसी अनुसार समायोजित करें। छोटे मॉडल तेज़ी से डाउनलोड होते हैं और कम RAM उपयोग करते हैं, हालांकि आपको सुधार की गुणवत्ता में थोड़ा कमी मिल सकती है। + +### यह मुझे अन्य डोमेनों में **extract text from image python** कैसे मदद करता है? + +एक ही पाइपलाइन रसीदों, पासपोर्ट या हाथ से लिखे नोट्स के लिए काम करती है। केवल बदलाव भाषा पैक (`ocr.Language.FRENCH`, आदि) और संभवतः HuggingFace से डोमेन‑विशिष्ट फाइन‑ट्यून्ड मॉडल है। + +## बोनस: कई फ़ाइलों का स्वचालन + +यदि आपके पास इमेजों से भरा फ़ोल्डर है, तो OCR कॉल को एक सरल लूप में लपेटें: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +यह छोटा जोड़ आपको **download huggingface model python** एक बार करने देता है, फिर दर्जनों फ़ाइलों को बैच‑प्रोसेस करता है—आपके दस्तावेज़‑ऑटोमेशन पाइपलाइन को स्केल करने के लिए शानदार। + +## निष्कर्ष + +हमने अभी एक पूर्ण, अंत‑से‑अंत उदाहरण के माध्यम से चलकर दिखाया है कि कैसे **download HuggingFace model python**, **extract text from image python**, और **improve OCR accuracy python** को Aspose के OCR क्लाउड और AI पोस्ट‑प्रोसेसर का उपयोग करके किया जाता है। स्क्रिप्ट चलाने के लिए तैयार है, अवधारणाएँ समझाई गई हैं, और आपने पहले‑और‑बाद आउटपुट देखा है जिससे आप जानते हैं कि यह काम करता है। + +अगला क्या? एक अलग HuggingFace मॉडल बदलकर देखें, अन्य भाषा पैकों के साथ प्रयोग करें, या साफ़ किए गए टेक्स्ट को डाउनस्ट्रीम NLP पाइपलाइन में फीड करें (जैसे, इनवॉइस लाइन आइटम्स के लिए एंटिटी एक्सट्रैक्शन)। संभावनाएँ असीमित हैं, और आपने जो नींव बनाई है वह ठोस है। + +क्या आपके पास प्रश्न हैं या कोई जटिल इमेज है जो अभी भी OCR को फँसाती है? नीचे टिप्पणी छोड़ें, और चलिए साथ में समस्या हल करें। कोडिंग का आनंद लें! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/hindi/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..1297eda68 --- /dev/null +++ b/ocr/hindi/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-04-26 +description: Aspose OCR Python का उपयोग करके OCR मॉडल को जल्दी डाउनलोड करें। जानिए + कैसे मॉडल डायरेक्टरी सेट करें, मॉडल पाथ को कॉन्फ़िगर करें, और कुछ लाइनों में मॉडल + डाउनलोड करें। +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: hi +og_description: Aspose OCR Python के साथ सेकंड में OCR मॉडल डाउनलोड करें। यह गाइड + दिखाता है कि मॉडल डायरेक्टरी कैसे सेट करें, मॉडल पाथ को कॉन्फ़िगर करें, और मॉडल + को सुरक्षित रूप से कैसे डाउनलोड करें। +og_title: OCR मॉडल डाउनलोड करें – पूर्ण Aspose OCR पायथन ट्यूटोरियल +tags: +- OCR +- Python +- Aspose +title: Aspose OCR Python के साथ OCR मॉडल डाउनलोड करें – चरण‑दर‑चरण गाइड +url: /hi/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – Complete Aspose OCR Python ट्यूटोरियल + +क्या आप कभी यह सोचते रहे हैं कि **download ocr model** को Aspose OCR के साथ Python में बिना अनगिनत दस्तावेज़ों के खोजे कैसे डाउनलोड किया जाए? आप अकेले नहीं हैं। कई डेवलपर्स को तब समस्या आती है जब मॉडल स्थानीय रूप से मौजूद नहीं होता और SDK एक अस्पष्ट त्रुटि फेंकता है। अच्छी खबर? समाधान कुछ ही लाइनों का है, और आप मिनटों में मॉडल तैयार कर लेंगे। + +इस ट्यूटोरियल में हम सब कुछ कवर करेंगे: सही क्लासेज़ को इम्पोर्ट करने से लेकर **set model directory**, वास्तविक **how to download model**, और अंत में पाथ की पुष्टि तक। अंत तक आप किसी भी इमेज पर एक ही फ़ंक्शन कॉल से OCR चला पाएँगे, और आप **configure model path** विकल्पों को समझेंगे जो आपके प्रोजेक्ट को व्यवस्थित रखेंगे। कोई फालतू बात नहीं, सिर्फ एक व्यावहारिक, चलने योग्य उदाहरण **aspose ocr python** उपयोगकर्ताओं के लिए। + +## आप क्या सीखेंगे + +- Aspose OCR Cloud क्लासेज़ को सही तरीके से इम्पोर्ट करना। +- **download ocr model** को स्वचालित रूप से डाउनलोड करने के सटीक चरण। +- पुनरुत्पादनीय बिल्ड्स के लिए **set model directory** और **configure model path** के तरीके। +- यह सत्यापित करना कि मॉडल इनिशियलाइज़्ड है और डिस्क पर कहाँ स्थित है। +- सामान्य समस्याएँ (परमिशन, गायब डायरेक्टरी) और त्वरित समाधान। + +### आवश्यकताएँ + +- आपके मशीन पर Python 3.8+ इंस्टॉल हो। +- `asposeocrcloud` पैकेज (`pip install asposeocrcloud`)। +- उस फ़ोल्डर पर लिखने की अनुमति जहाँ आप मॉडल स्टोर करना चाहते हैं (उदाहरण के लिए, `C:\models` या `~/ocr_models`)। + +--- + +## चरण 1: Aspose OCR Cloud क्लासेज़ इम्पोर्ट करें + +सबसे पहले आपको सही इम्पोर्ट स्टेटमेंट चाहिए। यह उन क्लासेज़ को लाता है जो मॉडल कॉन्फ़िगरेशन और OCR ऑपरेशन्स को मैनेज करती हैं। + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Why this matters:* `AsposeAI` वह इंजन है जो OCR चलाएगा, जबकि `AsposeAIModelConfig` इंजन को **where** मॉडल देखना है और **whether** उसे स्वचालित रूप से फ़ेच करना चाहिए, बताता है। इस चरण को छोड़ने या गलत मॉड्यूल इम्पोर्ट करने से `ModuleNotFoundError` आएगा, यहाँ तक कि डाउनलोड भाग तक पहुँचने से पहले। + +--- + +## चरण 2: मॉडल कॉन्फ़िगरेशन परिभाषित करें (Set Model Directory & Configure Model Path) + +अब हम Aspose को बताते हैं कि मॉडल फ़ाइलें कहाँ रखी जाएँ। यही वह जगह है जहाँ आप **set model directory** और **configure model path** करेंगे। + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**टिप्स और गोटचाज़** + +- **Absolute paths** स्क्रिप्ट अलग वर्किंग डायरेक्टरी से चलने पर भ्रम से बचाते हैं। +- Linux/macOS पर आप `"/home/you/ocr_models"` उपयोग कर सकते हैं; Windows पर बैकस्लैश को लिटरली ट्रीट करने के लिए `r` प्रीफ़िक्स दें। +- `allow_auto_download="true"` सेट करना **how to download model** को अतिरिक्त कोड लिखे बिना सक्षम करने की कुंजी है। + +--- + +## चरण 3: कॉन्फ़िगरेशन का उपयोग करके AsposeAI इंस्टेंस बनाएं + +कॉन्फ़िगरेशन तैयार होने पर, OCR इंजन का इंस्टेंस बनाएँ। + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Why this matters:* `ocr_ai` ऑब्जेक्ट अब वह कॉन्फ़िगरेशन रखता है जो हमने अभी परिभाषित किया है। यदि मॉडल मौजूद नहीं है, तो अगली कॉल स्वचालित रूप से डाउनलोड को ट्रिगर करेगी—यह **how to download model** का मुख्य भाग है। + +--- + +## चरण 4: मॉडल डाउनलोड ट्रिगर करें (यदि आवश्यक हो) + +OCR चलाने से पहले, आपको सुनिश्चित करना होगा कि मॉडल वास्तव में डिस्क पर है। `is_initialized()` मेथड दोनों ही जाँच करता है और इनिशियलाइज़ेशन को फोर्स करता है। + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**What happens under the hood?** + +- पहला `is_initialized()` कॉल `False` रिटर्न करता है क्योंकि मॉडल फ़ोल्डर खाली है। +- `print` उपयोगकर्ता को बताता है कि डाउनलोड शुरू होने वाला है। +- दूसरा कॉल Aspose को पहले निर्दिष्ट Hugging Face रेपो से मॉडल फ़ेच करने के लिए मजबूर करता है। +- डाउनलोड हो जाने पर, बाद के कॉल्स `True` रिटर्न करेंगे। + +**Edge case:** यदि आपका नेटवर्क Hugging Face को ब्लॉक करता है, तो आपको एक एक्सेप्शन दिखेगा। ऐसे में, मॉडल ज़िप को मैन्युअली डाउनलोड करें, उसे `directory_model_path` में एक्सट्रैक्ट करें, और स्क्रिप्ट फिर से चलाएँ। + +--- + +## चरण 5: मॉडल जहाँ उपलब्ध है उसका स्थानीय पथ रिपोर्ट करें + +डाउनलोड समाप्त होने के बाद, आप संभवतः जानना चाहेंगे कि फ़ाइलें कहाँ रखी गईं। यह डिबगिंग और CI पाइपलाइन सेटअप में मदद करता है। + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Typical output looks like: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +अब आपने सफलतापूर्वक **download ocr model**, डायरेक्टरी सेट कर ली है, और पाथ की पुष्टि कर ली है। + +--- + +## दृश्य अवलोकन + +नीचे एक सरल डायग्राम है जो कॉन्फ़िगरेशन से लेकर तैयार‑टू‑यूज़ मॉडल तक का फ्लो दिखाता है। + +![download ocr model flow diagram showing configuration, automatic download, and local path](/images/download-ocr-model-flow.png) + +*Alt text includes the primary keyword for SEO.* + +--- + +## सामान्य विविधताएँ और उन्हें कैसे संभालें + +### 1. अलग मॉडल रिपॉजिटरी का उपयोग करना + +यदि आपको `openai/gpt2` के अलावा कोई मॉडल चाहिए, तो बस `hugging_face_repo_id` वैल्यू को बदल दें: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +सुनिश्चित करें कि रेपो पब्लिक है या आपके पास आवश्यक टोकन आपके एनवायरनमेंट में सेट है। + +### 2. ऑटोमैटिक डाउनलोड को डिसेबल करना + +कभी‑कभी आप डाउनलोड को स्वयं कंट्रोल करना चाहते हैं (जैसे, एयर‑गैप्ड एनवायरनमेंट में)। `allow_auto_download` को `"false"` सेट करें और इनिशियलाइज़ करने से पहले एक कस्टम डाउनलोड स्क्रिप्ट चलाएँ: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. रनटाइम पर मॉडल डायरेक्टरी बदलना + +आप `AsposeAI` ऑब्जेक्ट को फिर से नहीं बनाते हुए पाथ को री‑कॉन्फ़िगर कर सकते हैं: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## प्रोडक्शन उपयोग के लिए प्रो टिप्स + +- **Cache the model**: यदि कई सर्विसेज़ को एक ही मॉडल चाहिए तो डायरेक्टरी को शेयरड नेटवर्क ड्राइव पर रखें। इससे अनावश्यक डाउनलोड से बचा जा सकता है। +- **Version pinning**: Hugging Face रेपो अपडेट हो सकता है। किसी विशिष्ट संस्करण को लॉक करने के लिए रेपो ID के अंत में `@v1.0.0` जोड़ें (`"openai/gpt2@v1.0.0"`). +- **Permissions**: सुनिश्चित करें कि स्क्रिप्ट चलाने वाला यूज़र `directory_model_path` पर पढ़ने/लिखने का अधिकार रखता है। Linux पर `chmod 755` आमतौर पर पर्याप्त होता है। +- **Logging**: सरल `print` स्टेटमेंट्स को Python के `logging` मॉड्यूल से बदलें ताकि बड़े एप्लिकेशन में बेहतर ऑब्ज़रवबिलिटी मिले। + +--- + +## पूर्ण कार्यशील उदाहरण (कॉपी‑पेस्ट तैयार) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Expected output** (पहली रन में डाउनलोड होगा, बाद की रन में डाउनलोड स्किप होगा): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +स्क्रिप्ट को फिर से चलाएँ; आपको केवल पाथ लाइन दिखेगी क्योंकि मॉडल पहले से ही कैश्ड है। + +--- + +## निष्कर्ष + +हमने अभी Aspose OCR Python का उपयोग करके **download ocr model** करने की पूरी प्रक्रिया को कवर किया, **set model directory** कैसे सेट करें दिखाया, और **configure model path** की बारीकियों को समझाया। कुछ ही लाइनों के कोड से आप डाउनलोड को ऑटोमैटिक बना सकते हैं, मैनुअल स्टेप्स से बच सकते हैं, और अपना OCR पाइपलाइन पुनरुत्पादनीय रख सकते हैं। + +अगला कदम आप वास्तविक OCR कॉल (`ocr_ai.recognize_image(...)`) को एक्सप्लोर कर सकते हैं या बेहतर एक्यूरेसी के लिए कोई अलग Hugging Face मॉडल आज़मा सकते हैं। चाहे जो भी हो, यहाँ बनाई गई नींव—स्पष्ट कॉन्फ़िगरेशन, ऑटोमैटिक डाउनलोड, और पाथ वेरिफिकेशन—भविष्य की किसी भी इंटीग्रेशन को आसान बना देगी। + +क्या आपके पास एज केसों के बारे में प्रश्न हैं, या आप क्लाउड डिप्लॉयमेंट के लिए मॉडल डायरेक्टरी को कैसे ट्यून किया, यह साझा करना चाहते हैं? नीचे कमेंट करें, और हैप्पी कोडिंग! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/hindi/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..8169db7b8 --- /dev/null +++ b/ocr/hindi/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-04-26 +description: OCR परिणामों को पोस्ट‑प्रोसेस कैसे करें और निर्देशांक के साथ टेक्स्ट + निकालें। संरचित आउटपुट और AI सुधार का उपयोग करके चरण‑दर‑चरण समाधान सीखें। +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: hi +og_description: OCR परिणामों को पोस्ट‑प्रोसेस कैसे करें और कोऑर्डिनेट्स के साथ टेक्स्ट + निकालें। विश्वसनीय वर्कफ़्लो के लिए इस व्यापक ट्यूटोरियल का पालन करें। +og_title: OCR को पोस्ट‑प्रोसेस कैसे करें – पूर्ण गाइड +tags: +- OCR +- Python +- AI +- Text Extraction +title: OCR को पोस्ट‑प्रोसेस कैसे करें – पाइथन में निर्देशांक के साथ टेक्स्ट निकालें +url: /hi/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR को पोस्ट‑प्रोसेस कैसे करें – Python में कॉर्डिनेट्स के साथ टेक्स्ट निकालें + +क्या आपको कभी **how to post‑process OCR** परिणामों की जरूरत पड़ी है क्योंकि कच्चा आउटपुट शोरयुक्त या गलत‑संरेखित था? आप अकेले नहीं हैं। कई वास्तविक‑दुनिया प्रोजेक्ट्स—इनवॉइस स्कैनिंग, रसीद डिजिटाइज़ेशन, या यहाँ तक कि AR अनुभवों को बढ़ाने में—OCR इंजन आपको कच्चे शब्द देता है, लेकिन आपको उन्हें साफ़ करना पड़ता है और यह ट्रैक रखना पड़ता है कि प्रत्येक शब्द पेज पर कहाँ स्थित है। यही वह जगह है जहाँ एक structured output मोड और AI‑ड्रिवेन पोस्ट‑प्रोसेसर मिलकर चमकते हैं। + +इस ट्यूटोरियल में हम एक पूर्ण, चलाने योग्य Python पाइपलाइन के माध्यम से जाएंगे जो एक इमेज से **extracts text with coordinates** निकालता है, AI‑आधारित सुधार चरण चलाता है, और प्रत्येक शब्द को उसके (x, y) स्थान के साथ प्रिंट करता है। कोई गायब इम्पोर्ट नहीं, कोई अस्पष्ट “see the docs” शॉर्टकट नहीं—बस एक स्व-निहित समाधान जिसे आप आज ही अपने प्रोजेक्ट में डाल सकते हैं। + +> **Pro tip:** यदि आप कोई अलग OCR लाइब्रेरी उपयोग कर रहे हैं, तो “structured” या “layout” मोड देखें; अवधारणाएँ वही रहती हैं। + +--- + +## आवश्यकताएँ + +शुरू करने से पहले, सुनिश्चित करें कि आपके पास है: + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.9+ | आधुनिक सिंटैक्स और टाइप हिंट्स | +| `ocr` library that supports `OutputMode.STRUCTURED` (e.g., a fictional `myocr`) | बाउंडिंग‑बॉक्स डेटा के लिए आवश्यक | +| An AI post‑processing module (could be OpenAI, HuggingFace, or a custom model) | OCR के बाद सटीकता में सुधार करता है | +| An image file (`input.png`) in your working directory | वह स्रोत जिसे हम पढ़ेंगे | + +यदि इनमें से कोई भी अपरिचित लग रहा है, तो बस प्लेसहोल्डर पैकेज `pip install myocr ai‑postproc` से इंस्टॉल करें। नीचे दिया गया कोड भी फॉलबैक स्टब्स शामिल करता है ताकि आप वास्तविक लाइब्रेरीज़ के बिना फ्लो का परीक्षण कर सकें। + +## चरण 1: OCR इंजन के लिए Structured Output मोड सक्षम करें + +पहला काम हम OCR इंजन को यह बताना है कि वह हमें केवल साधारण टेक्स्ट से अधिक दे। Structured output प्रत्येक शब्द को उसके बाउंडिंग बॉक्स और कॉन्फिडेंस स्कोर के साथ लौटाता है, जो बाद में **extract text with coordinates** के लिए आवश्यक है। + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Why this matters:* बिना structured मोड के आपको केवल एक लंबी स्ट्रिंग मिलेगी, और आप वह स्पैशियल जानकारी खो देंगे जो इमेज पर टेक्स्ट ओवरले करने या डाउनस्ट्रीम लेआउट विश्लेषण के लिए आवश्यक है। + +## चरण 2: इमेज को पहचानें और शब्द, बॉक्स, तथा कॉन्फिडेंस कैप्चर करें + +अब हम इमेज को इंजन में फीड करते हैं। परिणाम एक ऑब्जेक्ट है जिसमें शब्द ऑब्जेक्ट्स की सूची होती है, प्रत्येक `text`, `x`, `y`, `width`, `height`, और `confidence` को एक्सपोज़ करता है। + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Edge case:* यदि इमेज खाली या पढ़ने योग्य नहीं है, तो `structured_result.words` एक खाली सूची होगी। इसे जांचना और सुगमता से हैंडल करना अच्छा अभ्यास है। + +## चरण 3: स्थितियों को संरक्षित रखते हुए AI‑आधारित पोस्ट‑प्रोसेसिंग चलाएँ + +भले ही सबसे अच्छे OCR इंजन भी गलतियाँ करते हैं—जैसे “O” बनाम “0” या लापता डायक्रिटिक्स। डोमेन‑स्पेसिफिक टेक्स्ट पर प्रशिक्षित AI मॉडल उन त्रुटियों को सुधार सकता है। महत्वपूर्ण बात यह है कि हम मूल कॉर्डिनेट्स को रखते हैं ताकि स्पैशियल लेआउट अपरिवर्तित रहे। + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Why we preserve coordinates:* कई डाउनस्ट्रीम टास्क (जैसे PDF जेनरेशन, AR लेबलिंग) सटीक प्लेसमेंट पर निर्भर करते हैं। AI केवल `text` फील्ड को बदलता है, `x`, `y`, `width`, `height` को अपरिवर्तित छोड़ता है। + +## चरण 4: सुधारे गए शब्दों पर इटरेट करें और उनके टेक्स्ट को कॉर्डिनेट्स के साथ दिखाएँ + +अंत में, हम सुधारे गए शब्दों पर लूप लगाते हैं और प्रत्येक शब्द को उसके टॉप‑लेफ़्ट कोने `(x, y)` के साथ प्रिंट करते हैं। यह **extract text with coordinates** लक्ष्य को पूरा करता है। + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**अपेक्षित आउटपुट (उदाहरण):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +प्रत्येक लाइन सुधारे गए शब्द और मूल इमेज पर उसका सटीक स्थान दिखाती है। + +## पूर्ण कार्यशील उदाहरण + +नीचे एक एकल स्क्रिप्ट है जो सब कुछ जोड़ती है। आप इसे कॉपी‑पेस्ट कर सकते हैं, इम्पोर्ट स्टेटमेंट्स को अपनी वास्तविक लाइब्रेरीज़ के अनुसार समायोजित कर सकते हैं, और सीधे चला सकते हैं। + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**स्क्रिप्ट चलाना** + +```bash +python ocr_postprocess_demo.py +``` + +यदि आपके पास वास्तविक लाइब्रेरीज़ इंस्टॉल हैं, तो स्क्रिप्ट आपके `input.png` को प्रोसेस करेगी। अन्यथा, स्टब इम्प्लीमेंटेशन आपको कोई बाहरी डिपेंडेंसी बिना अपेक्षित फ्लो और आउटपुट देखने देती है। + +## अक्सर पूछे जाने वाले प्रश्न (FAQ) + +| Question | Answer | +|----------|--------| +| *क्या यह Tesseract के साथ काम करता है?* | Tesseract स्वयं बॉक्स से बाहर कोई structured मोड प्रदान नहीं करता, लेकिन `pytesseract.image_to_data` जैसे रैपर्स बाउंडिंग बॉक्स लौटाते हैं जिन्हें आप उसी AI पोस्ट‑प्रोसेसर में फीड कर सकते हैं। | +| *यदि मुझे टॉप‑लेफ़्ट के बजाय बॉटम‑राइट कोना चाहिए तो?* | प्रत्येक शब्द ऑब्जेक्ट `width` और `height` भी प्रदान करता है। विपरीत कोना पाने के लिए `x2 = x + width` और `y2 = y + height` गणना करें। | +| *क्या मैं कई इमेजेज को बैच‑प्रोसेस कर सकता हूँ?* | बिल्कुल। चरणों को `for image_path in Path("folder").glob("*.png"):` लूप में रैप करें और प्रत्येक फ़ाइल के परिणाम एकत्र करें। | +| *सुधार के लिए मैं कौन सा AI मॉडल चुनूँ?* | सामान्य टेक्स्ट के लिए, OCR त्रुटियों पर फाइन‑ट्यून किया गया छोटा GPT‑2 काम करता है। डोमेन‑स्पेसिफिक डेटा (जैसे, मेडिकल प्रिस्क्रिप्शन) के लिए, शोर‑साफ़ डेटा पर पेयर्ड सीक्वेंस‑टू‑सीक्वेंस मॉडल ट्रेन करें। | +| *AI सुधार के बाद कॉन्फिडेंस स्कोर उपयोगी है?* | आप डिबगिंग के लिए अभी भी मूल कॉन्फिडेंस रख सकते हैं, लेकिन यदि मॉडल समर्थन करता है तो AI अपना स्वयं का कॉन्फिडेंस आउटपुट कर सकता है। | + +## किनारे के मामले और सर्वोत्तम प्रथाएँ + +1. **खाली या भ्रष्ट इमेजेज** – आगे बढ़ने से पहले हमेशा सत्यापित करें कि `structured_result.words` खाली नहीं है। +2. **नॉन‑लैटिन स्क्रिप्ट्स** – सुनिश्चित करें कि आपका OCR इंजन लक्ष्य भाषा के लिए कॉन्फ़िगर किया गया है; AI पोस्ट‑प्रोसेसर को उसी स्क्रिप्ट पर प्रशिक्षित होना चाहिए। +3. **परफॉर्मेंस** – AI सुधार महंगा हो सकता है। यदि आप वही इमेज पुनः उपयोग करेंगे तो परिणामों को कैश करें, या AI चरण को असिंक्रोनस चलाएँ। +4. **कोऑर्डिनेट सिस्टम** – OCR लाइब्रेरीज़ विभिन्न मूल बिंदु (टॉप‑लेफ़्ट बनाम बॉटम‑लेफ़्ट) उपयोग कर सकती हैं। PDF या कैनवस पर ओवरले करते समय तदनुसार समायोजित करें। + +## निष्कर्ष + +अब आपके पास **how to post‑process OCR** और विश्वसनीय रूप से **extract text with coordinates** के लिए एक ठोस, एंड‑टू‑एंड रेसिपी है। Structured output को सक्षम करके, परिणाम को AI सुधार लेयर से गुजारकर, और मूल बाउंडिंग बॉक्स को संरक्षित रखकर, आप शोरयुक्त OCR स्कैन को साफ़, स्पैशियल‑अवेयर टेक्स्ट में बदल सकते हैं जो PDF जेनरेशन, डेटा एंट्री ऑटोमेशन, या ऑगमेंटेड‑रियलिटी ओवरले जैसे डाउनस्ट्रीम टास्क के लिए तैयार है। + +अगले कदम के लिए तैयार? स्टब AI को OpenAI `gpt‑4o‑mini` कॉल से बदलें, या पाइपलाइन को FastAPI में इंटीग्रेट करें। + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/hindi/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..bd1df7d8d --- /dev/null +++ b/ocr/hindi/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-26 +description: Python के साथ छवियों को जल्दी पहचानना। इमेज रिकग्निशन पाइपलाइन, बैच प्रोसेसिंग + सीखें, और AI का उपयोग करके इमेज रिकग्निशन को स्वचालित करें। +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: hi +og_description: Python के साथ तेज़ी से छवियों को पहचानना। यह गाइड इमेज रिकग्निशन पाइपलाइन, + बैचिंग और एआई का उपयोग करके ऑटोमेशन को समझाता है। +og_title: इमेज को कैसे पहचानें – इमेज पहचान पाइपलाइन को स्वचालित करें +tags: +- image-processing +- python +- ai +title: छवियों को कैसे पहचानें – इमेज पहचान पाइपलाइन को स्वचालित करें +url: /hi/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# छवियों को पहचानने का तरीका – इमेज रिकग्निशन पाइपलाइन को स्वचालित करें + +क्या आपने कभी सोचा है **छवियों को कैसे पहचानें** बिना हजारों पंक्तियों का कोड लिखे? आप अकेले नहीं हैं—बहुत से डेवलपर्स को वही समस्या आती है जब उन्हें पहली बार दर्जनों या सैकड़ों तस्वीरों को प्रोसेस करना पड़ता है। अच्छी खबर? कुछ सरल चरणों के साथ आप एक पूर्ण‑ब्लोन इमेज रिकग्निशन पाइपलाइन बना सकते हैं जो बैचिंग, रनिंग और सफ़ाई खुद ही कर देती है। + +इस ट्यूटोरियल में हम एक पूर्ण, चलाने योग्य उदाहरण के माध्यम से दिखाएंगे **कैसे छवियों को बैच करें**, प्रत्येक को एक AI इंजन में फीड करें, परिणामों को पोस्ट‑प्रोसेस करें, और अंत में संसाधनों को रिलीज़ करें। अंत तक आपके पास एक स्व-निहित स्क्रिप्ट होगी जिसे आप किसी भी प्रोजेक्ट में डाल सकते हैं, चाहे आप फोटो‑टैगर, क्वालिटी‑कंट्रोल सिस्टम, या रिसर्च डेटासेट जेनरेटर बना रहे हों। + +## आप क्या सीखेंगे + +- **छवियों को कैसे पहचानें** एक मॉक AI इंजन का उपयोग करके (वास्तविक सेवाओं जैसे TensorFlow, PyTorch, या क्लाउड APIs के लिए पैटर्न समान है)। +- कैसे एक **इमेज रिकग्निशन पाइपलाइन** बनाएं जो बैच को प्रभावी ढंग से संभालती है। +- **इमेज रिकग्निशन को स्वचालित करने** का सबसे अच्छा तरीका ताकि आपको हर बार फाइलों पर मैन्युअल लूप न बनाना पड़े। +- पाइपलाइन को स्केल करने और संसाधनों को सुरक्षित रूप से मुक्त करने के टिप्स। + +> **पूर्वापेक्षाएँ:** Python 3.8+, फ़ंक्शन्स और लूप्स की बुनियादी समझ, और कुछ इमेज फ़ाइलें (या पाथ) जिन्हें आप प्रोसेस करना चाहते हैं। कोर उदाहरण के लिए कोई बाहरी लाइब्रेरी आवश्यक नहीं है, लेकिन हम बताएंगे कि जहाँ आप वास्तविक AI SDKs को प्लग‑इन कर सकते हैं। + +![बैच प्रोसेसिंग पाइपलाइन में छवियों को पहचानने का आरेख](pipeline.png "छवियों को पहचानने का आरेख") + +## चरण 1: अपनी छवियों को बैच करें – कैसे प्रभावी रूप से छवियों को बैच करें + +AI किसी भी भारी काम को करने से पहले, आपको उसे फीड करने के लिए छवियों का एक संग्रह चाहिए। इसे अपनी किराने की सूची की तरह सोचें; बाद में इंजन सूची में से एक‑एक आइटम लेगा। + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**बैच क्यों?** +बैचिंग आपके लिखने वाले बायलरप्लेट कोड की मात्रा को कम करती है और बाद में पैरललिज़्म जोड़ना आसान बनाती है। यदि आपको कभी 10 000 तस्वीरें प्रोसेस करनी हों, तो आप केवल `image_batch` के स्रोत को बदलेंगे—पाइपलाइन का बाकी हिस्सा अपरिवर्तित रहेगा। + +## चरण 2: इमेज रिकग्निशन पाइपलाइन चलाएँ (AI के साथ छवियों को पहचानें) + +अब हम बैच को वास्तविक रिकग्नाइज़र से जोड़ते हैं। वास्तविक‑दुनिया के परिदृश्य में आप `torchvision.models` या किसी क्लाउड एंडपॉइंट को कॉल कर सकते हैं; यहाँ हम व्यवहार को मॉक करते हैं ताकि ट्यूटोरियल स्व‑निहित रहे। + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**व्याख्या:** +- `engine.recognize_image` **इमेज रिकग्निशन पाइपलाइन** का हृदय है; यह एक डीप‑लर्निंग मॉडल या REST API को कॉल कर सकता है। +- `postprocessor.run` **इमेज रिकग्निशन को स्वचालित करने** का प्रदर्शन करता है, कच्ची प्रेडिक्शन्स को एक साफ़ डिक्शनरी में सामान्यीकृत करता है जिसे आप स्टोर या स्ट्रीम कर सकते हैं। +- हम प्रत्येक `corrected` डिक्शनरी को `recognized_results` में इकट्ठा करते हैं ताकि डाउनस्ट्रीम स्टेप्स (जैसे डेटाबेस इन्सर्शन) सरल हों। + +## चरण 3: पोस्ट‑प्रोसेस और स्टोर करें – इमेज रिकग्निशन परिणामों को स्वचालित करें + +प्रेडिक्शन्स की एक साफ़ सूची मिलने के बाद, आप आमतौर पर उन्हें स्थायी रूप से सहेजना चाहते हैं। नीचे दिया गया उदाहरण एक CSV फ़ाइल लिखता है; आप इसे डेटाबेस या मैसेज क्यू में बदल सकते हैं। + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**CSV क्यों?** +CSV सार्वभौमिक रूप से पढ़ी जा सकती है—Excel, pandas, यहाँ तक कि साधारण‑टेक्स्ट एडिटर भी इसे खोल सकते हैं। यदि बाद में आपको **इमेज रिकग्निशन को स्केल पर स्वचालित करने** की जरूरत पड़े, तो लिखने वाले ब्लॉक को अपने डेटा लेक में बुल्क इन्सर्ट से बदल दें। + +## चरण 4: सफ़ाई – AI संसाधनों को सुरक्षित रूप से रिलीज़ करें + +कई AI SDKs GPU मेमोरी आवंटित करते हैं या वर्कर थ्रेड्स बनाते हैं। उन्हें मुक्त करना भूल जाने से मेमोरी लीक्स और क्रैश हो सकते हैं। हालांकि हमारे मॉक ऑब्जेक्ट्स को इसकी आवश्यकता नहीं है, हम सही पैटर्न दिखाएंगे। + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +स्क्रिप्ट चलाने पर एक मैत्रीपूर्ण पुष्टि संदेश प्रिंट होता है, जो बताता है कि पाइपलाइन साफ़‑सुथरी समाप्त हो गई है। + +## पूर्ण कार्यशील स्क्रिप्ट + +सब कुछ एक साथ रखने पर, यहाँ पूरा, कॉपी‑एंड‑पेस्ट‑रेडी प्रोग्राम है: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### अपेक्षित आउटपुट + +जब आप स्क्रिप्ट चलाते हैं (मान लेते हैं कि तीन प्लेसहोल्डर पाथ मौजूद हैं), तो आपको कुछ इस तरह दिखेगा: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +और उत्पन्न `recognition_results.csv` में यह होगा: + +| छवि | लेबल | विश्वास | +|---------------------|-------|------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## निष्कर्ष + +अब आपके पास Python में **छवियों को कैसे पहचानें** का एक ठोस, एंड‑टू‑एंड उदाहरण है, जिसमें **इमेज रिकग्निशन पाइपलाइन**, बैच हैंडलिंग, और स्वचालित पोस्ट‑प्रोसेसिंग शामिल है। पैटर्न स्केलेबल है: मॉक क्लासेस को वास्तविक मॉडल से बदलें, बड़े `image_batch` को फीड करें, और आपके पास एक प्रोडक्शन‑रेडी समाधान है। + +और आगे बढ़ना चाहते हैं? ये अगले कदम आज़माएँ: + +- `MockEngine` को वास्तविक प्रेडिक्शन्स के लिए TensorFlow या PyTorch मॉडल से बदलें। +- बड़े बैचों को तेज़ करने के लिए लूप को `concurrent.futures.ThreadPoolExecutor` के साथ पैरललाइज़ करें। +- CSV राइटर को क्लाउड स्टोरेज बकेट से जोड़ें ताकि **इमेज रिकग्निशन को स्वचालित** किया जा सके वितरित वर्कर्स के बीच। + +बिना झिझक प्रयोग करें, चीज़ें तोड़ें, फिर उन्हें ठीक करें—यही तरीका है इमेज रिकग्निशन पाइपलाइन में महारत हासिल करने का। यदि आपको कोई समस्या आती है या सुधार के विचार हैं, तो नीचे टिप्पणी करें। हैप्पी कोडिंग! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/hindi/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..34bd18a08 --- /dev/null +++ b/ocr/hindi/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-04-26 +description: AsposeAI OCR पोस्ट‑प्रोसेसिंग का उपयोग करके क्रेडिट कार्ड नंबरों को जल्दी + से मास्क करें। PCI अनुपालन, रेगुलर एक्सप्रेशन मास्किंग और डेटा सैनिटाइज़ेशन को चरण‑दर‑चरण + ट्यूटोरियल में सीखें। +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: hi +og_description: AsposeAI के साथ OCR परिणामों में क्रेडिट कार्ड नंबरों को मास्क करें। + यह ट्यूटोरियल PCI अनुपालन, रेगुलर एक्सप्रेशन मास्किंग और डेटा सैनिटाइज़ेशन को कवर + करता है। +og_title: क्रेडिट कार्ड नंबरों को मास्क करें – पूर्ण पायथन OCR पोस्ट‑प्रोसेसिंग गाइड +tags: +- OCR +- Python +- security +title: OCR आउटपुट में क्रेडिट कार्ड नंबरों को मास्क करें – पूर्ण पायथन गाइड +url: /hi/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# क्रेडिट कार्ड नंबरों को मास्क करें – पूर्ण Python गाइड + +क्या आपको कभी OCR इंजन से सीधे प्राप्त टेक्स्ट में **क्रेडिट कार्ड नंबरों को मास्क करने** की ज़रूरत पड़ी है? आप अकेले नहीं हैं। नियामक उद्योगों में, पूर्ण PAN (Primary Account Number) को उजागर करना PCI अनुपालन ऑडिटरों के साथ बड़ी समस्या बन सकता है। अच्छी खबर यह है कि कुछ ही पंक्तियों के Python कोड और AsposeAI के पोस्ट‑प्रोसेसिंग हुक के साथ, आप मध्य के आठ अंकों को स्वचालित रूप से छिपा सकते हैं और सुरक्षित रह सकते हैं। + +इस ट्यूटोरियल में हम एक वास्तविक परिदृश्य पर चलेंगे: रसीद की छवि पर OCR चलाना, फिर एक कस्टम **OCR पोस्ट‑प्रोसेसिंग** फ़ंक्शन लागू करना जो किसी भी PCI डेटा को साफ़ करता है। अंत तक आपके पास एक पुन: उपयोग योग्य स्निपेट होगा जिसे आप किसी भी AsposeAI वर्कफ़्लो में जोड़ सकते हैं, साथ ही किनारे के मामलों को संभालने और समाधान को स्केल करने के लिए कुछ व्यावहारिक टिप्स भी। + +## आप क्या सीखेंगे + +- **AsposeAI** के साथ एक कस्टम पोस्ट‑प्रोसेसर कैसे रजिस्टर करें। +- क्यों **रेगुलर एक्सप्रेशन मास्किंग** तरीका तेज़ और भरोसेमंद है। +- डेटा सैनिटाइज़ेशन से संबंधित **PCI अनुपालन** की बुनियादी बातें। +- कई कार्ड फ़ॉर्मेट या अंतरराष्ट्रीय नंबरों के लिए पैटर्न को कैसे विस्तारित करें। +- अपेक्षित आउटपुट और यह कैसे सत्यापित करें कि मास्किंग काम कर रहा है। + +> **Prerequisites** – आपके पास एक कार्यशील Python 3 वातावरण, Aspose.AI for OCR पैकेज इंस्टॉल (`pip install aspose-ocr`), और एक सैंपल इमेज (जैसे `receipt.png`) होनी चाहिए जिसमें क्रेडिट‑कार्ड नंबर हो। अन्य कोई बाहरी सेवा आवश्यक नहीं है। + +--- + +## Step 1: Define a Post‑Processor that Masks Credit Card Numbers + +समाधान का दिल एक छोटे फ़ंक्शन में रहता है जो OCR परिणाम प्राप्त करता है, **रेगुलर एक्सप्रेशन मास्किंग** रूटीन चलाता है, और साफ़ किया हुआ टेक्स्ट लौटाता है। + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Why this works:** +- रेगुलर एक्सप्रेशन `(\d{4})\d{8}(\d{4})` ठीक 16 लगातार अंकों से मेल खाता है, जो Visa, MasterCard और कई अन्य कार्डों का सामान्य फ़ॉर्मेट है। +- पहले और आखिरी चार अंकों (`\1` और `\2`) को कैप्चर करके हम डिबगिंग के लिए पर्याप्त जानकारी रखते हैं, जबकि **PCI compliance** नियमों का पालन करते हैं जो पूर्ण PAN को स्टोर करने से रोकते हैं। +- प्रतिस्थापन `\1****\2` संवेदनशील मध्य के आठ अंकों को छिपा देता है, जिससे `1234567812345678` → `1234****5678` बन जाता है। + +> **Pro tip:** यदि आपको 15‑अंकीय American Express नंबरों का समर्थन चाहिए, तो एक दूसरा पैटर्न जैसे `r'(\d{4})\d{6}(\d{5})'` जोड़ें और दोनों रिप्लेसमेंट क्रमिक रूप से चलाएँ। + +--- + +## Step 2: Initialise the AsposeAI Engine + +पोस्ट‑प्रोसेसर को अटैच करने से पहले हमें OCR इंजन का एक इंस्टेंस चाहिए। AsposeAI OCR मॉडल और कस्टम प्रोसेसिंग के लिए एक सरल API बंडल करता है। + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Why initialise here?** +`AsposeAI` ऑब्जेक्ट को एक बार बनाकर कई छवियों में पुन: उपयोग करने से ओवरहेड कम होता है। इंजन भाषा मॉडल को कैश भी करता है, जिससे बाद के कॉल तेज़ होते हैं—जब आप रसीदों के बैच को स्कैन कर रहे हों तो यह उपयोगी है। + +--- + +## Step 3: Register the Custom Masking Function + +AsposeAI एक `set_post_processor` मेथड प्रदान करता है जो आपको कोई भी कॉलेबल प्लग‑इन करने देता है। हम अपना `mask_pci` फ़ंक्शन एक वैकल्पिक सेटिंग्स डिक्शनरी (अभी खाली) के साथ पास करते हैं। + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**What’s happening behind the scenes?** +जब आप बाद में `run_postprocessor` को कॉल करेंगे, AsposeAI कच्चे OCR परिणाम को `mask_pci` को देगा। फ़ंक्शन एक हल्के ऑब्जेक्ट (`data`) प्राप्त करता है जिसमें पहचाना गया टेक्स्ट होता है, और आप एक नया स्ट्रिंग लौटाते हैं। यह डिज़ाइन कोर OCR को अपरिवर्तित रखता है जबकि आपको **डेटा सैनिटाइज़ेशन** नीतियों को एक ही जगह लागू करने देता है। + +--- + +## Step 4: Run OCR on the Receipt Image + +अब जब इंजन को आउटपुट साफ़ करने का तरीका पता है, हम उसे एक इमेज देते हैं। इस ट्यूटोरियल के लिए मान लेते हैं कि आपके पास पहले से ही सही भाषा और रिज़ॉल्यूशन सेटिंग्स वाला `engine` ऑब्जेक्ट कॉन्फ़िगर है। + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Tip:** यदि आपके पास प्री‑कॉन्फ़िगर्ड ऑब्जेक्ट नहीं है, तो आप इसे इस तरह बना सकते हैं: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +`recognize_image` कॉल एक ऑब्जेक्ट लौटाता है जिसका `text` एट्रिब्यूट कच्चा, अनमास्क्ड स्ट्रिंग रखता है। + +--- + +## Step 5: Apply the Registered Post‑Processor + +कच्चा OCR डेटा हाथ में होने पर, हम उसे AI इंस्टेंस को देते हैं। इंजन स्वचालित रूप से पहले रजिस्टर किए गए `mask_pci` फ़ंक्शन को चलाता है। + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Why use `run_postprocessor` instead of calling the function manually?** +यह वर्कफ़्लो को सुसंगत रखता है, विशेषकर जब आपके पास कई पोस्ट‑प्रोसेसर (जैसे स्पेल‑चेकिंग, लैंग्वेज डिटेक्शन) हों। AsposeAI उन्हें रजिस्टर किए क्रम में कतारबद्ध करता है, जिससे आउटपुट डिटरमिनिस्टिक रहता है। + +--- + +## Step 6: Verify the Sanitized Output + +आख़िर में, साफ़ किया हुआ टेक्स्ट प्रिंट करें और पुष्टि करें कि सभी क्रेडिट‑कार्ड नंबर सही ढंग से मास्क हो गए हैं। + +```python +print(final_result.text) +``` + +**Expected output** (excerpt): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +यदि रसीद में कोई कार्ड नंबर नहीं था, तो टेक्स्ट अपरिवर्तित रहता है—मास्क करने को कुछ नहीं, चिंता करने को कुछ नहीं। + +--- + +## Handling Edge Cases and Common Variations + +### Multiple Card Numbers in One Document +यदि रसीद में एक से अधिक PAN (जैसे लॉयल्टी कार्ड + पेमेंट कार्ड) हों, तो रेगुलर एक्सप्रेशन ग्लोबली चलता है और सभी मैचों को स्वचालित रूप से मास्क करता है। अतिरिक्त कोड की आवश्यकता नहीं। + +### Non‑Standard Formatting +कभी‑कभी OCR स्पेस या डैश डाल देता है (`1234 5678 1234 5678` या `1234-5678-1234-5678`)। इन कैरेक्टर्स को अनदेखा करने के लिए पैटर्न को विस्तारित करें: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +जोड़ा गया `[ -]?` वैकल्पिक स्पेस या हाइफ़न को डिटेक्ट करता है। + +### International Cards +कुछ क्षेत्रों में 19‑अंकीय PAN उपयोग होते हैं; आप पैटर्न को इस तरह विस्तृत कर सकते हैं: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +सिर्फ यह याद रखें कि **PCI compliance** अभी भी मध्य के अंकों को मास्क करने की मांग करता है, चाहे लंबाई कुछ भी हो। + +### Logging Masked Values (Optional) +यदि आपको ऑडिट ट्रेल चाहिए, तो `custom_settings` के माध्यम से एक फ़्लैग पास करें और फ़ंक्शन को समायोजित करें: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +फिर इस तरह रजिस्टर करें: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Full Working Example (Copy‑Paste Ready) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +इस स्क्रिप्ट को `4111111111111111` वाले रसीद पर चलाने पर परिणाम होगा: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +यही पूरा पाइपलाइन है—कच्चे OCR से **डेटा सैनिटाइज़ेशन** तक—कुछ साफ़ Python लाइनों में बँधा हुआ। + +--- + +## Conclusion + +हमने दिखाया कि कैसे AsposeAI के पोस्ट‑प्रोसेसिंग हुक, एक संक्षिप्त रेगुलर‑एक्सप्रेशन रूटीन, और कुछ सर्वोत्तम‑प्रैक्टिस टिप्स का उपयोग करके OCR परिणामों में **क्रेडिट कार्ड नंबरों को मास्क** किया जा सकता है। समाधान पूरी तरह से स्व-निहित है, किसी भी इमेज के साथ काम करता है जिसे OCR पढ़ सकता है, और अधिक जटिल कार्ड फ़ॉर्मेट या लॉगिंग आवश्यकताओं को कवर करने के लिए विस्तारित किया जा सकता है। + +अगला कदम? इस मास्क को एक **डेटाबेस इन्सर्शन** रूटीन के साथ जोड़ें जो केवल आखिरी चार अंक ही स्टोर करे, या एक **बैच प्रोसेसर** बनाएं जो रात भर पूरी फ़ोल्डर की रसीदें स्कैन करे। आप अन्य **OCR पोस्ट‑प्रोसेसिंग** कार्यों जैसे पता मानकीकरण या भाषा पहचान को भी एक्सप्लोर कर सकते हैं—हर एक यहाँ दिखाए गए पैटर्न का पालन करता है। + +यदि आपके पास किनारे के मामलों, प्रदर्शन, या कोड को किसी अन्य OCR लाइब्रेरी के लिए अनुकूलित करने के बारे में प्रश्न हैं, तो नीचे टिप्पणी करें, और बातचीत जारी रखें। Happy coding, and stay secure! + +![क्रेडिट कार्ड नंबरों को मास्क करने के OCR पाइपलाइन में कैसे काम करता है का चित्रण](https://example.com/images/ocr-mask-flow.png "OCR पोस्ट‑प्रोसेसिंग मास्किंग फ्लो का चित्र") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/hindi/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..4598eedb3 --- /dev/null +++ b/ocr/hindi/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-04-26 +description: Python में inference time को मापना सीखें, Hugging Face से एक GGUF मॉडल + लोड करें, और तेज़ परिणामों के लिए GPU उपयोग को अनुकूलित करें। +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: hi +og_description: हगिंग फेस से GGUF मॉडल लोड करके और GPU लेयर्स को ट्यून करके पायथन + में इनफ़रेंस समय मापें, ताकि इष्टतम प्रदर्शन प्राप्त हो सके। +og_title: इनफ़रेंस समय मापें – GGUF मॉडल लोड करें और GPU को अनुकूलित करें +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: इन्फ़रेंस समय मापें – GGUF मॉडल लोड करें और GPU को अनुकूलित करें +url: /hi/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# इनफ़रेंस समय मापें – GGUF मॉडल लोड करें और GPU को ऑप्टिमाइज़ करें + +क्या आपको कभी बड़े भाषा मॉडल के लिए **measure inference time** करने की ज़रूरत पड़ी है लेकिन आप नहीं जानते थे कि कहाँ से शुरू करें? आप अकेले नहीं हैं—कई डेवलपर्स को वही समस्या आती है जब वे पहली बार Hugging Face से GGUF फ़ाइल लेते हैं और इसे मिश्रित CPU/GPU सेटअप पर चलाने की कोशिश करते हैं। + +इस गाइड में हम **how to load a GGUF model** को समझेंगे, इसे Hugging Face के लिए कॉन्फ़िगर करेंगे, और एक साफ़ Python स्निपेट के साथ **measure inference time** करेंगे। साथ ही हम आपको दिखाएंगे कि कैसे **optimize inference GPU** उपयोग को बेहतर बनाया जाए ताकि आपके रन जितना तेज़ हो सके उतना तेज़ हो। कोई फालतू बात नहीं, सिर्फ एक व्यावहारिक, एंड‑टू‑एंड समाधान जिसे आप आज ही कॉपी‑पेस्ट कर सकते हैं। + +## आप क्या सीखेंगे + +- कैसे **configure a HuggingFace model** को `AsposeAIModelConfig` के साथ कॉन्फ़िगर करें। +- Hugging Face हब से (`fp16` क्वांटाइज़ेशन) **load a GGUF model** करने के सटीक चरण। +- इनफ़रेंस कॉल के आसपास **timing Python code** के लिए एक पुन: उपयोग योग्य पैटर्न। +- `gpu_layers` को समायोजित करके **optimize inference GPU** के टिप्स। +- अपेक्षित आउटपुट और यह कैसे सत्यापित करें कि आपका टाइमिंग सही है। + +### पूर्वापेक्षाएँ + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.9+ | आधुनिक सिंटैक्स और टाइप हिंट्स। | +| `asposeai` package (or the equivalent SDK) | `AsposeAI` और `AsposeAIModelConfig` प्रदान करता है। | +| Access to the Hugging Face repo `bartowski/Qwen2.5-3B-Instruct-GGUF` | वह GGUF मॉडल जिसे हम लोड करेंगे। | +| A GPU with at least 8 GB VRAM (optional but recommended) | **optimize inference GPU** चरण को सक्षम करता है। | + +यदि आपने अभी तक SDK स्थापित नहीं किया है, तो चलाएँ: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![measure inference time diagram](https://example.com/measure-inference-time.png){alt="इनफ़रेंस समय मापने का आरेख"} + +## चरण 1: GGUF मॉडल लोड करें – HuggingFace मॉडल कॉन्फ़िगर करें + +पहली चीज़ जो आपको चाहिए वह एक उचित कॉन्फ़िगरेशन ऑब्जेक्ट है जो Aspose AI को बताता है कि मॉडल कहाँ से प्राप्त करना है और उसे कैसे संभालना है। यहाँ हम **load a GGUF model** और **configure huggingface model** पैरामीटर सेट करते हैं। + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**यह क्यों महत्वपूर्ण है:** +- `hugging_face_repo_id` हब पर सटीक GGUF फ़ाइल की ओर इशारा करता है। +- `fp16` मेमोरी बैंडविड्थ को कम करता है जबकि मॉडल की अधिकांश फ़िडेलिटी को बनाए रखता है। +- `gpu_layers` वह नियंत्रण है जिसे आप **optimize inference GPU** प्रदर्शन के लिए समायोजित करते हैं; GPU पर अधिक लेयर्स आमतौर पर तेज़ लेटेंसी का मतलब है, बशर्ते आपके पास पर्याप्त VRAM हो। + +## चरण 2: Aspose AI इंस्टेंस बनाएं + +अब जब मॉडल का विवरण हो गया है, हम एक `AsposeAI` ऑब्जेक्ट बनाते हैं। यह चरण सीधा है, लेकिन यहाँ SDK वास्तव में GGUF फ़ाइल को डाउनलोड करता है (यदि यह कैश नहीं है) और रनटाइम तैयार करता है। + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Pro tip:** पहला रन कुछ सेकंड अधिक लेगा क्योंकि मॉडल GPU के लिए डाउनलोड और कंपाइल हो रहा है। बाद के रन बहुत तेज़ होते हैं। + +## चरण 3: इनफ़रेंस चलाएँ और **Measure Inference Time** + +यह ट्यूटोरियल का मुख्य भाग है: इनफ़रेंस कॉल को `time.time()` से घेरकर **measure inference time** किया जाता है। हम एक छोटा OCR परिणाम भी देते हैं ताकि उदाहरण स्वयं‑समाहित रहे। + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**आपको क्या दिखना चाहिए:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +यदि संख्या अधिक लगती है, तो आप संभवतः अधिकांश लेयर्स CPU पर चला रहे हैं। यह हमें अगले चरण की ओर ले जाता है। + +## चरण 4: **Optimize Inference GPU** – `gpu_layers` को ट्यून करें + +कभी‑कभी डिफ़ॉल्ट `gpu_layers=40` बहुत अधिक आक्रामक (OOM का कारण बनता) या बहुत रूढ़िवादी (प्रदर्शन को कम छोड़ता) हो सकता है। यहाँ एक त्वरित लूप है जिसे आप सही बिंदु खोजने के लिए उपयोग कर सकते हैं: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**यह क्यों काम करता है:** +- प्रत्येक कॉल विभिन्न GPU आवंटन के साथ रनटाइम को पुनः बनाता है, जिससे आप तुरंत लेटेंसी ट्रेड‑ऑफ़ देख सकते हैं। +- लूप **time python code** को पुन: उपयोग योग्य तरीके से दर्शाता है, जिसे आप अन्य प्रदर्शन परीक्षणों के लिए अनुकूलित कर सकते हैं। + +16 GB RTX 3080 पर सामान्य आउटपुट इस प्रकार दिख सकता है: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +उससे, आप इस हार्डवेयर के लिए इष्टतम बिंदु के रूप में `gpu_layers=40` चुनेंगे। + +## पूर्ण कार्यशील उदाहरण + +सब कुछ मिलाकर, यहाँ एक एकल स्क्रिप्ट है जिसे आप फ़ाइल (`measure_inference.py`) में डाल सकते हैं और चला सकते हैं: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +इसे चलाएँ: + +```bash +python measure_inference.py +``` + +आपको एक उचित GPU पर सब‑सेकंड लेटेंसी दिखनी चाहिए, जिससे पुष्टि होगी कि आपने सफलतापूर्वक **measure inference time** और **optimize inference GPU** किया है। + +--- + +## अक्सर पूछे जाने वाले प्रश्न (FAQs) + +**प्रश्न: क्या यह अन्य क्वांटाइज़ेशन फ़ॉर्मेट्स के साथ काम करता है?** +**उत्तर:** बिल्कुल। कॉन्फ़िग में `hugging_face_quantization="int8"` (या `q4_0`, आदि) बदलें और बेंचमार्क को फिर से चलाएँ। एक ट्रेड‑ऑफ़ की उम्मीद रखें: कम मेमोरी उपयोग बनाम हल्का सटीकता में गिरावट। + +**प्रश्न: यदि मेरे पास GPU नहीं है तो क्या करें?** +**उत्तर:** `gpu_layers=0` सेट करें। कोड पूरी तरह से CPU पर वापस आ जाएगा, और आप अभी भी **measure inference time** कर सकते हैं—सिर्फ़ उच्च संख्याओं की अपेक्षा रखें। + +**प्रश्न: क्या मैं केवल मॉडल फ़ॉरवर्ड पास को टाइम कर सकता हूँ, पोस्ट‑प्रोसेसिंग को छोड़कर?** +**उत्तर:** हाँ। सीधे `ai_engine.run_model(...)` (या समकक्ष मेथड) को कॉल करें और उस कॉल को `time.time()` से घेरें। **time python code** का पैटर्न वही रहता है। + +## निष्कर्ष + +अब आपके पास एक पूर्ण, कॉपी‑एंड‑पेस्ट समाधान है **measure inference time** के लिए GGUF मॉडल के, Hugging Face से **load gguf model**, और **optimize inference GPU** सेटिंग्स को फाइन‑ट्यून करने का। `gpu_layers` को समायोजित करके और क्वांटाइज़ेशन के साथ प्रयोग करके, आप हर मिलीसेकंड प्रदर्शन को निकाल सकते हैं। + +आगे आप चाहेंगे: + +- इस टाइमिंग लॉजिक को CI पाइपलाइन में इंटीग्रेट करें ताकि रिग्रेशन पकड़े जा सकें। +- बैच इनफ़रेंस का अन्वेषण करें ताकि थ्रूपुट और बेहतर हो सके। +- मॉडल को वास्तविक OCR पाइपलाइन के साथ मिलाएँ, न कि यहाँ उपयोग किए गए डमी टेक्स्ट के साथ। + +कोडिंग का आनंद लें, और आपके लेटेंसी नंबर हमेशा कम रहें! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/hindi/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..796cf8bd6 --- /dev/null +++ b/ocr/hindi/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-26 +description: Python के OCR इंजन का उपयोग करके हस्तलेखित पाठ को पहचानें। जानें कि छवि + से टेक्स्ट कैसे निकालें, हस्तलेख मोड कैसे चालू करें, और हस्तलेखित नोट्स को जल्दी + पढ़ें। +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: hi +og_description: Python के साथ हस्तलेखित पाठ को पहचानें। यह ट्यूटोरियल दिखाता है कि + कैसे छवि से पाठ निकालें, हस्तलेख मोड चालू करें, और एक सरल OCR इंजन का उपयोग करके + हस्तलेखित नोट्स पढ़ें। +og_title: Python में हस्तलेखित पाठ को पहचानें – पूर्ण OCR गाइड +tags: +- OCR +- Python +- Handwriting Recognition +title: Python में हस्तलिखित पाठ को पहचानें – OCR इंजन ट्यूटोरियल +url: /hi/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python में हस्तलिखित पाठ को पहचानें – OCR इंजन ट्यूटोरियल + +क्या आपको कभी **हस्तलिखित पाठ को पहचानने** की ज़रूरत पड़ी, लेकिन “मैं कहाँ से शुरू करूँ?” पर अटक गए? आप अकेले नहीं हैं। चाहे आप मीटिंग के नोट्स को डिजिटल बना रहे हों या स्कैन किए हुए फ़ॉर्म से डेटा निकाल रहे हों, भरोसेमंद OCR परिणाम प्राप्त करना कभी‑कभी यूनिकॉर्न पकड़ने जैसा लग सकता है। + +अच्छी ख़बर: कुछ ही पंक्तियों के Python कोड से आप **छवि से पाठ निकाल सकते** हैं, **हस्तलिखित मोड चालू कर सकते** हैं, और अंत में **हस्तलिखित नोट्स पढ़ सकते** हैं, बिना किसी अजीब लाइब्रेरी की खोज किए। इस गाइड में हम पूरी प्रक्रिया को समझेंगे, **create OCR engine python** शैली की सेट‑अप से लेकर स्क्रीन पर परिणाम प्रिंट करने तक। + +## आप क्या सीखेंगे + +- `ocr` पैकेज का उपयोग करके **create OCR engine python** इंस्टेंस कैसे बनाते हैं। +- कौन सा भाषा सेटिंग बिल्ट‑इन हस्तलिखित समर्थन देती है। +- **turn on handwritten mode** को कॉल करने का सही तरीका ताकि इंजन समझे कि आप कर्सिव टेक्स्ट के साथ काम कर रहे हैं। +- नोट की तस्वीर को फीड करके **recognize handwritten text** कैसे प्राप्त करें। +- विभिन्न इमेज फ़ॉर्मेट्स को संभालने, सामान्य समस्याओं का समाधान करने, और समाधान को विस्तारित करने के टिप्स। + +कोई फालतू बात नहीं, कोई “डॉक्यूमेंटेशन देखें” वाला अडचन नहीं—बस एक पूरा, चलाने योग्य स्क्रिप्ट जो आप आज़मा सकते हैं। + +## पूर्वापेक्षाएँ + +शुरू करने से पहले सुनिश्चित करें कि आपके पास है: + +1. Python 3.8+ इंस्टॉल हो (कोड f‑strings का उपयोग करता है)। +2. काल्पनिक `ocr` लाइब्रेरी (`pip install ocr‑engine` – इसे अपने वास्तविक पैकेज नाम से बदलें)। +3. एक स्पष्ट हस्तलिखित नोट की इमेज फ़ाइल (JPEG, PNG, या TIFF काम करेंगे)। +4. थोड़ी जिज्ञासा—बाकी सब नीचे कवर किया गया है। + +> **Pro tip:** यदि आपकी इमेज शोरयुक्त है, तो OCR इंजन को भेजने से पहले Pillow के साथ एक तेज़ प्री‑प्रोसेसिंग स्टेप चलाएँ (जैसे `Image.open(...).convert('L')`)। यह अक्सर सटीकता बढ़ाता है। + +## Python के साथ हस्तलिखित पाठ को पहचानने का तरीका + +नीचे पूरा स्क्रिप्ट है जो **creates OCR engine python** ऑब्जेक्ट बनाता है, उन्हें हस्तलिखित के लिए कॉन्फ़िगर करता है, और निकाले गए स्ट्रिंग को प्रिंट करता है। इसे `handwriting_ocr.py` के रूप में सेव करें और टर्मिनल से चलाएँ। + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### अपेक्षित आउटपुट + +जब स्क्रिप्ट सफलतापूर्वक चलती है, तो आपको कुछ इस तरह दिखेगा: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +यदि OCR इंजन कोई अक्षर नहीं पहचान पाता, तो `text` फ़ील्ड खाली स्ट्रिंग होगी। ऐसे में इमेज की क्वालिटी दोबारा चेक करें या उच्च‑रिज़ॉल्यूशन स्कैन आज़माएँ। + +## चरण‑दर‑चरण व्याख्या + +### Step 1 – **create OCR engine python** इंस्टेंस + +`OcrEngine` क्लास एंट्री पॉइंट है। इसे एक खाली नोटबुक की तरह समझें—जब तक आप इसे भाषा और हस्तलिखित मोड के बारे में नहीं बताते, कुछ नहीं होता। + +### Step 2 – ऐसी भाषा चुनें जो हस्तलिखित को सपोर्ट करती हो + +`ocr.Language.EXTENDED_LATIN` सिर्फ “English” नहीं है। यह लैटिन‑आधारित स्क्रिप्ट्स का सेट बंडल करता है और महत्वपूर्ण रूप से कर्सिव सैंपल्स पर प्रशिक्षित मॉडल शामिल करता है। इस स्टेप को छोड़ने से अक्सर गड़बड़ आउटपुट मिलता है क्योंकि इंजन प्रिंटेड‑टेक्स्ट मॉडल को डिफ़ॉल्ट ले लेता है। + +### Step 3 – **turn on handwritten mode** + +`enable_handwritten_mode(True)` कॉल करने से एक आंतरिक फ़्लैग सेट होता है। इंजन तब अपने न्यूरल नेटवर्क पर स्विच करता है जो वास्तविक‑दुनिया के नोट्स में मिलने वाले अनियमित स्पेसिंग और वैरिएबल स्ट्रोक विड्थ के लिए ट्यून किया गया है। इस लाइन को भूलना आम गलती है; इंजन आपके स्क्रिबल को शोर समझ लेगा। + +### Step 4 – इमेज फीड करें और **recognize handwritten text** + +`recognize_image` भारी काम करता है: यह बिटमैप को प्री‑प्रोसेस करता है, उसे हस्तलिखित मॉडल से गुजराता है, और `text` एट्रिब्यूट वाला ऑब्जेक्ट रिटर्न करता है। यदि आपको क्वालिटी मेट्रिक चाहिए तो `handwritten_result.confidence` भी देख सकते हैं। + +### Step 5 – परिणाम प्रिंट करें और **read handwritten notes** + +`print(handwritten_result.text)` सबसे सरल तरीका है यह वेरिफ़ाई करने का कि आपने सफलतापूर्वक **extract text from image** कर लिया है। प्रोडक्शन में आप संभवतः इस स्ट्रिंग को डेटाबेस में स्टोर करेंगे या किसी अन्य सर्विस को पास करेंगे। + +## एज केस और सामान्य वैरिएशन्स को संभालना + +| Situation | What to Do | +|-----------|------------| +| **Image is rotated** | `recognize_image` कॉल करने से पहले Pillow से रोटेट करें (`Image.rotate(angle)`)। | +| **Low contrast** | ग्रेस्केल में कन्वर्ट करें और एडैप्टिव थ्रेशोल्डिंग लागू करें (`Image.point(lambda p: p > 128 and 255)`)। | +| **Multiple pages** | फ़ाइल पाथ की लिस्ट पर लूप चलाएँ और परिणामों को जोड़ें। | +| **Non‑Latin scripts** | `EXTENDED_LATIN` को `ocr.Language.CHINESE` (या उपयुक्त) से बदलें और `enable_handwritten_mode(True)` रखें। | +| **Performance concerns** | कई इमेजेज़ के लिए एक ही `ocr_engine` इंस्टेंस री‑यूज़ करें; हर बार नई इंस्टेंस बनाना ओवरहेड जोड़ता है। | + +### मेमोरी उपयोग पर Pro tip + +यदि आप बैच में सैकड़ों नोट्स प्रोसेस कर रहे हैं, तो काम ख़त्म होने पर `ocr_engine.dispose()` कॉल करें। यह नेटीव रिसोर्सेज़ को फ्री करता है जो Python रैपर रख सकता है। + +## त्वरित विज़ुअल रीकैप + +![recognize handwritten text example](https://example.com/handwritten-note.png "recognize handwritten text example") + +*ऊपर की इमेज एक सामान्य हस्तलिखित नोट दिखाती है जिसे हमारा स्क्रिप्ट साधारण टेक्स्ट में बदल सकता है।* + +## पूर्ण कार्यशील उदाहरण (एक‑फ़ाइल स्क्रिप्ट) + +जो लोग कॉपी‑पेस्ट की सादगी पसंद करते हैं, उनके लिए यहाँ पूरी स्क्रिप्ट फिर से बिना व्याख्यात्मक टिप्पणी के दी गई है: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +इसे इस कमांड से चलाएँ: + +```bash +python handwriting_ocr.py +``` + +अब आपको कंसोल में **recognize handwritten text** आउटपुट दिखाई देगा। + +## निष्कर्ष + +हमने अभी-अभी वह सब कवर किया जो आपको Python में **recognize handwritten text** करने के लिए चाहिए—एक नई **create OCR engine python** कॉल से शुरू करके, सही भाषा चुनना, **turn on handwritten mode** करना, और अंत में **extract text from image** करके **read handwritten notes** तक पहुँचना। + +एक ही, स्व-निहित स्क्रिप्ट से आप मीटिंग के धुंधले फोटो से साफ़, सर्चेबल टेक्स्ट तक पहुँच सकते हैं। आगे, आउटपुट को नेचुरल‑लैंग्वेज पाइपलाइन में फीड करने, सर्चेबल इंडेक्स में स्टोर करने, या वॉइस‑ओवर जेनरेशन के लिए ट्रांसक्रिप्शन सर्विस में वापस भेजने पर विचार करें। + +### आगे क्या करें? + +- **Batch processing:** स्क्रिप्ट को लूप में रैप करके स्कैन की फ़ोल्डर को हैंडल करें। +- **Confidence filtering:** कम‑क्वालिटी रीड्स को हटाने के लिए `result.confidence` का उपयोग करें। +- **Alternative libraries:** यदि `ocr` पूरी तरह फिट नहीं बैठता, तो `pytesseract` को `--psm 13` के साथ हस्तलिखित मोड के लिए एक्सप्लोर करें। +- **UI integration:** Flask या FastAPI के साथ मिलाकर वेब‑आधारित अपलोड सर्विस बनाएं। + +क्या आपके पास किसी विशेष **image format** के बारे में सवाल है या मॉडल ट्यून करने में मदद चाहिए? नीचे कमेंट करें, और कोडिंग का आनंद लें! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/hongkong/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..23bf85ffd --- /dev/null +++ b/ocr/hongkong/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,187 @@ +--- +category: general +date: 2026-04-26 +description: 學習如何下載 HuggingFace 模型(Python)並使用 Python 從圖像中提取文字,同時使用 Aspose OCR Cloud + 提升 OCR 準確度。 +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: zh-hant +og_description: 下載 HuggingFace Python 模型,提升你的 OCR 流程。遵循本指南,使用 Python 從圖像中提取文字,並提升 + OCR 準確度。 +og_title: 下載 HuggingFace 模型 Python – 完整 OCR 增強教學 +tags: +- OCR +- HuggingFace +- Python +- AI +title: 下載 huggingface 模型 Python – 一步一步 OCR 加速指南 +url: /zh-hant/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 下載 huggingface model python – 完整 OCR 增強教學 + +有沒有試過 **download HuggingFace model python**,卻感到有點迷惘?你並不是唯一遇到這種情況的人。在許多專案中,最大的瓶頸往往是把合適的模型下載到本機,然後讓 OCR 結果真正可用。 + +在本教學中,我們將手把手示範如何 **download HuggingFace model python**、使用 **extract text from image python** 從圖片中擷取文字,並透過 Aspose 的 AI 後處理器 **improve OCR accuracy python**。完成後,你將擁有一支可直接執行的腳本,能將雜訊多的發票影像轉換成乾淨、可讀的文字——沒有魔法,只有清晰步驟。 + +## 需要的環境 + +- Python 3.9+(程式碼在 3.11 亦可執行) +- 一次性模型下載所需的網際網路連線 +- `asposeocrcloud` 套件(`pip install asposeocrcloud`) +- 一張範例圖片(例如 `sample_invoice.png`),放在你自行管理的資料夾中 + +就這樣——不需要大型框架,也不需要 GPU 專屬驅動,除非你想加速。 + +現在,讓我們深入實作細節。 + +![下載 huggingface model python 工作流程](image.png "下載 huggingface model python 圖示") + +## 步驟 1:設定 OCR 引擎並選擇語言 *(這裡我們開始 **extract text from image python**。)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**為何重要:** +OCR 引擎是第一道防線;選擇正確的語言套件能立即降低字元辨識錯誤,這是 **improve OCR accuracy python** 的核心部分。 + +## 步驟 2:設定 AsposeAI 模型 – 從 HuggingFace 下載 *(在此我們實際執行 **download HuggingFace model python**。)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**背後發生了什麼?** +當 `allow_auto_download` 為 true 時,SDK 會向 HuggingFace 請求,取得 `Qwen2.5‑3B‑Instruct‑GGUF` 模型,並存放於你指定的資料夾。這正是 **download huggingface model python** 的核心——SDK 負責繁重的下載工作,你不必自行撰寫 `git clone` 或 `wget` 指令。 + +*小技巧:* 將 `directory_model_path` 放在 SSD 上以加快載入速度;即使是 `int8` 形式,模型大小仍約 3 GB。 + +## 步驟 3:將 AI 引擎附加至 OCR 引擎 *(將兩者結合以便 **improve OCR accuracy python**。)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**為何要綁定?** +OCR 引擎會輸出原始文字,可能包含拼寫錯誤、斷行或標點不正確。AI 引擎則充當智慧編輯器,清理這些問題——正是 **improve OCR accuracy python** 所需要的。 + +## 步驟 4:對圖片執行 OCR *(我們最終 **extract text from image python** 的時刻。)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` 現在包含一個 `text` 屬性,內含引擎辨識到的原始字元。實際使用時你會發現一些小問題——例如「Invoice」被辨識成「Inv0ice」或句子中間出現斷行。 + +## 步驟 5:使用 AI 後處理器清理 *(此步驟直接 **improve OCR accuracy python**。)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +AI 模型會重新寫入文字,套用語言感知的修正。因為我們使用的是從 HuggingFace 取得的指令微調模型,輸出通常流暢且可直接供下游處理使用。 + +## 步驟 6:顯示前後對比 *(快速檢查我們的 **extract text from image python** 與 **improve OCR accuracy python** 效果如何。)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### 預期輸出 + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +請注意 AI 將「Inv0ice」修正為「Invoice」並平滑了多餘的斷行。這就是使用已下載的 HuggingFace 模型 **improve OCR accuracy python** 的實際成效。 + +## 常見問題 (FAQ) + +### 執行模型需要 GPU 嗎? + +不需要。`gpu_layers=20` 設定會在偵測到相容的 GPU 時使用最多 20 個 GPU 層,若無則回退至 CPU。在現代筆記型電腦上,CPU 仍能以每秒數百個 token 的速度處理,足以應付偶爾的發票解析需求。 + +### 若模型下載失敗該怎麼辦? + +請確認你的環境能連線至 `https://huggingface.co`。若身處公司代理網路,請設定 `HTTP_PROXY` 與 `HTTPS_PROXY` 環境變數。SDK 會自動重試,你也可以手動執行 `git lfs pull` 將資料庫拉到 `directory_model_path`。 + +### 可以換成較小的模型嗎? + +當然可以。只要將 `hugging_face_repo_id` 換成其他 repo(例如 `TinyLlama/TinyLlama-1.1B-Chat-v0.1`),並相應調整 `hugging_face_quantization`。較小的模型下載更快、佔用記憶體更少,但校正品質可能稍有下降。 + +### 這對我在其他領域 **extract text from image python** 有何幫助? + +相同的流程同樣適用於收據、護照或手寫筆記。唯一需要調整的是語言套件(如 `ocr.Language.FRENCH` 等)以及可能的領域特化模型(可從 HuggingFace 取得)。 + +## 加分項:自動化多檔案處理 + +如果你有一個資料夾內放滿圖片,只需將 OCR 呼叫包在簡單的迴圈中: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +這個小小的加法讓你 **download huggingface model python** 只執行一次,之後即可批次處理數十個檔案——非常適合擴展文件自動化流程。 + +## 結論 + +我們剛剛完整示範了一個端對端的範例,說明如何 **download HuggingFace model python**、**extract text from image python**,以及使用 Aspose OCR Cloud 與 AI 後處理器 **improve OCR accuracy python**。腳本已可直接執行,概念已說明清楚,且你已看到前後對照的成果,證明它可行。 + +接下來可以嘗試換成不同的 HuggingFace 模型、實驗其他語言套件,或將清理過的文字輸入下游的 NLP 流程(例如發票項目實體抽取)。只要有想法,基礎已經打好。 + +有任何問題或遇到仍讓 OCR 卡住的難題圖片嗎?在下方留言,我們一起排除。祝編程愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/hongkong/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..009b236d6 --- /dev/null +++ b/ocr/hongkong/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,235 @@ +--- +category: general +date: 2026-04-26 +description: 使用 Aspose OCR Python 快速下載 OCR 模型。了解如何設定模型目錄、配置模型路徑,以及如何在幾行程式碼內下載模型。 +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: zh-hant +og_description: 使用 Aspose OCR Python 在數秒內下載 OCR 模型。本指南說明如何設定模型目錄、配置模型路徑,以及如何安全地下載模型。 +og_title: 下載 OCR 模型 – 完整 Aspose OCR Python 教學 +tags: +- OCR +- Python +- Aspose +title: 使用 Aspose OCR Python 下載 OCR 模型 – 步驟指南 +url: /zh-hant/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 下載 OCR 模型 – 完整 Aspose OCR Python 教程 + +有沒有想過如何在 Python 中使用 Aspose OCR **download ocr model**,而不必在大量文件中搜尋?你並不是唯一有此疑問的人。許多開發者在模型未本地存在且 SDK 拋出難以理解的錯誤時,會卡住。好消息是?只需幾行程式碼,即可在數分鐘內讓模型就緒。 + +在本教程中,我們將逐步說明您需要了解的所有內容:從匯入正確的類別、**set model directory**、實際**how to download model**,最後驗證路徑。完成後,您將能夠只用一次函式呼叫對任何影像執行 OCR,並了解可保持專案整潔的**configure model path**選項。沒有多餘說明,僅提供給 **aspose ocr python** 使用者的實用、可執行範例。 + +## 您將學習的內容 + +- 正確匯入 Aspose OCR Cloud 類別的方法。 +- 自動**download ocr model**的完整步驟。 +- 用於可重現建置的**set model directory**與**configure model path**方式。 +- 如何驗證模型是否已初始化以及它在磁碟上的位置。 +- 常見陷阱(權限、目錄遺失)與快速解決方案。 + +### 先決條件 + +- 已在機器上安裝 Python 3.8+。 +- `asposeocrcloud` 套件(`pip install asposeocrcloud`)。 +- 具有寫入權限的資料夾,用於存放模型(例如 `C:\models` 或 `~/ocr_models`)。 + +--- + +## 步驟 1:匯入 Aspose OCR Cloud 類別 + +您首先需要正確的匯入語句,這會把管理模型配置與 OCR 操作的類別載入。 + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Why this matters:* `AsposeAI` 是執行 OCR 的引擎,而 `AsposeAIModelConfig` 告訴引擎 **where** 要尋找模型以及 **whether** 要自動取得模型。跳過此步驟或匯入錯誤的模組會在下載之前就拋出 `ModuleNotFoundError`。 + +## 步驟 2:定義模型配置(設定模型目錄與配置模型路徑) + +現在告訴 Aspose 模型檔案要放在哪裡。這裡就是您 **set model directory** 與 **configure model path** 的地方。 + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Tips & Gotchas** + +- **Absolute paths** 可避免腳本在不同工作目錄下執行時產生混淆。 +- 在 Linux/macOS 上您可能會使用 `"/home/you/ocr_models"`;在 Windows 上,請在字串前加上 `r` 以讓反斜線被當作字面值處理。 +- 設定 `allow_auto_download="true"` 是 **how to download model** 的關鍵,無需額外程式碼。 + +## 步驟 3:使用配置建立 AsposeAI 實例 + +配置完成後,實例化 OCR 引擎。 + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Why this matters:* `ocr_ai` 物件現在持有我們剛剛定義的配置。如果模型不存在,下一次呼叫會自動觸發下載——這就是 **how to download model** 的核心,完全免手動操作。 + +## 步驟 4:觸發模型下載(如有需要) + +在執行 OCR 之前,必須確保模型已實際寫入磁碟。`is_initialized()` 方法同時檢查並強制初始化。 + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**What happens under the hood?** + +- 第一次呼叫 `is_initialized()` 會回傳 `False`,因為模型資料夾是空的。 +- `print` 會告知使用者下載即將開始。 +- 第二次呼叫會強制 Aspose 從先前指定的 Hugging Face 倉庫取得模型。 +- 下載完成後,後續檢查皆會回傳 `True`。 + +**Edge case:** 若您的網路阻擋 Hugging Face,會拋出例外。此時請手動下載模型 zip,解壓至 `directory_model_path`,再重新執行腳本。 + +## 步驟 5:報告模型目前所在的本機路徑 + +下載結束後,您可能想知道檔案落在哪裡。這對除錯與設定 CI 流程都很有幫助。 + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Typical output looks like: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +現在您已成功 **download ocr model**、設定目錄,並確認路徑。 + +## 視覺概覽 + +以下是一張簡易圖示,說明從配置到可直接使用的模型的流程。 + +![download ocr model flow diagram showing configuration, automatic download, and local path](/images/download-ocr-model-flow.png) + +*Alt text includes the primary keyword for SEO.* + +## 常見變化與處理方式 + +### 1. 使用不同的模型倉庫 + +如果需要的模型不是 `openai/gpt2`,只要替換 `hugging_face_repo_id` 的值即可: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +請確保該倉庫為公開,或已在環境變數中設定必要的 token。 + +### 2. 停用自動下載 + +有時您想自行控制下載(例如在空氣隔離環境)。將 `allow_auto_download` 設為 `"false"`,並在初始化前自行執行下載腳本: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. 執行時變更模型目錄 + +您可以在不重新建立 `AsposeAI` 物件的情況下重新設定路徑: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +## 生產環境的專業提示 + +- **Cache the model**:若多個服務共用同一模型,請將目錄放在共享網路磁碟,以避免重複下載。 +- **Version pinning**:Hugging Face 倉庫可能會更新。若要鎖定特定版本,請在 repo ID 後加上 `@v1.0.0`(例如 `"openai/gpt2@v1.0.0"`)。 +- **Permissions**:確保執行腳本的使用者對 `directory_model_path` 具有讀寫權限。Linux 上通常只需 `chmod 755`。 +- **Logging**:將簡單的 `print` 替換為 Python 的 `logging` 模組,以提升大型應用的可觀測性。 + +## 完整可執行範例(可直接複製貼上) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Expected output** (first run will download, subsequent runs will skip download): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +再次執行腳本;您只會看到路徑那一行,因為模型已被快取。 + +## 結論 + +我們剛剛完整說明了使用 Aspose OCR Python **download ocr model** 的流程,展示了如何 **set model directory**,並解釋了 **configure model path** 的細節。只要幾行程式碼,即可自動化下載、避免手動步驟,並保持 OCR 流程可重現。 + +接下來,您可能想探索實際的 OCR 呼叫(`ocr_ai.recognize_image(...)`)或嘗試不同的 Hugging Face 模型以提升準確度。無論哪種情況,您在此建立的基礎——清晰的配置、自動下載與路徑驗證——都會讓未來的整合變得輕而易舉。 + +有關邊緣案例的問題,或想分享您在雲端部署時如何調整模型目錄的經驗嗎?歡迎在下方留言,祝編程愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/hongkong/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..d242e76ae --- /dev/null +++ b/ocr/hongkong/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-04-26 +description: 如何對 OCR 結果進行後處理並提取帶坐標的文字。學習使用結構化輸出和 AI 校正的逐步解決方案。 +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: zh-hant +og_description: 如何後處理 OCR 結果並提取帶座標的文字。請跟隨本完整教學,獲得可靠的工作流程。 +og_title: 如何進行 OCR 後處理 – 完整指南 +tags: +- OCR +- Python +- AI +- Text Extraction +title: 如何對 OCR 進行後處理 — 使用 Python 提取帶座標的文字 +url: /zh-hant/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何後處理 OCR – 在 Python 中提取帶座標的文字 + +有沒有曾經需要 **如何後處理 OCR** 結果,因為原始輸出雜訊太多或對齊不正確?你並不是唯一遇到這種情況的人。在許多實際專案中——發票掃描、收據數位化,甚至增強 AR 體驗——OCR 引擎會給你原始文字,但你仍需清理它們並追蹤每個字在頁面上的位置。這時結合結構化輸出模式與 AI 驅動的後處理器就能大顯身手。 + +在本教學中,我們將逐步說明一個完整且可執行的 Python 流程,**從影像中提取帶座標的文字**,執行 AI 基礎的校正步驟,並列印每個字以及其 (x, y) 位置。沒有缺少的匯入,也沒有模糊的「請參考文件」捷徑——只是一個可直接放入你專案的獨立解決方案。 + +> **小技巧:** 如果你使用的是其他 OCR 函式庫,請尋找「structured」或「layout」模式;概念保持不變。 + +--- + +## 前置條件 + +在深入之前,請確保你已具備以下條件: + +| 需求 | 為何重要 | +|-------------|----------------| +| Python 3.9+ | 現代語法與型別提示 | +| `ocr` library that supports `OutputMode.STRUCTURED` (e.g., a fictional `myocr`) | 用於取得邊界框資料 | +| An AI post‑processing module (could be OpenAI, HuggingFace, or a custom model) | 提升 OCR 後的準確度 | +| An image file (`input.png`) in your working directory | 我們將讀取的來源 | + +如果上述項目對你來說陌生,只需使用 `pip install myocr ai‑postproc` 安裝佔位套件。以下程式碼也包含備用存根,讓你在沒有實際函式庫的情況下測試流程。 + +## 步驟 1:為 OCR 引擎啟用結構化輸出模式 + +我們首先要告訴 OCR 引擎提供的不僅是純文字。結構化輸出會回傳每個字以及其邊界框與信心分數,這對於之後的 **提取帶座標的文字** 至關重要。 + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*為何重要:* 若未使用結構化模式,你只能得到一長串文字,且會失去在影像上疊加文字或供下游版面分析所需的空間資訊。 + +## 步驟 2:辨識影像並擷取文字、框框與信心分數 + +現在我們將影像送入引擎。結果是一個物件,內含一系列字物件,每個字物件提供 `text`、`x`、`y`、`width`、`height` 與 `confidence`。 + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*邊緣情況:* 若影像為空或無法讀取,`structured_result.words` 會是空列表。建議先檢查並妥善處理此情況。 + +## 步驟 3:在保留位置的同時執行 AI 基礎的後處理 + +即使是最佳的 OCR 引擎也會出錯——例如「O」與「0」混淆或缺少變音符號。針對特定領域文字訓練的 AI 模型能校正這些錯誤。關鍵是,我們保留原始座標,使空間版面保持完整。 + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*為何保留座標:* 許多下游任務(例如 PDF 產生、AR 標註)依賴精確的放置。AI 僅修改 `text` 欄位,`x`、`y`、`width`、`height` 保持不變。 + +## 步驟 4:遍歷校正後的文字並顯示其座標 + +最後,我們遍歷校正後的文字,將每個字與其左上角 `(x, y)` 一起印出。這即達成 **提取帶座標的文字** 目標。 + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**預期輸出(範例):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +每一行顯示校正後的文字以及其在原始影像上的精確位置。 + +## 完整可執行範例 + +以下是一個將所有步驟串接的單一腳本。你可以直接複製貼上,依實際使用的函式庫調整匯入語句,然後直接執行。 + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**執行腳本** + +```bash +python ocr_postprocess_demo.py +``` + +若已安裝真實函式庫,腳本會處理你的 `input.png`。否則,存根實作讓你在不需任何外部依賴的情況下看到預期的流程與輸出。 + +## 常見問題 (FAQ) + +| 問題 | 答案 | +|----------|--------| +| *這能在 Tesseract 上使用嗎?* | Tesseract 本身不直接提供結構化模式,但像 `pytesseract.image_to_data` 這樣的封裝會回傳邊界框,你可以將其餵入相同的 AI 後處理器。 | +| *如果我需要右下角而不是左上角怎麼辦?* | 每個字物件也提供 `width` 與 `height`。計算 `x2 = x + width` 與 `y2 = y + height` 即可取得相對的角落。 | +| *我可以批次處理多張影像嗎?* | 當然可以。將步驟包在 `for image_path in Path("folder").glob("*.png"):` 迴圈中,並為每個檔案收集結果。 | +| *我要如何選擇校正用的 AI 模型?* | 對於一般文字,可使用在 OCR 錯誤上微調的輕量 GPT‑2。若是特定領域資料(例如醫療處方),則可在噪聲‑乾淨配對資料上訓練序列對序列模型。 | +| *AI 校正後信心分數仍有用嗎?* | 仍可保留原始信心分數以供除錯,但若模型支援,AI 也可能輸出自己的信心分數。 | + +## 邊緣情況與最佳實踐 + +1. **空的或損毀的影像** – 在繼續之前務必確認 `structured_result.words` 非空。 +2. **非拉丁文字** – 確保 OCR 引擎已為目標語言設定;AI 後處理器也必須在相同文字上訓練。 +3. **效能** – AI 校正可能成本高。若會重複使用同一影像,請快取結果,或以非同步方式執行 AI 步驟。 +4. **座標系統** – OCR 函式庫可能使用不同的原點(左上或左下)。在 PDF 或畫布上疊加時請相應調整。 + +## 結論 + +現在你已掌握一套完整、可靠的 **如何後處理 OCR** 與 **提取帶座標的文字** 的流程。透過啟用結構化輸出、將結果送入 AI 校正層,並保留原始邊界框,你可以將雜訊多的 OCR 掃描轉換為乾淨且具空間感的文字,供 PDF 產生、資料輸入自動化或擴增實境標註等下游任務使用。 + +準備好進一步了嗎?試著將存根 AI 換成 OpenAI `gpt‑4o‑mini` 呼叫,或將此流程整合至 FastAPI 中。 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/hongkong/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..383cdcb51 --- /dev/null +++ b/ocr/hongkong/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-04-26 +description: 如何使用 Python 快速辨識圖像。學習圖像辨識流程、批次處理,並使用 AI 自動化圖像辨識。 +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: zh-hant +og_description: 如何使用 Python 快速辨識圖像。本指南將逐步說明圖像辨識流程、批次處理以及使用 AI 的自動化。 +og_title: 如何辨識圖像 – 自動化圖像辨識流程 +tags: +- image-processing +- python +- ai +title: 如何辨識圖像 – 自動化圖像辨識流程 +url: /zh-hant/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何辨識影像 – 自動化影像辨識流程 + +有沒有想過 **如何辨識影像** 而不需要寫上千行程式碼?你並不孤單——許多開發者在第一次需要處理數十或數百張圖片時都會碰到同樣的障礙。好消息是?只要幾個簡潔的步驟,你就能建立一個完整的影像辨識流程,能自動批次處理、執行並清理。 + +在本教學中,我們將逐步示範一個完整且可執行的範例,說明 **如何批次處理影像**、將每張影像送入 AI 引擎、後處理結果,最後釋放資源。完成後,你將擁有一個可直接放入任何專案的獨立腳本,無論是建立照片標記工具、品質檢測系統,或是研究資料集產生器,都能即時使用。 + +## 你將學會 + +- **如何辨識影像** 使用模擬 AI 引擎(此模式與 TensorFlow、PyTorch 或雲端 API 等真實服務相同)。 +- 如何建立一個能有效處理批次的 **影像辨識流程**。 +- 最佳的 **自動化影像辨識** 方法,讓你不必每次手動遍歷檔案。 +- 擴展流程與安全釋放資源的技巧。 + +> **前置條件:** Python 3.8+、對函式與迴圈有基本了解,以及想要處理的少量影像檔案(或路徑)。核心範例不需要外部函式庫,但我們會說明可以在哪裡接入真實的 AI SDK。 + +![批次處理流程中如何辨識影像的示意圖](pipeline.png "如何辨識影像示意圖") + +## 步驟 1:批次處理你的影像 – 如何有效批次影像 + +在 AI 開始任何繁重運算之前,你需要先準備好一組要送入的影像。把它想像成你的購物清單;引擎之後會逐一挑選清單上的項目。 + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**為什麼要批次?** +批次處理能減少你必須撰寫的樣板程式碼,且日後若要加入平行運算也相當簡單。若你需要處理 10 000 張照片,只要更改 `image_batch` 的來源——其餘流程皆不需變動。 + +## 步驟 2:執行影像辨識流程(使用 AI 辨識影像) + +現在把批次資料接入實際的辨識器。真實情境下可能會呼叫 `torchvision.models` 或雲端端點;此處我們以模擬行為示範,讓教學保持自足。 + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**說明:** +- `engine.recognize_image` 是 **影像辨識流程** 的核心;它可能是呼叫深度學習模型或 REST API。 +- `postprocessor.run` 示範了 **自動化影像辨識**,將原始預測正規化為可儲存或串流的乾淨字典。 +- 我們將每個 `corrected` 字典收集到 `recognized_results` 中,使後續步驟(例如資料庫插入)變得簡單。 + +## 步驟 3:後處理與儲存 – 自動化影像辨識結果 + +取得整潔的預測清單後,通常會想將結果持久化。以下範例寫入 CSV 檔案;你也可以自行改成寫入資料庫或訊息佇列。 + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**為什麼使用 CSV?** +CSV 具通用可讀性——Excel、pandas,甚至純文字編輯器都能開啟。若日後需要 **自動化影像辨識** 大規模執行,只要把寫入區塊換成批次寫入你的資料湖即可。 + +## 步驟 4:清理 – 安全釋放 AI 資源 + +許多 AI SDK 會分配 GPU 記憶體或產生工作執行緒。忘記釋放會導致記憶體洩漏與程式崩潰。即使我們的模擬物件不需要此步驟,我們仍示範正確的模式。 + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +執行腳本時會印出友善的確認訊息,讓你知道流程已順利結束。 + +## 完整可執行腳本 + +把所有部份組合起來,以下即為完整、可直接複製貼上的程式: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### 預期輸出 + +執行腳本(假設三個佔位路徑皆存在)時,會看到類似以下的輸出: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +產生的 `recognition_results.csv` 內容如下: + +| 圖片 | 標籤 | 信心度 | +|---------------------|-------|------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## 結論 + +現在你已掌握一個完整的 **如何辨識影像** Python 範例,具備 **影像辨識流程**、批次處理與自動化後處理的全部要素。此模式具可擴充性:將模擬類別換成真實模型,提供更大的 `image_batch`,即可得到可投入生產的解決方案。 + +想更進一步嗎?試試以下建議: + +- 將 `MockEngine` 換成 TensorFlow 或 PyTorch 模型以取得真實預測。 +- 使用 `concurrent.futures.ThreadPoolExecutor` 平行化迴圈,以加速大型批次。 +- 將 CSV 寫入器掛接至雲端儲存桶,以 **自動化影像辨識** 在分散式工作者之間。 + +盡情實驗、敢於破壞再修復——這才是真正精通影像辨識流程的關鍵。若遇到任何問題或有改進想法,歡迎在下方留言。祝編程愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/hongkong/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..ca03ba9c8 --- /dev/null +++ b/ocr/hongkong/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,249 @@ +--- +category: general +date: 2026-04-26 +description: 使用 AsposeAI OCR 後處理快速遮蔽信用卡號碼。於一步一步的教學中學習 PCI 合規、正則表達式遮蔽與資料淨化。 +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: zh-hant +og_description: 使用 AsposeAI 在 OCR 結果中遮蔽信用卡號碼。本教學涵蓋 PCI 合規、正則表達式遮蔽及資料淨化。 +og_title: 遮蔽信用卡號碼 – 完整 Python OCR 後處理指南 +tags: +- OCR +- Python +- security +title: 在 OCR 輸出中遮蔽信用卡號碼 – 完整 Python 指南 +url: /zh-hant/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 遮蔽信用卡號碼 – 完整 Python 指南 + +是否曾需要在直接來自 OCR 引擎的文字中**遮蔽信用卡號碼**?你並非唯一遇到此情況的人。在受規管的行業中,暴露完整的 PAN(Primary Account Number)可能會讓你在 PCI 合規審核員面前陷入麻煩。好消息是?只需幾行 Python 以及 AsposeAI 的後處理掛鉤,即可自動隱藏中間八位數,確保安全。 + +在本教學中,我們將逐步示範一個真實情境:對收據影像執行 OCR,然後套用自訂的 **OCR 後處理** 函式以清理任何 PCI 資料。完成後,你將擁有一段可重複使用的程式碼片段,能直接嵌入任何 AsposeAI 工作流程,並提供處理邊緣案例與擴展解決方案的實用技巧。 + +## 你將學到 + +- 如何在 **AsposeAI** 中註冊自訂的後處理器。 +- 為何 **正則表達式遮蔽** 方法既快速又可靠。 +- **PCI 合規** 與資料清理的基礎知識。 +- 如何擴充模式以支援多種卡片格式或國際卡號。 +- 預期的輸出以及如何驗證遮蔽是否成功。 + +> **先決條件** – 你應該具備可運作的 Python 3 環境,已安裝 Aspose.AI for OCR 套件 (`pip install aspose-ocr`),以及包含信用卡號碼的範例影像(例如 `receipt.png`)。不需要其他外部服務。 + +--- + +## 步驟 1:定義遮蔽信用卡號碼的後處理器 + +解決方案的核心是一個小函式,接收 OCR 結果,執行 **正則表達式遮蔽** 程序,並回傳已清理的文字。 + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**為什麼這樣有效:** +- 正則表達式 `(\d{4})\d{8}(\d{4})` 完全匹配 16 位連續數字,這是 Visa、MasterCard 等常見的格式。 +- 透過捕獲前四位與後四位 (`\1` 與 `\2`),我們保留足夠的除錯資訊,同時遵守 **PCI 合規** 規則,禁止儲存完整的 PAN。 +- 置換 `\1****\2` 隱藏敏感的中間八位,使 `1234567812345678` 變為 `1234****5678`。 + +> **專業提示:** 若需支援 15 位數的美國運通卡號,可加入第二個模式,例如 `r'(\d{4})\d{6}(\d{5})'`,並依序執行兩次取代。 + +## 步驟 2:初始化 AsposeAI 引擎 + +在我們能掛接後處理器之前,需要先建立 OCR 引擎的實例。AsposeAI 包含 OCR 模型以及供自訂處理使用的簡易 API。 + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**為什麼在此初始化?** +- 只建立一次 `AsposeAI` 物件,並在多張影像間重複使用,可減少開銷。引擎亦會快取語言模型,提升後續呼叫速度——在批次掃描收據時相當方便。 + +## 步驟 3:註冊自訂遮蔽函式 + +AsposeAI 提供 `set_post_processor` 方法,允許你插入任何可呼叫的函式。我們將 `mask_pci` 函式與可選的設定字典(目前為空)一起傳入。 + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**背後發生了什麼?** +稍後呼叫 `run_postprocessor` 時,AsposeAI 會將原始 OCR 結果傳給 `mask_pci`。該函式會收到一個輕量物件 (`data`),其中包含辨識出的文字,而你則回傳一個新字串。此設計讓核心 OCR 保持不變,同時在單一位置強制執行 **資料清理** 政策。 + +## 步驟 4:對收據影像執行 OCR + +既然引擎已知道如何清理輸出,我們就將影像餵給它。為了本教學的方便,我們假設你已擁有一個已配置語言與解析度設定的 `engine` 物件。 + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**提示:** 若尚未有預先配置的物件,可使用以下方式建立: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +`recognize_image` 呼叫會回傳一個物件,其 `text` 屬性包含原始、未遮蔽的字串。 + +## 步驟 5:套用已註冊的後處理器 + +取得原始 OCR 資料後,我們將其交給 AI 實例。引擎會自動執行先前註冊的 `mask_pci` 函式。 + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**為什麼使用 `run_postprocessor` 而非手動呼叫函式?** +這樣可保持工作流程的一致性,特別是當你有多個後處理器(例如拼寫檢查、語言偵測)時。AsposeAI 會依註冊順序排隊執行,確保輸出具決定性。 + +## 步驟 6:驗證已清理的輸出 + +最後,印出已清理的文字,確認所有信用卡號碼已正確遮蔽。 + +```python +print(final_result.text) +``` + +**預期輸出**(節錄): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +若收據未包含卡號,文字將保持不變——無需遮蔽,也無需擔心。 + +## 處理邊緣案例與常見變形 + +### 同一文件中多筆卡號 +若收據包含多於一筆 PAN(例如會員卡加付款卡),正則表達式會全域執行,自動遮蔽所有匹配項目。無需額外程式碼。 + +### 非標準格式 +有時 OCR 會插入空格或連字號(`1234 5678 1234 5678` 或 `1234-5678-1234-5678`)。可擴充模式以忽略這些字元: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +新增的 `[ -]?` 允許在數字區塊之間出現可選的空格或連字號。 + +### 國際卡片 +對於某些地區使用的 19 位 PAN,可擴大模式: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +只要記住 **PCI 合規** 仍要求遮蔽中間數字,無論長度為何。 + +### 記錄遮蔽值(可選) +若需要稽核追蹤,可透過 `custom_settings` 傳遞旗標並調整函式: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +然後這樣註冊: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +## 完整可執行範例(可直接複製貼上) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +在包含 `4111111111111111` 的收據上執行此腳本,將產生: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +這就是完整的流程——從原始 OCR 到 **資料清理**——只需幾行簡潔的 Python 程式碼即可完成。 + +## 結論 + +我們剛剛示範了如何使用 AsposeAI 的後處理掛鉤、簡潔的正則表達式程序,以及一系列 **PCI 合規** 的最佳實踐技巧,來 **遮蔽 OCR 結果中的信用卡號碼**。此解決方案完全獨立,適用於任何 OCR 引擎能讀取的影像,且可擴充以支援更複雜的卡片格式或記錄需求。 + +準備好下一步了嗎?可將此遮蔽與 **資料庫插入** 程式結合,只儲存最後四位作為參考,或整合 **批次處理器**,於夜間掃描整個收據資料夾。你亦可探索其他 **OCR 後處理** 任務,如地址標準化或語言偵測——皆遵循我們此處使用的相同模式。 + +對於邊緣案例、效能,或如何將程式碼套用至其他 OCR 函式庫有任何疑問嗎?在下方留言,我們一起討論。祝程式開發愉快,保持安全! + +![說明在 OCR 流程中遮蔽信用卡號碼運作方式的圖示](https://example.com/images/ocr-mask-flow.png "OCR 後處理遮蔽流程圖") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/hongkong/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..d3523fb6b --- /dev/null +++ b/ocr/hongkong/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-04-26 +description: 學習如何在 Python 中測量推論時間、從 Hugging Face 載入 GGUF 模型,並優化 GPU 使用以獲得更快的結果。 +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: zh-hant +og_description: 透過載入 Hugging Face 的 GGUF 模型並調校 GPU 層,以在 Python 中測量推論時間,達致最佳效能。 +og_title: 測量推理時間 – 載入 GGUF 模型並優化 GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: 測量推論時間 – 載入 GGUF 模型並優化 GPU +url: /zh-hant/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 測量推論時間 – 載入 GGUF 模型與最佳化 GPU + +有沒有曾經想 **測量大型語言模型的推論時間**,卻不知道從哪裡開始?你並不孤單——許多開發者在第一次從 Hugging Face 下載 GGUF 檔案並嘗試在 CPU/GPU 混合環境下執行時,都會卡在同一個問題上。 + +在本指南中,我們將一步步說明 **如何載入 GGUF 模型**、為 Hugging Face 進行設定,並使用簡潔的 Python 程式碼 **測量推論時間**。同時,我們也會示範如何 **最佳化推論 GPU** 使用,讓你的執行速度盡可能快。內容沒有冗餘,直接給你可即時 copy‑paste 的端到端解決方案。 + +## 你將學到 + +- 如何使用 `AsposeAIModelConfig` **設定 HuggingFace 模型**。 +- 從 Hugging Face Hub **載入 GGUF 模型**(`fp16` 量化)的完整步驟。 +- 一個可重複使用的 **計時 Python 程式碼** 範本,用於推論呼叫。 +- 調整 `gpu_layers` 以 **最佳化推論 GPU** 的技巧。 +- 預期輸出以及如何驗證計時結果是否合理。 + +### 前置條件 + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.9+ | 現代語法與型別提示。 | +| `asposeai` 套件(或等效 SDK) | 提供 `AsposeAI` 與 `AsposeAIModelConfig`。 | +| 取得 Hugging Face repo `bartowski/Qwen2.5-3B-Instruct-GGUF` 的存取權 | 我們將載入的 GGUF 模型所在。 | +| 至少 8 GB VRAM 的 GPU(可選,但建議) | 讓 **最佳化推論 GPU** 步驟得以執行。 | + +如果尚未安裝 SDK,請執行: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![measure inference time diagram](https://example.com/measure-inference-time.png){alt="measure inference time diagram"} + +## 步驟 1:載入 GGUF 模型 – 設定 HuggingFace 模型 + +首先需要一個正確的設定物件,告訴 Aspose AI 從哪裡取得模型以及如何處理。這裡我們會 **載入 GGUF 模型** 並 **設定 huggingface model** 參數。 + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**為什麼重要:** +- `hugging_face_repo_id` 指向 Hub 上的確切 GGUF 檔案。 +- `fp16` 在降低記憶體頻寬的同時,保留大部分模型的精度。 +- `gpu_layers` 是調整 **最佳化推論 GPU** 效能的關鍵參數;將更多層放到 GPU 上通常會提升延遲表現,前提是有足夠的 VRAM。 + +## 步驟 2:建立 Aspose AI 實例 + +模型設定完成後,我們建立一個 `AsposeAI` 物件。這一步相當直接,但正是在此 SDK 會下載 GGUF 檔案(若未快取)並準備執行環境。 + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**小技巧:** 第一次執行會較慢,因為模型需要下載並為 GPU 編譯。之後的執行則會非常快速。 + +## 步驟 3:執行推論並 **測量推論時間** + +以下是本教學的核心:使用 `time.time()` 包住推論呼叫,以 **測量推論時間**。我們同時提供一段極小的 OCR 結果,讓範例保持自足。 + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**你應該會看到的結果:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +如果數值偏高,代表大部分層仍在 CPU 上執行。接下來的步驟將說明如何改善。 + +## 步驟 4:**最佳化推論 GPU** – 調整 `gpu_layers` + +預設的 `gpu_layers=40` 有時會過於激進(導致 OOM)或過於保守(性能未發揮)。以下是一個快速迴圈,幫助你找出最佳設定: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**原理說明:** +- 每次呼叫都會以不同的 GPU 配置重新建構執行環境,讓你即時觀察延遲的變化。 +- 這個迴圈同時示範了 **time python code** 的可重複使用方式,方便你套用到其他效能測試。 + +在 16 GB RTX 3080 上的典型輸出可能如下: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +從中挑選 `gpu_layers=40` 作為此硬體的最佳值。 + +## 完整範例 + +將上述所有步驟整合成一個腳本(`measure_inference.py`),即可直接執行: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +執行方式: + +```bash +python measure_inference.py +``` + +在配備不錯的 GPU 上,你應該會看到次秒級的延遲,證明已成功 **測量推論時間** 並 **最佳化推論 GPU**。 + +--- + +## 常見問題 (FAQs) + +**Q: 這能套用到其他量化格式嗎?** +A: 完全可以。只要在設定中將 `hugging_face_quantization="int8"`(或 `q4_0` 等)替換後重新執行基準測試。會有記憶體使用量降低與精度略微下降的權衡。 + +**Q: 如果沒有 GPU 該怎麼辦?** +A: 設定 `gpu_layers=0`。程式會完全回退到 CPU,仍然可以 **測量推論時間**,只是數值會較高。 + +**Q: 能只計時模型的前向傳播,而不包括後處理嗎?** +A: 可以。直接呼叫 `ai_engine.run_model(...)`(或等效方法),再以 `time.time()` 包住該呼叫即可。**time python code** 的模式保持不變。 + +--- + +## 結論 + +現在你已擁有一套完整、可直接 copy‑paste 的解決方案,能 **測量推論時間**、**載入 GGUF 模型**,以及微調 **最佳化推論 GPU** 設定。透過調整 `gpu_layers` 與量化方式,你可以把每一毫秒的效能都榨出來。 + +接下來,你可以考慮: + +- 將此計時邏輯整合到 CI pipeline,及時偵測效能回退。 +- 探索批次推論以進一步提升吞吐量。 +- 將模型與真實的 OCR 流程結合,取代本教學中的示範文字。 + +祝開發順利,願你的延遲數值永遠保持低位! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/hongkong/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..999d96b7c --- /dev/null +++ b/ocr/hongkong/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-04-26 +description: 使用 Python 的 OCR 引擎辨識手寫文字。學習如何從圖片提取文字、開啟手寫模式,快速閱讀手寫筆記。 +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: zh-hant +og_description: 使用 Python 識別手寫文字。本教學示範如何從圖像提取文字、開啟手寫模式,並使用簡易 OCR 引擎讀取手寫筆記。 +og_title: 在 Python 中識別手寫文字 – 完整 OCR 指南 +tags: +- OCR +- Python +- Handwriting Recognition +title: 在 Python 中辨識手寫文字 – OCR 引擎教學 +url: /zh-hant/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Python 中辨識手寫文字 – OCR 引擎教學 + +曾經需要 **辨識手寫文字**,卻卡在「從哪裡開始?」的問題上嗎?你並不孤單。無論是將會議筆記數位化,或是從掃描表單中抽取資料,取得可靠的 OCR 結果常常感覺像在追逐獨角獸。 + +好消息是:只要幾行 Python 程式碼,就能 **從影像中抽取文字**、**開啟手寫模式**,最後 **讀取手寫筆記**,不必再搜尋難以尋找的函式庫。本指南將一步步說明完整流程,從 **create OCR engine python** 的設定到在螢幕上印出結果。 + +## 你將學會 + +- 如何使用 `ocr` 套件 **create OCR engine python** 產生實例。 +- 哪個語言設定內建手寫支援。 +- 正確的 **turn on handwritten mode** 呼叫方式,讓引擎知道你在處理手寫文字。 +- 如何提供筆記的圖片並 **recognize handwritten text**。 +- 處理不同影像格式、除錯常見問題以及擴充解決方案的技巧。 + +不囉唆,也不會只說「看文件」——直接給你一段可執行的完整腳本,今天就能複製貼上測試。 + +## 前置條件 + +在開始之前,請確保你已具備: + +1. 安裝 Python 3.8 以上(程式碼使用 f‑strings)。 +2. 假想的 `ocr` 函式庫(`pip install ocr‑engine` – 請以實際使用的套件名稱取代)。 +3. 一張清晰的手寫筆記影像檔(支援 JPEG、PNG 或 TIFF)。 +4. 一點點好奇心——其他都在下方說明。 + +> **專業小技巧:** 若影像雜訊較多,可先用 Pillow 進行簡易前處理(例如 `Image.open(...).convert('L')`),再送入 OCR 引擎。這通常能提升辨識準確度。 + +## 如何使用 Python 辨識手寫文字 + +以下是完整腳本,會 **create OCR engine python** 物件、設定手寫模式,並印出擷取的字串。請將檔案另存為 `handwriting_ocr.py`,然後在終端機執行。 + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### 預期輸出 + +腳本順利執行時,會看到類似以下的結果: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +如果 OCR 引擎無法偵測到任何字元,`text` 欄位會是空字串。此時請再次檢查影像品質,或嘗試使用更高解析度的掃描。 + +## 步驟說明 + +### 步驟 1 – **create OCR engine python** 實例 + +`OcrEngine` 類別是入口點。把它想像成一本空白筆記本——在你指定語言與是否為手寫之前,它不會執行任何動作。 + +### 步驟 2 – 選擇支援手寫的語言 + +`ocr.Language.EXTENDED_LATIN` 不只是「英文」。它整合了一系列拉丁系文字,且關鍵是包含了以手寫樣本訓練的模型。若跳過此步驟,常會得到亂碼,因為引擎預設使用印刷文字模型。 + +### 步驟 3 – **turn on handwritten mode** + +呼叫 `enable_handwritten_mode(True)` 會切換內部旗標。引擎隨即改用針對真實筆記中不規則間距與筆畫寬度調校的神經網路。忘記這一行是常見錯誤,會讓引擎把你的筆跡當成雜訊。 + +### 步驟 4 – 輸入影像並 **recognize handwritten text** + +`recognize_image` 承擔主要工作:它會前處理位圖、將其送入手寫模型,最後回傳一個含有 `text` 屬性的物件。若需要品質指標,也可以檢查 `handwritten_result.confidence`。 + +### 步驟 5 – 印出結果並 **read handwritten notes** + +`print(handwritten_result.text)` 是驗證已成功 **extract text from image** 的最簡方式。實務上,你可能會把字串存入資料庫,或傳給其他服務使用。 + +## 處理邊緣案例與常見變化 + +| 情境 | 處理方式 | +|-----------|------------| +| **影像已旋轉** | 在呼叫 `recognize_image` 前,使用 Pillow 旋轉 (`Image.rotate(angle)`)。 | +| **對比度低** | 轉成灰階並套用自適應閾值 (`Image.point(lambda p: p > 128 and 255)`)。 | +| **多頁文件** | 迭代檔案路徑清單,將結果串接起來。 | +| **非拉丁文字** | 將 `EXTENDED_LATIN` 換成 `ocr.Language.CHINESE`(或其他適用語言),同時保留 `enable_handwritten_mode(True)`。 | +| **效能顧慮** | 在大量影像間重複使用同一個 `ocr_engine` 實例;每次重新初始化會增加開銷。 | + +### 記憶體使用的專業小技巧 + +若一次要批次處理數百張筆記,完成後呼叫 `ocr_engine.dispose()`。這會釋放 Python 包裝器可能佔用的原生資源。 + +## 快速視覺回顧 + +![recognize handwritten text example](https://example.com/handwritten-note.png "recognize handwritten text example") + +*上圖展示了一張典型的手寫筆記,腳本可以將其轉換為純文字。* + +## 完整可執行範例(單一檔案腳本) + +喜歡直接複製貼上的朋友,以下提供不含說明註解的完整程式碼: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +執行方式: + +```bash +python handwriting_ocr.py +``` + +執行後,你應該會在終端機看到 **recognize handwritten text** 的輸出結果。 + +## 結論 + +我們已完整說明如何在 Python 中 **recognize handwritten text**——從全新的 **create OCR engine python** 呼叫、選擇正確語言、**turn on handwritten mode**,最後 **extract text from image** 並 **read handwritten notes**。 + +只要一個自包含的腳本,就能把模糊的會議塗鴉照片轉換成乾淨、可搜尋的文字。接下來,你可以將輸出送入自然語言處理管線、存入可搜尋的索引,甚至回傳給語音合成服務產生旁白。 + +### 往後的發展方向 + +- **批次處理:** 把腳本包在迴圈中,處理整個資料夾的掃描檔。 +- **信心過濾:** 使用 `result.confidence` 丟棄低品質的辨識結果。 +- **其他函式庫:** 若 `ocr` 不完全符合需求,可嘗試 `pytesseract` 並搭配 `--psm 13` 以啟用手寫模式。 +- **UI 整合:** 結合 Flask 或 FastAPI,提供網頁上傳服務。 + +對特定影像格式有疑問或需要模型調校協助?歡迎在下方留言,祝編程愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/hungarian/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..c123d3bea --- /dev/null +++ b/ocr/hungarian/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-04-26 +description: Tanulja meg, hogyan töltheti le a HuggingFace modellt Pythonban, és hogyan + nyerhet ki szöveget képből Pythonban, miközben javítja az OCR pontosságát Pythonban + az Aspose OCR Cloud segítségével. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: hu +og_description: Töltsd le a HuggingFace modellt Pythonban, és növeld az OCR folyamatod + hatékonyságát. Kövesd ezt az útmutatót, hogy Pythonban képből szöveget nyerj ki, + és javítsd az OCR pontosságát Pythonban. +og_title: HuggingFace modell letöltése Python – Teljes OCR fejlesztési útmutató +tags: +- OCR +- HuggingFace +- Python +- AI +title: HuggingFace modell letöltése Pythonban – Lépésről‑lépésre OCR Boost útmutató +url: /hu/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – Teljes OCR Fejlesztési Bemutató + +Próbálta már **download HuggingFace model python**‑t letölteni, és kicsit elveszettnek érezte magát? Nem egyedül van ezzel. Sok projektben a legnagyobb szűk keresztmetszet a megfelelő modell gépre hozatala, majd az OCR‑eredmények valóban hasznosá tétele. + +Ebben az útmutatóban egy gyakorlati példán keresztül mutatjuk be, hogyan **download HuggingFace model python**, hogyan **extract text from image python**‑nal szöveget nyerünk ki egy képről, és hogyan **improve OCR accuracy python**‑t használunk az Aspose AI utófeldolgozójával. A végére egy kész‑futó szkriptet kap, amely egy zajos számla képet tiszta, olvasható szöveggé alakít – semmi varázslat, csak egyértelmű lépések. + +## Amire szüksége lesz + +- Python 3.9+ (a kód 3.11‑en is működik) +- Internetkapcsolat az egyszeri modellletöltéshez +- Az `asposeocrcloud` csomag (`pip install asposeocrcloud`) +- Egy minta kép (pl. `sample_invoice.png`) egy saját mappában + +Ennyi – nincs nehéz keretrendszer, nincs GPU‑specifikus driver, hacsak nem akarja felgyorsítani a folyamatot. + +Most merüljünk el a tényleges megvalósításban. + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## 1. lépés: Az OCR motor beállítása és nyelv kiválasztása +*(Itt kezdődik a **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Miért fontos:** +Az OCR motor az első védvonal; a megfelelő nyelvi csomag kiválasztása azonnal csökkenti a karakterfelismerési hibákat, ami a **improve OCR accuracy python** egyik alapja. + +## 2. lépés: Az AsposeAI modell konfigurálása – letöltés a HuggingFace‑ről +*(Itt valójában **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**Mi történik a háttérben?** +Amikor az `allow_auto_download` igaz, az SDK kapcsolatba lép a HuggingFace‑el, letölti a `Qwen2.5‑3B‑Instruct‑GGUF` modellt, és elhelyezi a megadott mappában. Ez a **download huggingface model python** magja – az SDK végzi a nehéz munkát, így nem kell saját `git clone` vagy `wget` parancsot írnia. + +*Pro tipp:* Helyezze a `directory_model_path`‑t SSD‑re a gyorsabb betöltés érdekében; a modell ~3 GB még `int8` formában is. + +## 3. lépés: Az AI motor csatolása az OCR motorhoz +*(Összekapcsoljuk a két elemet, hogy **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Miért kössük össze?** +Az OCR motor nyers szöveget ad, amely hibás betűket, törött sorokat vagy rossz írásjeleket tartalmazhat. Az AI motor egy intelligens szerkesztőként működik, ezeket a problémákat javítja – pontosan az, amire a **improve OCR accuracy python**‑hoz szükség van. + +## 4. lépés: OCR futtatása a képen +*(A pillanat, amikor végre **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +Az `ocr_result` most egy `text` attribútummal rendelkezik, amely a motor által látott nyers karaktereket tartalmazza. Gyakorlatban néhány hibát észlelhet – például az „Invoice” helyett „Inv0ice”, vagy egy sortörés egy mondat közepén. + +## 5. lépés: Tisztítás az AI utófeldolgozóval +*(Ez a lépés közvetlenül **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +Az AI modell átírja a szöveget, nyelv‑tudatos javításokat alkalmazva. Mivel egy instrukció‑finomhangolt modellt használtunk a HuggingFace‑ről, a kimenet általában folyékony és készen áll a további feldolgozásra. + +## 6. lépés: Az eredeti és a javított szöveg megjelenítése +*(Gyors ellenőrzés, hogy mennyire **extract text from image python**‑t és **improve OCR accuracy python**‑t sikerült elérni.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Várható kimenet + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Látható, hogy az AI kijavította a „Inv0ice” szót „Invoice”‑ra, és eltüntette a felesleges sortöréseket. Ez a **improve OCR accuracy python** konkrét eredménye egy letöltött HuggingFace modellel. + +## Gyakran Ismételt Kérdések (GYIK) + +### Szükségem van GPU‑ra a modell futtatásához? +Nem. Az `gpu_layers=20` beállítás azt mondja az SDK‑nak, hogy legfeljebb 20 GPU‑réteget használjon, ha kompatibilis GPU jelen van; egyébként CPU‑ra vált. Egy modern laptopon a CPU útvonal is képes néhány száz token per másodperc feldolgozására – tökéletes alkalmi számlafelismeréshez. + +### Mi van, ha a modell letöltése sikertelen? +Győződjön meg róla, hogy a környezete eléri a `https://huggingface.co` címet. Ha vállalati proxy mögött van, állítsa be a `HTTP_PROXY` és `HTTPS_PROXY` környezeti változókat. Az SDK automatikusan újrapróbálkozik, de manuálisan is futtathatja a `git lfs pull` parancsot a repo letöltéséhez a `directory_model_path`‑ba. + +### Lecserélhetem a modellt egy kisebbre? +Természetesen. Csak cserélje le a `hugging_face_repo_id`‑t egy másik repo‑ra (pl. `TinyLlama/TinyLlama-1.1B-Chat-v0.1`), és ennek megfelelően állítsa be a `hugging_face_quantization`‑t. A kisebb modellek gyorsabban letöltődnek és kevesebb RAM‑ot igényelnek, bár a javítási minőség kissé csökkenhet. + +### Hogyan segít ez a **extract text from image python** más területeken? +Ugyanez a csővezeték működik nyugták, útlevelek vagy kézzel írott jegyzetek esetén is. Egyetlen változtatás a nyelvi csomag (`ocr.Language.FRENCH`, stb.) és esetleg egy domain‑specifikus, HuggingFace‑ről származó finomhangolt modell. + +## Bónusz: Több fájl automatizálása + +Ha egy mappában sok kép van, csomagolja az OCR hívást egy egyszerű ciklusba: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +Ez a kis kiegészítés lehetővé teszi, hogy egyszer **download huggingface model python**, majd tucatnyi fájlt kötegelt módon dolgozzon fel – ideális a dokumentum‑automatizálási folyamat skálázásához. + +## Összegzés + +Lépésről‑lépésre végigjártunk egy teljes, vég‑végi példán, amely megmutatja, hogyan **download HuggingFace model python**, **extract text from image python**, és **improve OCR accuracy python** használatával az Aspose OCR Cloud és egy AI utófeldolgozó segítségével. A szkript készen áll a futtatásra, a koncepciók elmagyarázásra kerültek, és látta a before‑after kimenetet, így tudja, hogy működik. + +Mi a következő? Próbálja ki egy másik HuggingFace modellt, kísérletezzen más nyelvi csomagokkal, vagy adja át a megtisztított szöveget egy downstream NLP csővezetéknek (pl. entitás‑kivonás számlatételhez). A lehetőségek végtelenek, és az alap, amit most felépített, szilárd. + +Van kérdése vagy egy nehéz kép, ami még mindig megzavarja az OCR‑t? Hagyjon kommentet alább, és együtt megoldjuk. Boldog kódolást! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/hungarian/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..029af5547 --- /dev/null +++ b/ocr/hungarian/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-04-26 +description: Töltsd le gyorsan az OCR modellt az Aspose OCR Python segítségével. Tanuld + meg, hogyan állítsd be a modell könyvtárát, konfiguráld a modell útvonalát, és hogyan + töltsd le a modellt néhány sorban. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: hu +og_description: Tölts le OCR modellt másodpercek alatt az Aspose OCR Python segítségével. + Ez az útmutató bemutatja, hogyan állítsd be a modell könyvtárát, konfiguráld a modell + útvonalát, és hogyan töltsd le a modellt biztonságosan. +og_title: OCR modell letöltése – Teljes Aspose OCR Python útmutató +tags: +- OCR +- Python +- Aspose +title: OCR modell letöltése az Aspose OCR Python segítségével – Lépésről lépésre útmutató +url: /hu/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ocr modell letöltése – Teljes Aspose OCR Python útmutató + +Gondolkodtál már azon, hogyan **letöltsd az ocr modellt** az Aspose OCR segítségével Pythonban anélkül, hogy végtelen dokumentációt kellene átböngészni? Nem vagy egyedül. Sok fejlesztő akad el, amikor a modell helyileg nincs jelen, és az SDK egy homályos hibát dob. A jó hír? A megoldás néhány sor kódból áll, és percek alatt készen áll a modell. + +Ebben az útmutatóban mindent végigvázolunk, amit tudnod kell: a megfelelő osztályok importálásától a **model könyvtár beállításáig**, a **modell letöltés módjáig**, egészen a útvonal ellenőrzéséig. A végére képes leszel OCR-t futtatni bármely képen egyetlen függvényhívással, és megérted a **model útvonal konfigurálása** opciókat, amelyek rendezetten tartják a projektedet. Nincs felesleges szöveg, csak egy gyakorlati, futtatható példa **aspose ocr python** felhasználók számára. + +## Mit fogsz megtanulni + +- Hogyan importáld helyesen az Aspose OCR Cloud osztályait. +- A pontos lépéseket a **ocr modell letöltéséhez** automatikusan. +- A módokat, hogyan **állítsd be a model könyvtárat** és **konfiguráld a model útvonalat** a reprodukálható buildhez. +- Hogyan ellenőrizd, hogy a modell inicializálva van-e és hol található a lemezen. +- Gyakori buktatók (jogosultságok, hiányzó könyvtárak) és gyors megoldások. + +### Előfeltételek + +- Python 3.8+ telepítve a gépeden. +- `asposeocrcloud` csomag (`pip install asposeocrcloud`). +- Írási jogosultság egy olyan mappához, ahol a modellt tárolni szeretnéd (pl. `C:\models` vagy `~/ocr_models`). + +--- + +## 1. lépés: Aspose OCR Cloud osztályok importálása + +Az első dolog, amire szükséged van, a megfelelő import utasítás. Ez betölti azokat az osztályokat, amelyek a modell konfigurációt és az OCR műveleteket kezelik. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Miért fontos:* Az `AsposeAI` az a motor, amely az OCR-t végrehajtja, míg az `AsposeAIModelConfig` megmondja a motornak, **hol** keresse a modellt és **hogy** töltse le automatikusan. Ennek a lépésnek a kihagyása vagy a rossz modul importálása `ModuleNotFoundError`-t eredményez még a letöltés előtt. + +--- + +## 2. lépés: A modell konfigurációjának definiálása (Model könyvtár beállítása & Model útvonal konfigurálása) + +Most megmondjuk az Aspose-nak, hol tárolja a modell fájlokat. Itt **állítod be a model könyvtárat** és **konfigurálod a model útvonalat**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Tippek és trükkök** + +- **Abszolút útvonalak** elkerülik a zavarokat, ha a script más munkakönyvtárból fut. +- Linux/macOS esetén használhatod a `"/home/you/ocr_models"` útvonalat; Windows alatt előtagként `r`-t adj a visszaperjelek szó szerinti kezeléséhez. +- Az `allow_auto_download="true"` beállítás a kulcs ahhoz, **hogyan töltsd le a modellt** anélkül, hogy extra kódot írnál. + +--- + +## 3. lépés: AsposeAI példány létrehozása a konfigurációval + +A konfiguráció készen áll, most példányosítsuk az OCR motort. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Miért fontos:* Az `ocr_ai` objektum most már tartalmazza a most definiált konfigurációt. Ha a modell nincs jelen, a következő hívás automatikusan elindítja a letöltést – ez a **modell letöltésének módja** egy kéz nélküli megközelítésben. + +--- + +## 4. lépés: A modell letöltésének elindítása (ha szükséges) + +Mielőtt OCR-t futtatnál, meg kell győződnöd arról, hogy a modell ténylegesen a lemezen van. Az `is_initialized()` metódus egyszerre ellenőrzi és kényszeríti az inicializálást. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**Mi történik a háttérben?** + +- Az első `is_initialized()` hívás `False`-t ad vissza, mert a modell mappa üres. +- A `print` tájékoztatja a felhasználót, hogy a letöltés hamarosan kezdődik. +- A második hívás arra készteti az Aspose-t, hogy letöltse a modellt a korábban megadott Hugging Face repóból. +- Letöltés után a metódus a későbbi ellenőrzéseknél `True`-t ad vissza. + +**Különleges eset:** Ha a hálózatod blokkolja a Hugging Face-et, kivételt kapsz. Ebben az esetben manuálisan töltsd le a modell zip fájlt, csomagold ki a `directory_model_path` könyvtárba, majd futtasd újra a scriptet. + +--- + +## 5. lépés: A helyi útvonal jelentése, ahol a modell most elérhető + +A letöltés befejezése után valószínűleg szeretnéd tudni, hová kerültek a fájlok. Ez segít a hibakeresésben és a CI pipeline-ok beállításában. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +A tipikus kimenet így néz ki: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Most már sikeresen **letöltötted az ocr modellt**, beállítottad a könyvtárat, és megerősítetted az útvonalat. + +--- + +## Vizuális áttekintés + +Az alábbi egyszerű diagram a konfigurációtól a használatra kész modellig mutatja a folyamatot. + +![ocr modell letöltés folyamatábra, amely bemutatja a konfigurációt, az automatikus letöltést és a helyi útvonalat](/images/download-ocr-model-flow.png) + +*Az alt szöveg tartalmazza a fő kulcsszót a SEO érdekében.* + +--- + +## Gyakori variációk és kezelési módjaik + +### 1. Másik modell repó használata + +Ha egy másik modellt szeretnél, mint a `openai/gpt2`, egyszerűen cseréld le a `hugging_face_repo_id` értékét: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Győződj meg róla, hogy a repó nyilvános, vagy a környezetedben be van állítva a szükséges token. + +### 2. Automatikus letöltés letiltása + +Néha szeretnéd magad irányítani a letöltést (pl. levegővel elzárt környezetekben). Állítsd az `allow_auto_download` értékét `"false"`-ra, és hívd meg a saját letöltő scriptedet az inicializálás előtt: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. A modell könyvtárának futás közbeni módosítása + +Újrakonfigurálhatod az útvonalat anélkül, hogy újra létrehoznád az `AsposeAI` objektumot: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Profi tippek production környezethez + +- **Modell cache-elése**: Tartsd a könyvtárat egy megosztott hálózati meghajtón, ha több szolgáltatásnak ugyanarra a modellre van szüksége. Így elkerülheted a felesleges letöltéseket. +- **Verzió rögzítése**: A Hugging Face repó frissülhet. Egy konkrét verzióra rögzítéshez tedd a `@v1.0.0` kiegészítést a repo ID-hez (`"openai/gpt2@v1.0.0"`). +- **Jogosultságok**: Bizonyosodj meg róla, hogy a scriptet futtató felhasználónak olvasási/írási jogai vannak a `directory_model_path`-on. Linuxon általában a `chmod 755` elegendő. +- **Loggolás**: Cseréld le az egyszerű `print` utasításokat a Python `logging` moduljára, hogy nagyobb alkalmazásokban jobb megfigyelhetőséget biztosíts. + +--- + +## Teljes működő példa (másolás‑beillesztés készen) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Várható kimenet** (az első futtatás letölti, a későbbi futtatások kihagyják a letöltést): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Futtasd újra a scriptet; csak az útvonal sor jelenik meg, mert a modell már cache‑elve van. + +--- + +## Összegzés + +Lépésről lépésre bemutattuk, hogyan **letöltsd az ocr modellt** az Aspose OCR Python használatával, hogyan **állítsd be a model könyvtárat**, és részleteztük a **model útvonal konfigurálása** finomságait. Néhány sor kóddal automatizálhatod a letöltést, elkerülheted a kézi beavatkozást, és reprodukálhatóvá teheted az OCR pipeline-odat. + +Ezután érdemes lehet megvizsgálni a tényleges OCR hívást (`ocr_ai.recognize_image(...)`) vagy egy másik Hugging Face modellt kipróbálni a pontosság növelése érdekében. Bármelyik úton is jársz, az itt felépített alap – tiszta konfiguráció, automatikus letöltés és útvonal ellenőrzés – megkönnyíti a jövőbeli integrációkat. + +Van kérdésed a széljegyekkel kapcsolatban, vagy szeretnéd megosztani, hogyan állítottad be a modell könyvtárát felhőalapú telepítésekhez? Írj egy megjegyzést alább, és jó kódolást! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/hungarian/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..b1f5ffc13 --- /dev/null +++ b/ocr/hungarian/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-04-26 +description: Hogyan postprocesszáljuk az OCR eredményeket és nyerjünk ki szöveget + koordinátákkal. Tanuljon meg egy lépésről‑lépésre megoldást strukturált kimenet + és AI‑korrekció használatával. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: hu +og_description: Hogyan utófeldolgozzuk az OCR-eredményeket, és szöveget nyerjünk ki + koordinátákkal. Kövesd ezt az átfogó útmutatót egy megbízható munkafolyamatért. +og_title: Hogyan utófeldolgozzuk az OCR-t – Teljes útmutató +tags: +- OCR +- Python +- AI +- Text Extraction +title: Hogyan utófeldolgozzuk az OCR‑t – Szöveg kinyerése koordinátákkal Pythonban +url: /hu/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan kell utófeldolgozni az OCR‑t – Szöveg kinyerése koordinátákkal Pythonban + +Volt már, hogy **hogyan kell utófeldolgozni az OCR** eredményeket, mert a nyers kimenet zajos vagy rosszul igazított volt? Nem vagy egyedül. Sok valós projektben – számlabeolvasás, nyugták digitalizálása vagy akár AR‑élmények kiegészítése – az OCR motor nyers szavakat ad, de neked még mindig tisztítanod kell őket, és nyomon kell követned, hogy a szó hol helyezkedik el az oldalon. Itt jön képbe a strukturált kimeneti mód egy AI‑vezérelt utófeldolgozóval kombinálva. + +Ebben a tutorialban végigvezetünk egy teljes, futtatható Python pipeline‑on, amely **koordinátákkal együtt kinyeri a szöveget** egy képből, egy AI‑alapú korrekciós lépést hajt végre, és minden szót kiír a (x, y) pozíciójával együtt. Nincs hiányzó import, nincs homályos „lásd a dokumentációt” hivatkozás – csak egy önálló megoldás, amelyet ma be tudsz illeszteni a projektedbe. + +> **Pro tip:** Ha másik OCR könyvtárat használsz, keresd a „structured” vagy „layout” módot; a koncepciók ugyanazok. + +--- + +## Előfeltételek + +Mielőtt belevágnánk, győződj meg róla, hogy a következők rendelkezésre állnak: + +| Követelmény | Miért fontos | +|-------------|--------------| +| Python 3.9+ | Modern szintaxis és típusjelölések | +| `ocr` könyvtár, amely támogatja az `OutputMode.STRUCTURED`‑t (pl. egy fiktív `myocr`) | Szükséges a körülhatároló doboz adatokhoz | +| AI utófeldolgozó modul (lehet OpenAI, HuggingFace vagy egy egyedi modell) | Javítja a pontosságot az OCR után | +| Képfájl (`input.png`) a munkakönyvtáradban | A forrás, amelyet beolvasunk | + +Ha bármelyik ismeretlennek tűnik, telepítsd a helyettesítő csomagokat a `pip install myocr ai‑postproc` paranccsal. Az alábbi kód tartalmaz fallback stub‑okat is, így a folyamatot a valódi könyvtárak nélkül is tesztelheted. + +--- + +## 1. lépés: Strukturált kimeneti mód engedélyezése az OCR motorban + +Az első dolog, amit megteszünk, hogy az OCR motorra azt mondjuk, adjon nekünk többet, mint egyszerű szöveget. A strukturált kimenet minden szót a körülhatároló dobozzal és a megbízhatósági pontszámmal együtt adja vissza, ami elengedhetetlen a **szöveg kinyerése koordinátákkal** később. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Miért fontos:* Strukturált mód nélkül csak egy hosszú karakterláncot kapnál, és elveszítenéd a térbeli információkat, amelyekre a szöveg képre való ráhelyezéséhez vagy a downstream layout elemzéshez szükség van. + +--- + +## 2. lépés: Kép felismerése és a szavak, dobozok, valamint a megbízhatóság rögzítése + +Most betápláljuk a képet a motorba. Az eredmény egy objektum, amely szólistát tartalmaz, minden szó objektuma pedig rendelkezik `text`, `x`, `y`, `width`, `height` és `confidence` mezőkkel. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Edge case:* Ha a kép üres vagy nem olvasható, a `structured_result.words` egy üres listát ad vissza. Jó gyakorlat ellenőrizni ezt, és megfelelően kezelni. + +--- + +## 3. lépés: AI‑alapú utófeldolgozás a pozíciók megőrzésével + +Még a legjobb OCR motorok is hibáznak – gondolj a „O” és a „0” közti különbségre vagy a hiányzó diakritikus jelekre. Egy domain‑specifikus szövegre tanított AI modell kijavíthatja ezeket a hibákat. Lényeges, hogy az eredeti koordinátákat megtartsuk, így a térbeli elrendezés változatlan marad. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Miért őrizzük meg a koordinátákat:* Sok downstream feladat (pl. PDF generálás, AR címkézés) pontos elhelyezést igényel. Az AI csak a `text` mezőt módosítja, a `x`, `y`, `width`, `height` változatlan marad. + +--- + +## 4. lépés: A javított szavak iterálása és a szöveg koordinátákkal való megjelenítése + +Végül végigjárjuk a javított szavakat, és kiírjuk minden szót a bal‑felső sarok `(x, y)` koordinátáival együtt. Ez teljesíti a **szöveg kinyerése koordinátákkal** célt. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Várt kimenet (példa):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Minden sor a javított szót és annak pontos helyét mutatja az eredeti képen. + +--- + +## Teljes működő példa + +Az alábbi egyetlen szkript mindent összekapcsol. Másold be, igazítsd a importokat a saját könyvtáraidhoz, és futtasd közvetlenül. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**A szkript futtatása** + +```bash +python ocr_postprocess_demo.py +``` + +Ha a valódi könyvtárak telepítve vannak, a szkript feldolgozza a `input.png` fájlt. Ellenkező esetben a stub implementáció lehetővé teszi, hogy a várt folyamatot és kimenetet láthasd külső függőségek nélkül. + +--- + +## Gyakran Ismételt Kérdések (FAQ) + +| Kérdés | Válasz | +|--------|--------| +| *Működik ez Tesseract‑tal?* | A Tesseract önmagában nem kínál strukturált módot, de a `pytesseract.image_to_data` wrapper visszaadja a körülhatároló dobozokat, amelyeket ugyanabba az AI utófeldolgozóba táplálhatsz. | +| *Mi van, ha a jobb‑alsó sarok koordinátájára van szükségem a bal‑felső helyett?* | Minden szó objektum tartalmazza a `width` és `height` értékeket. Számold ki `x2 = x + width` és `y2 = y + height` a ellentétes sarokhoz. | +| *Tudok több képet egyszerre feldolgozni?* | Természetesen. Csomagold a lépéseket egy `for image_path in Path("folder").glob("*.png"):` ciklusba, és gyűjtsd az eredményeket fájlonként. | +| *Hogyan válasszak AI modellt a korrekcióhoz?* | Általános szöveghez egy kis GPT‑2 modell, amely OCR hibákon finomhangolt, megfelelő. Domain‑specifikus adatokhoz (pl. orvosi receptek) taníts egy sequence‑to‑sequence modellt párhuzamos zajos‑tiszta adatokon. | +| *Hasznos a confidence score az AI korrekció után?* | Megtarthatod az eredeti confidence értéket hibakereséshez, de az AI is adhat saját confidence‑t, ha a modell támogatja. | + +--- + +## Edge case‑ek és legjobb gyakorlatok + +1. **Üres vagy sérült képek** – mindig ellenőrizd, hogy a `structured_result.words` nem üres, mielőtt folytatnád. +2. **Nem latin írásrendszerek** – győződj meg róla, hogy az OCR motor a célnyelvre van konfigurálva; az AI utófeldolgozónak ugyanazon írásrendszeren kell lennie tréningezve. +3. **Teljesítmény** – az AI korrekció költséges lehet. Cache‑eld az eredményeket, ha ugyanazt a képet többször használod, vagy futtasd az AI lépést aszinkron módon. +4. **Koordináta rendszer** – az OCR könyvtárak különböző origókat (bal‑felső vs. bal‑alsó) használhatnak. Igazítsd a koordinátákat, amikor PDF‑ekre vagy vásznakra helyezed őket. + +--- + +## Összegzés + +Most már van egy szilárd, vég‑től‑végig recept a **hogyan kell utófeldolgozni az OCR**-t és megbízhatóan **szöveget kinyerni koordinátákkal**. A strukturált kimenet engedélyezésével, az eredmény AI‑korrekciós rétegen való áthaladásával és az eredeti körülhatároló dobozok megőrzésével a zajos OCR beolvasásokat tiszta, térbeli információval rendelkező szöveggé alakíthatod, amely készen áll downstream feladatokra, mint PDF generálás, adatbevitel automatizálás vagy augmentált valóság overlay‑k. + +Készen állsz a következő lépésre? Próbáld ki a stub AI helyett egy OpenAI `gpt‑4o‑mini` hívással, vagy integráld a pipeline‑t egy FastAPI‑ba + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/hungarian/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..9a9b443c3 --- /dev/null +++ b/ocr/hungarian/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-26 +description: Hogyan ismerjünk fel képeket gyorsan Python segítségével. Tanulj meg + egy képfelismerő folyamatot, kötegelt feldolgozást, és automatizáld a képfelismerést + mesterséges intelligenciával. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: hu +og_description: Hogyan ismerjünk fel képeket gyorsan Python segítségével. Ez az útmutató + végigvezet egy képfelismerő folyamaton, a kötegelt feldolgozáson és az AI használatával + történő automatizáláson. +og_title: Hogyan ismerjünk fel képeket – Automatizáljuk a képfelismerő folyamatot +tags: +- image-processing +- python +- ai +title: Hogyan ismerjünk fel képeket – Képfelismerő folyamat automatizálása +url: /hu/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan ismerjünk fel képeket – Automatizálj egy képfelismerő csővezetéket + +Gondolkodtál már azon, **hogyan lehet képeket felismerni** anélkül, hogy ezer sor kódot írnál? Nem vagy egyedül – sok fejlesztő ugyanabba a falba ütközik, amikor először kell feldolgozni tucat vagy akár száz képet. A jó hír? Néhány egyszerű lépéssel felállíthatsz egy teljes körű képfelismerő csővezetéket, amely önmagától csoportosít, futtat és takarít fel. + +Ebben az útmutatóban egy teljes, futtatható példán keresztül mutatjuk be, **hogyan lehet képeket csoportosítani**, mindegyiket egy AI motorba betáplálni, az eredményeket utófeldolgozni, és végül felszabadítani az erőforrásokat. A végére egy önálló szkriptet kapsz, amelyet bármely projektbe beilleszthetsz, legyen szó fotó‑címkézőről, minőség‑ellenőrző rendszerről vagy kutatási adatkészlet‑generátorról. + +## Mit tanulhatsz meg + +- **Hogyan lehet képeket felismerni** egy mock AI motor segítségével (a minta ugyanaz a valódi szolgáltatásoknál, mint a TensorFlow, PyTorch vagy felhő‑API‑k). +- Hogyan építs egy **képfelismerő csővezetéket**, amely hatékonyan kezeli a csoportokat. +- A legjobb módja a **képfelismerés automatizálásának**, hogy ne kelljen minden alkalommal manuálisan fájlokon iterálni. +- Tippek a csővezeték skálázásához és az erőforrások biztonságos felszabadításához. + +> **Előfeltételek:** Python 3.8+, alapvető ismeretek a függvényekről és ciklusokról, valamint néhány képfájl (vagy útvonal), amelyet fel szeretnél dolgozni. A fő példához nincs szükség külső könyvtárakra, de megemlítjük, hol lehet valós AI SDK‑kat csatlakoztatni. + +![Képfeldolgozó csővezeték diagramja, amely megmutatja, hogyan ismerjünk fel képeket csoportos feldolgozás során](pipeline.png "Képfelismerés diagram") + +## 1. lépés: Csoportosítsd a képeidet – Hogyan csoportosíts képeket hatékonyan + +Mielőtt az AI bármit is nehéz feladatot végezne, szükséged van egy képgyűjteményre, amelyet betáplálhatsz. Gondolj erre úgy, mint egy bevásárlólistára; a motor később egyesével veszi fel a listáról a tételeket. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Miért csoportosíts?** +A csoportosítás csökkenti a szükséges boilerplate kód mennyiségét, és egyszerűvé teszi a párhuzamosság későbbi bevezetését. Ha valaha 10 000 képet kell feldolgoznod, csak a `image_batch` forrását kell módosítanod – a csővezeték többi része változatlan marad. + +## 2. lépés: Futtasd a képfelismerő csővezetéket (Képek felismerése AI‑val) + +Most a csoportot a tényleges felismerőhöz csatlakoztatjuk. Valós környezetben például a `torchvision.models`‑t vagy egy felhő‑endpointot hívnál; itt a viselkedést mock‑oljuk, hogy az útmutató önálló maradjon. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Magyarázat:** +- `engine.recognize_image` a **képfelismerő csővezeték** szíve; lehet egy mélytanuló modell vagy egy REST API hívás. +- `postprocessor.run` mutatja be a **képfelismerés automatizálását**, azaz a nyers predikciók normalizálását egy tiszta szótárba, amelyet tárolhatsz vagy streamelhetsz. +- Minden `corrected` szótárat a `recognized_results`‑ba gyűjtünk, így a későbbi lépések (pl. adatbázis‑beszúrás) egyszerűek. + +## 3. lépés: Utófeldolgozás és tárolás – Automatizáld a képfelismerés eredményeit + +Miután megvan a rendezett predikciólista, általában szeretnéd azt tartósan elmenteni. Az alábbi példa CSV‑fájlt ír; nyugodtan cseréld le adatbázisra vagy üzenetsorra. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Miért CSV?** +A CSV univerzálisan olvasható – Excel, pandas, sőt egyszerű szövegszerkesztők is megnyitják. Ha később **képfelismerést szeretnél automatizálni** nagy léptékben, cseréld le a írási blokkot egy tömeges beszúrásra a data lake‑edbe. + +## 4. lépés: Takaríts fel – AI erőforrások biztonságos felszabadítása + +Sok AI SDK GPU‑memóriát vagy munkás szálakat allokál. Ha elfelejted felszabadítani őket, memória‑szivárgás és összeomlás következik. Bár a mock objektumainknak nincs erre szüksége, megmutatjuk a helyes mintát. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +A szkript futtatása barátságos megerősítést ír ki, jelezve, hogy a csővezeték tisztán befejeződött. + +## Teljes működő szkript + +Mindent összerakva, itt a kész, másolás‑beillesztés‑kész program: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Várható kimenet + +A szkript futtatásakor (ha a három helyőrző útvonal létezik) valami ilyesmit látsz majd: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +És a létrehozott `recognition_results.csv` a következőket tartalmazza: + +| kép | címke | bizalom | +|---------------------|------|---------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other| 0.65 | + +## Összegzés + +Most már van egy szilárd, vég‑től‑végig példád arra, **hogyan lehet képeket felismerni** Pythonban, egy **képfelismerő csővezetékkel**, csoportkezeléssel és automatizált utófeldolgozással. A minta skálázható: cseréld le a mock osztályokat egy valódi modellre, adj nagyobb `image_batch`‑t, és kész is egy termelés‑kész megoldás. + +Szeretnél továbbmenni? Próbáld ki a következő lépéseket: + +- Cseréld le a `MockEngine`‑t egy TensorFlow vagy PyTorch modellre a valós predikciókhoz. +- Párhuzamosítsd a ciklust a `concurrent.futures.ThreadPoolExecutor`‑rel, hogy felgyorsítsd a nagy csoportokat. +- Kapcsold a CSV‑írót egy felhő‑tároló buckethez, hogy **képfelismerést automatizálj** elosztott munkások között. + +Nyugodtan kísérletezz, törj el dolgokat, majd javítsd őket – így válik valaki igazi mesterré a képfelismerő csővezetékekben. Ha bármilyen akadályba ütközöl vagy ötleted van a fejlesztésre, írj egy megjegyzést alul. Boldog kódolást! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/hungarian/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..b977fb21e --- /dev/null +++ b/ocr/hungarian/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-04-26 +description: Maszkolja gyorsan a hitelkártya-számokat az AsposeAI OCR utófeldolgozással. + Ismerje meg a PCI megfelelőséget, a reguláris kifejezéssel történő maszkolást és + az adat tisztítását egy lépésről‑lépésre útmutatóban. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: hu +og_description: Maszkold a hitelkártyaszámokat az OCR-eredményekben az AsposeAI segítségével. + Ez az útmutató a PCI-megfelelőséget, a reguláris kifejezésekkel történő maszkolást + és az adattisztítást tárgyalja. +og_title: Hitelkártya számok maszkolása – Teljes Python OCR utófeldolgozási útmutató +tags: +- OCR +- Python +- security +title: Hitelkártya-számok maszkolása az OCR kimenetben – Teljes Python útmutató +url: /hu/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hitelkártya-számok maszkolása – Teljes Python útmutató + +Volt már szükséged **hitelkártya-számok** maszkolására olyan szövegben, amely közvetlenül egy OCR motorból származik? Nem vagy egyedül. Szabályozott iparágakban a teljes PAN (Primary Account Number) felfedése komoly gondokat okozhat a PCI megfelelőségi auditoroknál. A jó hír? Néhány Python sorral és az AsposeAI post‑processing hook‑jával automatikusan elrejtheted a középső nyolc számjegyet, és biztonságban maradhatsz. + +Ebben az útmutatóban egy valós példán keresztül vezetünk végig: OCR futtatása egy nyugta képen, majd egy egyedi **OCR post‑processing** függvény alkalmazása, amely megtisztítja a PCI adatokat. A végére egy újrahasználható kódrészletet kapsz, amelyet bármely AsposeAI munkafolyamatba beilleszthetsz, valamint néhány gyakorlati tippet a szélső esetek kezelésére és a megoldás skálázására. + +## Mit fogsz megtanulni + +- Hogyan regisztrálj egy egyedi post‑processzort az **AsposeAI**‑val. +- Miért gyors és megbízható a **regular expression masking** (reguláris kifejezéses maszkolás) megközelítés. +- A **PCI compliance** (PCI megfelelőség) alapjai az adattisztítás kapcsán. +- Módszerek a minta kiterjesztésére több kártyaformátum vagy nemzetközi számok esetén. +- Várható kimenet és hogyan ellenőrizheted, hogy a maszkolás működött. + +> **Előfeltételek** – Rendelkezned kell egy működő Python 3 környezettel, az Aspose.AI for OCR csomaggal telepítve (`pip install aspose-ocr`), és egy mintaképpel (pl. `receipt.png`), amely tartalmaz egy hitelkártya-számot. Más külső szolgáltatás nem szükséges. + +--- + +## 1. lépés: Definiáld a post‑processzort, amely a hitelkártya-számokat maszkolja + +A megoldás lényege egy apró függvényben rejlik, amely megkapja az OCR eredményt, egy **regular expression masking** (reguláris kifejezéses maszkolás) rutint futtat, és visszaadja a megtisztított szöveget. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Miért működik ez:** +- A regex `(\d{4})\d{8}(\d{4})` pontosan 16 egymást követő számjegyet egyeztet, ami a Visa, MasterCard és sok más kártya általános formátuma. +- Az első és az utolsó négy számjegy (`\1` és `\2`) rögzítésével elegendő információt megőrzünk a hibakereséshez, miközben betartjuk a **PCI compliance** szabályait, amelyek tiltják a teljes PAN tárolását. +- A `\1****\2` helyettesítés elrejti a középső nyolc érzékeny számjegyet, így a `1234567812345678` `1234****5678` lesz. + +> **Pro tip:** Ha 15 számjegyű American Express számokat is támogatni szeretnél, adj hozzá egy második mintát, például `r'(\d{4})\d{6}(\d{5})'`, és futtasd egymás után mindkét helyettesítést. + +--- + +## 2. lépés: Inicializáld az AsposeAI motorját + +Mielőtt csatlakoztatnánk a post‑processzorunkat, szükségünk van az OCR motor egy példányára. Az AsposeAI tartalmazza az OCR modellt és egy egyszerű API-t az egyedi feldolgozáshoz. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Miért inicializáljuk itt?** +Az `AsposeAI` objektum egyszeri létrehozása és több kép között való újrahasználata csökkenti a terhelést. A motor emellett gyorsítótárazza a nyelvi modelleket, ami felgyorsítja a későbbi hívásokat – hasznos, ha nyugtákat szkennelsz kötegben. + +--- + +## 3. lépés: Regisztráld az egyedi maszkoló függvényt + +Az AsposeAI egy `set_post_processor` metódust biztosít, amely lehetővé teszi bármilyen hívható objektum csatlakoztatását. Átadjuk a `mask_pci` függvényünket egy opcionális beállítási szótárral (most üres). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**Mi történik a háttérben?** +Amikor később meghívod a `run_postprocessor`-t, az AsposeAI a nyers OCR eredményt átadja a `mask_pci`-nek. A függvény egy könnyű objektumot (`data`) kap, amely a felismert szöveget tartalmazza, és egy új stringet ad vissza. Ez a tervezés érintetlenül hagyja az OCR magját, miközben egy helyen tudod érvényesíteni a **data sanitization** (adat-tisztítási) szabályokat. + +--- + +## 4. lépés: Futtasd az OCR-t a nyugta képen + +Most, hogy a motor tudja, hogyan tisztítsa meg a kimenetet, betáplálunk egy képet. Az útmutató kedvéért feltételezzük, hogy már rendelkezel egy `engine` objektummal, amely a megfelelő nyelvi és felbontási beállításokkal van konfigurálva. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Tipp:** Ha nincs előre konfigurált objektumod, létrehozhatsz egyet a következővel: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +A `recognize_image` hívás egy olyan objektumot ad vissza, amelynek `text` attribútuma a nyers, nem maszkolt szöveget tartalmazza. + +--- + +## 5. lépés: Alkalmazd a regisztrált post‑processzort + +A nyers OCR adatok birtokában átadjuk őket az AI példánynak. A motor automatikusan futtatja a korábban regisztrált `mask_pci` függvényt. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Miért használjuk a `run_postprocessor`-t a függvény kézi meghívása helyett?** +Ez biztosítja a munkafolyamat konzisztenciáját, különösen ha több post‑processzort (pl. helyesírás-ellenőrzés, nyelvfelismerés) használsz. Az AsposeAI a regisztráció sorrendjében sorba helyezi őket, garantálva a determinisztikus kimenetet. + +--- + +## 6. lépés: Ellenőrizd a megtisztított kimenetet + +Végül nyomtassuk ki a megtisztított szöveget, és ellenőrizzük, hogy a hitelkártya-számok megfelelően vannak-e maszkolva. + +```python +print(final_result.text) +``` + +**Várható kimenet** (részlet): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Ha a nyugta nem tartalmazott kártyaszámot, a szöveg változatlan marad – nincs mit maszkolni, nincs miért aggódni. + +--- + +## Szélső esetek és gyakori variációk kezelése + +### Több kártya-szám egy dokumentumban +Ha egy nyugta több PAN-t (pl. egy hűségkártya és egy fizetési kártya) tartalmaz, a regex globálisan fut, és automatikusan minden egyezést maszkol. Nem szükséges extra kód. + +### Nem szabványos formázás +Néha az OCR szóközöket vagy kötőjeleket szúr be (`1234 5678 1234 5678` vagy `1234-5678-1234-5678`). Bővítsd a mintát, hogy figyelmen kívül hagyja ezeket a karaktereket: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +A hozzáadott `[ -]?` opcionális szóközöket vagy kötőjeleket enged meg a számcsoportok között. + +### Nemzetközi kártyák +Néhány régióban használt 19 számjegyű PAN-ok esetén kibővítheted a mintát: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Csak ne feledd, hogy a **PCI compliance** továbbra is előírja a középső számjegyek maszkolását, függetlenül a hosszuktól. + +### Maszkolt értékek naplózása (opcionális) +Ha audit nyomvonalra van szükséged, adj át egy jelzőt a `custom_settings`-en keresztül, és módosítsd a függvényt: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Ezután regisztráld a következővel: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Teljes működő példa (másolásra kész) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +A szkript futtatása egy `4111111111111111` számot tartalmazó nyugtán a következőt eredményezi: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +Ez a teljes folyamat – a nyers OCR-től a **data sanitization**-ig – néhány tiszta Python sorba csomagolva. + +--- + +## Összegzés + +Most bemutattuk, hogyan **maszkolhatod a hitelkártya-számokat** OCR eredményekben az AsposeAI post‑processing hook, egy tömör reguláris kifejezéses rutin és néhány bevált gyakorlat segítségével a **PCI compliance** érdekében. A megoldás teljesen önálló, bármely, az OCR motor által olvasható képen működik, és kiterjeszthető összetettebb kártyaformátumok vagy naplózási igények lefedésére. + +Készen állsz a következő lépésre? Próbáld meg összekapcsolni ezt a maszkolást egy **adatbázis-beillesztési** rutinnal, amely csak az utolsó négy számjegyet tárolja hivatkozásként, vagy integrálj egy **kötegfeldolgozót**, amely egy egész nyugták mappáját szkennelje éjszaka. Felfedezheted továbbá más **OCR post‑processing** feladatokat is, mint például címstandardizálás vagy nyelvfelismerés – mindegyik ugyanazt a mintát követi, amit itt használtunk. + +Van kérdésed a szélső esetekkel, a teljesítménnyel vagy azzal kapcsolatban, hogyan adaptáld a kódot egy másik OCR könyvtárhoz? Írj egy megjegyzést alább, és folytassuk a beszélgetést. Boldog kódolást, és maradj biztonságban! + +![Diagram illustrating how mask credit card numbers works in an OCR pipeline](https://example.com/images/ocr-mask-flow.png "Diagram of OCR post‑processing masking flow") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/hungarian/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..d854ec523 --- /dev/null +++ b/ocr/hungarian/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-04-26 +description: Tanulja meg, hogyan mérje az inferencia időt Pythonban, hogyan töltsön + be egy GGUF modellt a Hugging Face-ről, és hogyan optimalizálja a GPU használatát + a gyorsabb eredmények érdekében. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: hu +og_description: Mérje a következtetési időt Pythonban, egy Hugging Face‑ről betöltött + GGUF modell segítségével, és finomhangolja a GPU rétegeket az optimális teljesítmény + érdekében. +og_title: Mérje a következtetési időt – GGUF modell betöltése és GPU optimalizálása +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Az inferencia idő mérése – GGUF modell betöltése és GPU optimalizálása +url: /hu/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Inferenz Idő Mérése – GGUF Modell Betöltése és GPU Optimalizálása + +Valaha is szükséged volt arra, hogy **measure inference time** egy nagy nyelvi modellnél, de nem tudtad, hol kezdjed? Nem vagy egyedül—sok fejlesztő ugyanabba a falba ütközik, amikor először húznak le egy GGUF fájlt a Hugging Face‑ről, és megpróbálják futtatni egy vegyes CPU/GPU környezetben. + +Ebben az útmutatóban végigvezetünk a **how to load a GGUF model** folyamaton, konfiguráljuk a Hugging Face‑hez, és **measure inference time** egy tiszta Python kódrészlettel. Útközben megmutatjuk, hogyan **optimize inference GPU** használatát, hogy a futtatások a lehető leggyorsabbak legyenek. Nincs felesleges szöveg, csak egy gyakorlati, vég‑től‑végig megoldás, amit ma másolhatsz‑beilleszthetsz. + +## Amit Megtanulhatsz + +- Hogyan **configure a HuggingFace model** a `AsposeAIModelConfig`‑vel. +- A pontos lépések a **load a GGUF model** (`fp16` kvantálás) betöltéséhez a Hugging Face hub‑ról. +- Egy újrahasználható minta a **timing Python code** körül egy inferencia hívásnál. +- Tippek a **optimize inference GPU** beállításához a `gpu_layers` módosításával. +- Várható kimenet és hogyan ellenőrizheted, hogy az időmérés értelmes. + +### Előfeltételek + +| Követelmény | Miért fontos | +|-------------|----------------| +| Python 3.9+ | Modern szintaxis és típusjelzések. | +| `asposeai` package (or the equivalent SDK) | `AsposeAI` és `AsposeAIModelConfig` biztosítja. | +| Access to the Hugging Face repo `bartowski/Qwen2.5-3B-Instruct-GGUF` | A GGUF modell, amelyet betöltünk. | +| A GPU with at least 8 GB VRAM (optional but recommended) | Lehetővé teszi a **optimize inference GPU** lépést. | + +If you haven’t installed the SDK yet, run: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![measure inference time diagram](https://example.com/measure-inference-time.png){alt="inferenz idő mérés diagram"} + +## 1. lépés: GGUF Modell Betöltése – HuggingFace Modell Konfigurálása + +Az első dolog, amire szükséged van, egy megfelelő konfigurációs objektum, amely megmondja az Aspose AI‑nek, honnan töltse le a modellt és hogyan kezelje azt. Itt **load a GGUF model** és **configure huggingface model** paramétereket állítunk be. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Miért fontos:** +- `hugging_face_repo_id` a pontos GGUF fájlra mutat a Hub‑on. +- `fp16` csökkenti a memória sávszélességet, miközben a modell nagy részének pontosságát megőrzi. +- `gpu_layers` az a beállítás, amelyet módosítasz, ha **optimize inference GPU** teljesítményt szeretnéd javítani; több réteg a GPU‑n általában gyorsabb késleltetést jelent, ha elegendő VRAM‑od van. + +## 2. lépés: Aspose AI Példány Létrehozása + +Miután a modell le van írva, elindítunk egy `AsposeAI` objektumot. Ez a lépés egyszerű, de itt tölti le a SDK a GGUF fájlt (ha nincs gyorsítótárban), és előkészíti a futtatókörnyezetet. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Pro tipp:** Az első futtatás néhány másodperccel tovább tart, mivel a modell letöltődik és a GPU‑ra le van fordítva. A későbbi futtatások villámgyorsak. + +## 3. lépés: Inferenz Futtatása és **Measure Inference Time** + +Itt van a tutorial szíve: az inferencia hívást `time.time()`‑al körülvéve **measure inference time**. Emellett egy apró OCR eredményt adunk meg, hogy a példa önálló legyen. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Mit kell látnod:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Ha a szám magasnak tűnik, valószínűleg a legtöbb réteg a CPU‑n fut. Ez a következő lépéshez vezet. + +## 4. lépés: **Optimize Inference GPU** – `gpu_layers` Hangolása + +Néha az alapértelmezett `gpu_layers=40` vagy túl agresszív (OOM-ot okoz), vagy túl visszafogott (teljesítmény elvesztése). Itt egy gyors ciklus, amelyet használhatsz a megfelelő érték megtalálásához: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Miért működik:** +- Minden hívás újraépíti a futtatókörnyezetet egy különböző GPU‑allokációval, így azonnal láthatod a késleltetés kompromisszumát. +- A ciklus bemutatja a **time python code** újrahasználható módját, amelyet más teljesítménytesztekhez is adaptálhatsz. + +Egy tipikus kimenet egy 16 GB RTX 3080-as gépen így nézhet ki: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +Ebből a `gpu_layers=40`-at választanád optimális pontként ehhez a hardverhez. + +## Teljes Működő Példa + +Mindent összevonva, itt egyetlen szkript, amelyet beletehetsz egy fájlba (`measure_inference.py`) és futtathatsz: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Run it with: + +```bash +python measure_inference.py +``` + +Egy megfelelő GPU‑n alatti másodpercnél gyorsabb késleltetést kell látnod, ami megerősíti, hogy sikeresen **measure inference time** és **optimize inference GPU**. + +--- + +## Gyakran Ismételt Kérdések (GYIK) + +**K: Működik ez más kvantálási formátumokkal is?** +V: Teljesen. Cseréld ki a konfigurációban a `hugging_face_quantization="int8"`‑t (vagy `q4_0`, stb.) és futtasd újra a benchmarkot. Várj egy kompromisszumot: alacsonyabb memóriahasználat vs. enyhe pontosságcsökkenés. + +**K: Mi van, ha nincs GPU-m?** +V: Állítsd be `gpu_layers=0`. A kód teljesen a CPU‑ra fog visszatérni, és továbbra is képes leszel **measure inference time**‑ra—csak számíts magasabb értékekre. + +**K: Időzíthetem csak a modell előrehaladási lépését, a post‑processzálás nélkül?** +V: Igen. Hívd meg közvetlenül a `ai_engine.run_model(...)`‑t (vagy az ekvivalens metódust), és csomagold be a hívást `time.time()`‑al. A **time python code** minta változatlan marad. + +## Következtetés + +Most már egy teljes, másol‑beilleszt megoldással rendelkezel a **measure inference time** egy GGUF modellhez, a **load gguf model** betöltéséhez a Hugging Face‑ről, és a **optimize inference GPU** beállítások finomhangolásához. A `gpu_layers` módosításával és a kvantálás kísérletezésével minden egyes milliszekundót kihozhatsz a teljesítményből. + +Ezután esetleg szeretnéd: + +- Integrálni ezt az időzítési logikát egy CI pipeline‑ba a regressziók elkapásához. +- Batch inferenciát felfedezni a throughput további növeléséhez. +- A modellt egy valódi OCR pipeline‑nal kombinálni a helyettesítő szöveg helyett, amit itt használtunk. + +Boldog kódolást, és legyenek a késleltetési számaid mindig alacsonyak! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/hungarian/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..0c24fc146 --- /dev/null +++ b/ocr/hungarian/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-26 +description: Ismerje fel a kézírásos szöveget a Python OCR motorjával. Tanulja meg, + hogyan lehet szöveget kinyerni a képből, bekapcsolni a kézírási módot, és gyorsan + elolvasni a kézírásos jegyzeteket. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: hu +og_description: Ismerje fel a kézírásos szöveget Python segítségével. Ez az útmutató + bemutatja, hogyan lehet szöveget kinyerni a képből, bekapcsolni a kézírásos módot, + és egyszerű OCR motorral olvasni a kézírásos jegyzeteket. +og_title: Kézírás felismerése Pythonban – Teljes OCR útmutató +tags: +- OCR +- Python +- Handwriting Recognition +title: Kézírásos szöveg felismerése Pythonban – OCR motor útmutató +url: /hu/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# kézírásos szöveg felismerése Pythonban – OCR Motor Bemutató + +Valaha is szükséged volt **kézírásos szöveg felismerésére**, de elakadtál a „hol kezdjem?” kérdésnél? Nem vagy egyedül. Akár egy megbeszélés jegyzeteit digitalizálod, akár egy beolvasott űrlapról szeretnél adatot kinyerni, egy megbízható OCR eredmény elérése olyan, mintha egy unikornist kergetnél. + +Jó hír: néhány Python sorral **extract text from image** fájlokból, **turn on handwritten mode**, és végül **read handwritten notes** anélkül, hogy el kellene keresned elavult könyvtárakat. Ebben az útmutatóban végigvezetünk a teljes folyamaton, a **create OCR engine python** típusú beállítástól a képernyőre történő eredmény kiírásáig. + +## Mit fogsz megtanulni + +- Hogyan hozhatsz létre **create OCR engine python** példányt az `ocr` csomag használatával. +- Melyik nyelvi beállítás biztosít beépített kézírási támogatást. +- A pontos hívás a **turn on handwritten mode** aktiválásához, hogy a motor tudja, kézírásról van szó. +- Hogyan adhatod meg egy jegyzet képét, és **recognize handwritten text**-et nyerhetsz belőle. +- Tippek különböző képfájlformátumok kezelésére, gyakori hibák elhárítására és a megoldás bővítésére. + +Nincs felesleges szöveg, nincs „lásd a dokumentációt” zsákutca—csak egy teljes, futtatható szkript, amit ma másolhatsz és tesztelhetsz. + +## Előfeltételek + +Mielőtt belemerülnénk, győződj meg róla, hogy rendelkezel: + +1. Telepített Python 3.8+ (a kód f‑stringeket használ). +2. A feltételezett `ocr` könyvtár (`pip install ocr‑engine` – cseréld le a tényleges csomagnévre, amit használsz). +3. Egy tiszta képfájl kézírásos jegyzetből (JPEG, PNG vagy TIFF megfelelő). +4. Egy kis kíváncsiság—minden mást alább lefedünk. + +> **Pro tipp:** Ha a képed zajos, futtass egy gyors előfeldolgozási lépést a Pillow segítségével (pl. `Image.open(...).convert('L')`) mielőtt elküldenéd az OCR motorba. Gyakran növeli a pontosságot. + +## Hogyan ismerjünk fel kézírásos szöveget Pythonban + +Az alábbiakban a teljes szkript látható, amely **creates OCR engine python** objektumokat hoz létre, kézírásra konfigurálja őket, és kiírja a kinyert karakterláncot. Mentsd el `handwriting_ocr.py` néven, és futtasd a terminálodból. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Várható kimenet + +Ha a szkript sikeresen fut, valami ilyesmit fogsz látni: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Ha az OCR motor nem tud karaktereket észlelni, a `text` mező üres karakterlánc lesz. Ebben az esetben ellenőrizd újra a kép minőségét, vagy próbálj magasabb felbontású beolvasást. + +## Lépésről‑lépésre magyarázat + +### 1. lépés – **create OCR engine python** példány + +Az `OcrEngine` osztály a belépési pont. Gondolj rá úgy, mint egy üres jegyzetfüzetre – semmi sem történik, amíg meg nem mondod, milyen nyelvre számít és hogy kézírásról van-e szó. + +### 2. lépés – Válassz egy kézírási támogatással rendelkező nyelvet + +`ocr.Language.EXTENDED_LATIN` nem csak „English”. Egy sor latin‑alapú írásrendszert tartalmaz, és ami még fontosabb, tartalmaz kézírási mintákon tanított modelleket. Ennek a lépésnek a kihagyása gyakran torz kimenetet eredményez, mivel a motor alapértelmezés szerint egy nyomtatott szöveg modellt használ. + +### 3. lépés – **turn on handwritten mode** + +`enable_handwritten_mode(True)` hívása egy belső jelzőt állít be. Ezután a motor a neurális hálózatára vált, amely a valós jegyzetekben előforduló szabálytalan távolságokra és változó vonalvastagságokra van hangolva. Ennek a sornak a elhagyása gyakori hiba; a motor a karcolásaidat zajként kezeli. + +### 4. lépés – Add meg a képet és **recognize handwritten text** + +`recognize_image` végzi a nehéz munkát: előfeldolgozza a bitmapet, átadja a kézírási modellnek, és egy objektumot ad vissza a `text` attribútummal. Ha minőségi mérőszámra van szükséged, megtekintheted a `handwritten_result.confidence` értéket is. + +### 5. lépés – Írd ki az eredményt és **read handwritten notes** + +`print(handwritten_result.text)` a legegyszerűbb módja annak, hogy ellenőrizd, sikeresen **extract text from image**-t hajtottál végre. Éles környezetben valószínűleg egy adatbázisba tárolnád a karakterláncot, vagy egy másik szolgáltatásnak adnád át. + +## Szélsőséges esetek és gyakori variációk kezelése + +| Szituáció | Mit kell tenni | +|-----------|----------------| +| **A kép el van forgatva** | Használd a Pillow-t a forgatáshoz (`Image.rotate(angle)`) a `recognize_image` hívása előtt. | +| **Alacsony kontraszt** | Konvertáld szürkeárnyalatúra és alkalmazz adaptív küszöbölést (`Image.point(lambda p: p > 128 and 255)`). | +| **Több oldal** | Iterálj egy fájlútvonalak listáján, és fűzd össze az eredményeket. | +| **Nem latin írásrendszerek** | Cseréld le az `EXTENDED_LATIN`-t `ocr.Language.CHINESE`-ra (vagy a megfelelő nyelvre), és tartsd meg a `enable_handwritten_mode(True)` hívást. | +| **Teljesítmény aggályok** | Használd újra ugyanazt az `ocr_engine` példányt több képnél; minden alkalommal újra inicializálni többletterhet jelent. | + +### Pro tipp a memóriahasználatról + +Hogy ha több száz jegyzetet dolgozol fel egy kötegben, hívd meg a `ocr_engine.dispose()`-t a munka befejezése után. Ez felszabadítja a natív erőforrásokat, amelyeket a Python wrapper tarthat. + +## Gyors vizuális összefoglaló + +![kézírásos szöveg felismerése példa](https://example.com/handwritten-note.png "kézírásos szöveg felismerése példa") + +*The image above shows a typical handwritten note that our script can turn into plain text.* + +## Teljes működő példa (egyfájlos szkript) + +Azoknak, akik szeretik a másolás-beillesztés egyszerűségét, itt van a teljes kód újra, a magyarázó megjegyzések nélkül: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Run it with: + +```bash +python handwriting_ocr.py +``` + +Most már a konzolban látnod kell a **recognize handwritten text** kimenetet. + +## Összegzés + +Most lefedtük mindazt, amire szükséged van a **recognize handwritten text** Pythonban – egy friss **create OCR engine python** hívással kezdve, a megfelelő nyelv kiválasztásával, **turn on handwritten mode**, és végül **extract text from image** a **read handwritten notes**-hez. + +Egyetlen, önálló szkriptben egy homályos fényképről a megbeszélés vázlatáról tiszta, kereshető szöveget kapsz. Következő lépésként gondolkodj el a kimenet természetes nyelvi csővezetékbe való betáplálásán, kereshető indexben való tárolásán, vagy akár egy átíró szolgáltatásba való visszaküldésén hangalámondás generálásához. + +### Hová tovább innen? + +- **Kötegelt feldolgozás:** Csomagold a szkriptet egy ciklusba, hogy egy mappa beolvasásait kezeld. +- **Bizalmi szűrés:** Használd a `result.confidence`-t az alacsony minőségű olvasások eldobásához. +- **Alternatív könyvtárak:** Ha az `ocr` nem tökéletes, próbáld ki a `pytesseract`-ot a `--psm 13` kapcsolóval kézírási módhoz. +- **UI integráció:** Kombináld Flask vagy FastAPI-vel, hogy webes feltöltő szolgáltatást nyújts. + +Van kérdésed egy adott képfájlformátummal kapcsolatban, vagy segítségre van szükséged a modell finomhangolásához? Hagyj megjegyzést alább, és jó kódolást! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/indonesian/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..092c46a08 --- /dev/null +++ b/ocr/indonesian/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-04-26 +description: Pelajari cara mengunduh model HuggingFace Python dan mengekstrak teks + dari gambar Python sambil meningkatkan akurasi OCR Python dengan Aspose OCR Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: id +og_description: Unduh model HuggingFace Python dan tingkatkan pipeline OCR Anda. Ikuti + panduan ini untuk mengekstrak teks dari gambar Python dan meningkatkan akurasi OCR + Python. +og_title: Unduh Model HuggingFace Python – Tutorial Lengkap Peningkatan OCR +tags: +- OCR +- HuggingFace +- Python +- AI +title: Unduh model HuggingFace Python – Panduan OCR Boost Langkah demi Langkah +url: /id/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – Tutorial Lengkap Peningkatan OCR + +Pernah mencoba **download HuggingFace model python** dan merasa sedikit kebingungan? Anda tidak sendirian. Dalam banyak proyek, kendala terbesar adalah mendapatkan model yang baik ke mesin Anda dan kemudian membuat hasil OCR benar‑benar berguna. + +Dalam panduan ini kami akan membahas contoh langsung yang menunjukkan secara tepat cara **download HuggingFace model python**, mengekstrak teks dari gambar dengan **extract text from image python**, dan kemudian **improve OCR accuracy python** menggunakan post‑processor AI Aspose. Pada akhir tutorial Anda akan memiliki skrip siap‑jalankan yang mengubah gambar faktur yang berisik menjadi teks bersih dan dapat dibaca—tanpa sulap, hanya langkah‑langkah yang jelas. + +## Apa yang Anda Butuhkan + +- Python 3.9+ (kode juga berfungsi pada 3.11) +- Koneksi internet untuk mengunduh model satu kali +- Paket `asposeocrcloud` (`pip install asposeocrcloud`) +- Gambar contoh (misalnya `sample_invoice.png`) yang ditempatkan di folder yang Anda kontrol + +Itu saja—tanpa kerangka kerja berat, tanpa driver khusus GPU kecuali Anda ingin mempercepat proses. + +Sekarang, mari kita selami implementasi sebenarnya. + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## Langkah 1: Siapkan Mesin OCR dan Pilih Bahasa +*(Di sinilah kita mulai **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Mengapa ini penting:** +Mesin OCR adalah garis pertahanan pertama; memilih paket bahasa yang tepat mengurangi kesalahan pengenalan karakter secara langsung, yang merupakan bagian inti dari **improve OCR accuracy python**. + +## Langkah 2: Konfigurasikan Model AsposeAI – Mengunduh dari HuggingFace +*(Di sini kita benar‑benar **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**Apa yang terjadi di balik layar?** +Ketika `allow_auto_download` bernilai true, SDK menghubungi HuggingFace, mengambil model `Qwen2.5‑3B‑Instruct‑GGUF`, dan menyimpannya di folder yang Anda tentukan. Inilah inti dari **download huggingface model python**—SDK menangani pekerjaan berat, sehingga Anda tidak perlu menulis perintah `git clone` atau `wget` secara manual. + +*Tip pro:* Simpan `directory_model_path` di SSD untuk waktu muat yang lebih cepat; model berukuran sekitar 3 GB bahkan dalam format `int8`. + +## Langkah 3: Sambungkan Mesin AI ke Mesin OCR +*(Menghubungkan kedua bagian sehingga kita dapat **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Mengapa menggabungkannya?** +Mesin OCR memberikan teks mentah, yang mungkin berisi salah eja, baris terputus, atau tanda baca yang salah. Mesin AI berfungsi sebagai editor cerdas, membersihkan masalah‑masalah tersebut—tepat apa yang Anda butuhkan untuk **improve OCR accuracy python**. + +## Langkah 4: Jalankan OCR pada Gambar Anda +*(Momen di mana kita akhirnya **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` kini menyimpan atribut `text` dengan karakter mentah yang dilihat mesin. Dalam praktiknya Anda akan memperhatikan beberapa gangguan—mungkin “Invoice” berubah menjadi “Inv0ice” atau ada pemisahan baris di tengah kalimat. + +## Langkah 5: Bersihkan dengan AI Post‑Processor +*(Langkah ini secara langsung **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +Model AI menulis ulang teks, menerapkan perbaikan yang sadar bahasa. Karena kami menggunakan model yang di‑tune dengan instruksi dari HuggingFace, output biasanya mengalir dan siap untuk pemrosesan lanjutan. + +## Langkah 6: Tampilkan Sebelum dan Sesudah +*(Pengecekan cepat untuk melihat seberapa baik kami **extract text from image python** dan **improve OCR accuracy python**.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Output yang Diharapkan + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Perhatikan bagaimana AI memperbaiki “Inv0ice” menjadi “Invoice” dan melicinkan semua pemisahan baris yang tidak diinginkan. Itulah hasil nyata dari **improve OCR accuracy python** menggunakan model HuggingFace yang diunduh. + +## Pertanyaan yang Sering Diajukan (FAQ) + +### Apakah saya memerlukan GPU untuk menjalankan model? +Tidak. Pengaturan `gpu_layers=20` memberi tahu SDK untuk menggunakan hingga 20 lapisan GPU jika GPU yang kompatibel tersedia; jika tidak, akan kembali ke CPU. Pada laptop modern, jalur CPU masih memproses beberapa ratus token per detik—sempurna untuk parsing faktur sesekali. + +### Bagaimana jika model gagal diunduh? +Pastikan lingkungan Anda dapat mengakses `https://huggingface.co`. Jika Anda berada di belakang proxy perusahaan, atur variabel lingkungan `HTTP_PROXY` dan `HTTPS_PROXY`. SDK akan mencoba lagi secara otomatis, tetapi Anda juga dapat secara manual menjalankan `git lfs pull` repositori ke `directory_model_path`. + +### Bisakah saya mengganti model dengan yang lebih kecil? +Tentu saja. Cukup ganti `hugging_face_repo_id` dengan repositori lain (misalnya `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) dan sesuaikan `hugging_face_quantization` secara tepat. Model yang lebih kecil mengunduh lebih cepat dan menggunakan RAM lebih sedikit, meskipun Anda mungkin kehilangan sedikit kualitas koreksi. + +### Bagaimana ini membantu saya **extract text from image python** di domain lain? +Pipeline yang sama bekerja untuk kwitansi, paspor, atau catatan tulisan tangan. Satu‑satunya perubahan adalah paket bahasa (`ocr.Language.FRENCH`, dll.) dan mungkin model yang di‑tune khusus domain dari HuggingFace. + +## Bonus: Mengotomatiskan Banyak File + +Jika Anda memiliki folder berisi banyak gambar, bungkus pemanggilan OCR dalam loop sederhana: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +Penambahan kecil ini memungkinkan Anda **download huggingface model python** sekali, lalu memproses batch puluhan file—sangat cocok untuk memperluas pipeline otomatisasi dokumen Anda. + +## Kesimpulan + +Kami baru saja menelusuri contoh lengkap end‑to‑end yang menunjukkan cara **download HuggingFace model python**, **extract text from image python**, dan **improve OCR accuracy python** menggunakan OCR Cloud Aspose dan AI post‑processor. Skrip siap dijalankan, konsep‑konsep dijelaskan, dan Anda telah melihat output sebelum‑dan‑sesudah sehingga tahu bahwa ia berfungsi. + +Apa selanjutnya? Coba ganti dengan model HuggingFace yang berbeda, bereksperimen dengan paket bahasa lain, atau masukkan teks yang sudah dibersihkan ke pipeline NLP lanjutan (misalnya, ekstraksi entitas untuk item baris faktur). Tidak ada batasan, dan fondasi yang baru saja Anda bangun sudah kuat. + +Ada pertanyaan atau gambar rumit yang masih membuat OCR gagal? Tinggalkan komentar di bawah, dan mari kita selesaikan bersama. Selamat coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/indonesian/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..29f020de3 --- /dev/null +++ b/ocr/indonesian/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-04-26 +description: Unduh model OCR dengan cepat menggunakan Aspose OCR Python. Pelajari + cara mengatur direktori model, mengonfigurasi jalur model, dan cara mengunduh model + dalam beberapa baris. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: id +og_description: Unduh model OCR dalam hitungan detik dengan Aspose OCR Python. Panduan + ini menunjukkan cara mengatur direktori model, mengonfigurasi jalur model, dan cara + mengunduh model dengan aman. +og_title: Unduh Model OCR – Tutorial Python Aspose OCR Lengkap +tags: +- OCR +- Python +- Aspose +title: Unduh model OCR dengan Aspose OCR Python – Panduan Langkah demi Langkah +url: /id/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – Tutorial Lengkap Aspose OCR Python + +Pernah bertanya-tanya bagaimana cara **download ocr model** menggunakan Aspose OCR di Python tanpa harus mencari melalui dokumentasi yang tak berujung? Anda tidak sendirian. Banyak pengembang menemui kendala ketika model tidak tersedia secara lokal dan SDK mengeluarkan error yang membingungkan. Kabar baiknya? Solusinya hanya beberapa baris kode, dan Anda akan memiliki model siap pakai dalam hitungan menit. + +Dalam tutorial ini kami akan membahas semua yang perlu Anda ketahui: mulai dari mengimpor kelas yang tepat, hingga **set model directory**, cara **how to download model**, dan akhirnya memverifikasi path. Pada akhir tutorial Anda akan dapat menjalankan OCR pada gambar apa pun dengan satu pemanggilan fungsi, serta memahami opsi **configure model path** yang membuat proyek Anda tetap rapi. Tanpa basa‑basi, hanya contoh praktis yang dapat dijalankan untuk pengguna **aspose ocr python**. + +## Apa yang Akan Anda Pelajari + +- Cara mengimpor kelas Aspose OCR Cloud dengan benar. +- Langkah tepat untuk **download ocr model** secara otomatis. +- Cara **set model directory** dan **configure model path** untuk build yang dapat direproduksi. +- Cara memverifikasi bahwa model telah diinisialisasi dan di mana lokasinya di disk. +- Kesalahan umum (izin, direktori yang hilang) dan solusi cepatnya. + +### Prasyarat + +- Python 3.8+ terpasang di mesin Anda. +- Paket `asposeocrcloud` (`pip install asposeocrcloud`). +- Izin menulis ke folder tempat Anda ingin menyimpan model (misalnya, `C:\models` atau `~/ocr_models`). + +--- + +## Langkah 1: Impor Kelas Aspose OCR Cloud + +Hal pertama yang Anda perlukan adalah pernyataan import yang tepat. Ini akan menarik kelas yang mengelola konfigurasi model dan operasi OCR. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Mengapa ini penting:* `AsposeAI` adalah mesin yang akan menjalankan OCR, sementara `AsposeAIModelConfig` memberi tahu mesin **di mana** mencari model dan **apakah** ia harus mengunduhnya secara otomatis. Melewatkan langkah ini atau mengimpor modul yang salah akan menyebabkan `ModuleNotFoundError` sebelum Anda sampai pada bagian unduhan. + +--- + +## Langkah 2: Definisikan Konfigurasi Model (Set Model Directory & Configure Model Path) + +Sekarang kita memberi tahu Aspose di mana menyimpan file model. Di sinilah Anda **set model directory** dan **configure model path**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Tips & Hal-hal yang Perlu Diwaspadai** + +- **Path absolut** menghindari kebingungan ketika skrip dijalankan dari direktori kerja yang berbeda. +- Di Linux/macOS Anda dapat menggunakan `"/home/you/ocr_models"`; di Windows, beri awalan `r` agar backslash diperlakukan secara literal. +- Menetapkan `allow_auto_download="true"` adalah kunci untuk **how to download model** tanpa menulis kode tambahan. + +--- + +## Langkah 3: Buat Instance AsposeAI Menggunakan Konfigurasi + +Dengan konfigurasi siap, instantiate mesin OCR. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Mengapa ini penting:* Objek `ocr_ai` kini memegang konfigurasi yang baru saja kita definisikan. Jika model tidak ada, pemanggilan berikutnya akan memicu unduhan secara otomatis—ini inti dari **how to download model** secara hands‑off. + +--- + +## Langkah 4: Memicu Unduhan Model (Jika Diperlukan) + +Sebelum Anda dapat menjalankan OCR, pastikan model memang sudah ada di disk. Metode `is_initialized()` sekaligus memeriksa dan memaksa inisialisasi. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**Apa yang terjadi di balik layar?** + +- Pemanggilan pertama `is_initialized()` mengembalikan `False` karena folder model kosong. +- `print` memberi tahu pengguna bahwa unduhan akan segera dimulai. +- Pemanggilan kedua memaksa Aspose mengambil model dari repositori Hugging Face yang Anda tentukan sebelumnya. +- Setelah diunduh, metode ini mengembalikan `True` pada pemeriksaan selanjutnya. + +**Kasus khusus:** Jika jaringan Anda memblokir Hugging Face, Anda akan melihat exception. Dalam hal ini, unduh secara manual file zip model, ekstrak ke `directory_model_path`, dan jalankan skrip kembali. + +--- + +## Langkah 5: Laporkan Path Lokal Tempat Model Sekarang Tersedia + +Setelah unduhan selesai, Anda mungkin ingin mengetahui di mana file-file tersebut berada. Ini membantu debugging dan penyiapan pipeline CI. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Output tipikal terlihat seperti: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Sekarang Anda telah berhasil **download ocr model**, mengatur direktori, dan mengonfirmasi path. + +--- + +## Visual Overview + +Berikut diagram sederhana yang menunjukkan alur dari konfigurasi hingga model siap pakai. + +![diagram alur download ocr model yang menunjukkan konfigurasi, unduhan otomatis, dan jalur lokal](/images/download-ocr-model-flow.png) + +*Alt text mencakup kata kunci utama untuk SEO.* + +--- + +## Variasi Umum & Cara Menanganinya + +### 1. Menggunakan Repository Model yang Berbeda + +Jika Anda membutuhkan model selain `openai/gpt2`, cukup ganti nilai `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Pastikan repositori bersifat publik atau Anda memiliki token yang diperlukan yang sudah diset di lingkungan Anda. + +### 2. Menonaktifkan Unduhan Otomatis + +Kadang‑kadang Anda ingin mengontrol unduhan secara manual (misalnya, di lingkungan yang terisolasi). Setel `allow_auto_download` menjadi `"false"` dan panggil skrip unduhan khusus sebelum inisialisasi: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Mengubah Direktori Model pada Runtime + +Anda dapat mengubah path tanpa harus membuat ulang objek `AsposeAI`: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Pro Tips untuk Penggunaan di Produksi + +- **Cache model**: Simpan direktori pada drive jaringan bersama jika beberapa layanan membutuhkan model yang sama. Ini menghindari unduhan berulang. +- **Pin versi**: Repo Hugging Face dapat berubah. Untuk mengunci ke versi tertentu, tambahkan `@v1.0.0` ke ID repo (`"openai/gpt2@v1.0.0"`). +- **Izin**: Pastikan pengguna yang menjalankan skrip memiliki hak baca/tulis pada `directory_model_path`. Di Linux, biasanya `chmod 755` sudah cukup. +- **Logging**: Ganti pernyataan `print` sederhana dengan modul `logging` Python untuk observabilitas yang lebih baik pada aplikasi berskala besar. + +--- + +## Contoh Lengkap yang Siap Pakai (Copy‑Paste) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Output yang diharapkan** (eksekusi pertama akan mengunduh, eksekusi berikutnya akan melewati unduhan): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Jalankan skrip lagi; Anda hanya akan melihat baris path karena model sudah di‑cache. + +--- + +## Kesimpulan + +Kami baru saja membahas proses lengkap untuk **download ocr model** menggunakan Aspose OCR Python, menunjukkan cara **set model directory**, dan menjelaskan nuansa **configure model path**. Dengan hanya beberapa baris kode Anda dapat mengotomatisasi unduhan, menghindari langkah manual, dan menjaga pipeline OCR tetap dapat direproduksi. + +Selanjutnya, Anda mungkin ingin mengeksplorasi pemanggilan OCR sebenarnya (`ocr_ai.recognize_image(...)`) atau mencoba model Hugging Face lain untuk meningkatkan akurasi. Bagaimanapun, fondasi yang Anda bangun di sini—konfigurasi yang jelas, unduhan otomatis, dan verifikasi path—akan memudahkan integrasi di masa depan. + +Punya pertanyaan tentang kasus khusus, atau ingin berbagi bagaimana Anda menyesuaikan direktori model untuk deployment cloud? Tinggalkan komentar di bawah, dan selamat coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/indonesian/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..b047d7630 --- /dev/null +++ b/ocr/indonesian/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-26 +description: Cara memproses hasil OCR dan mengekstrak teks dengan koordinat. Pelajari + solusi langkah demi langkah menggunakan output terstruktur dan koreksi AI. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: id +og_description: Cara memproses hasil OCR dan mengekstrak teks dengan koordinat. Ikuti + tutorial komprehensif ini untuk alur kerja yang andal. +og_title: Cara Memproses Ulang OCR – Panduan Lengkap +tags: +- OCR +- Python +- AI +- Text Extraction +title: Cara Memproses Pasca OCR – Mengekstrak Teks dengan Koordinat di Python +url: /id/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara Memproses Ulang OCR – Mengekstrak Teks dengan Koordinat di Python + +Pernahkah Anda perlu **cara memproses ulang OCR** karena output mentahnya berisik atau tidak sejajar? Anda bukan satu-satunya. Dalam banyak proyek dunia nyata—pemindaian faktur, digitalisasi kwitansi, atau bahkan menambah pengalaman AR—mesin OCR memberi Anda kata‑kata mentah, tetapi Anda tetap harus membersihkannya dan melacak di mana setiap kata berada di halaman. Di sinilah mode output terstruktur yang dikombinasikan dengan post‑processor berbasis AI bersinar. + +> **Pro tip:** Jika Anda menggunakan perpustakaan OCR yang berbeda, cari mode “structured” atau “layout”; konsepnya tetap sama. + +--- + +## Prasyarat + +| Persyaratan | Mengapa penting | +|-------------|-----------------| +| Python 3.9+ | Sintaks modern dan petunjuk tipe | +| `ocr` library that supports `OutputMode.STRUCTURED` (e.g., a fictional `myocr`) | Perpustakaan `ocr` yang mendukung `OutputMode.STRUCTURED` (misalnya, `myocr` fiktif) | +| Needed for bounding‑box data | Diperlukan untuk data kotak‑pembatas | +| An AI post‑processing module (could be OpenAI, HuggingFace, or a custom model) | Modul post‑processing AI (bisa OpenAI, HuggingFace, atau model kustom) | +| Improves accuracy after OCR | Meningkatkan akurasi setelah OCR | +| An image file (`input.png`) in your working directory | File gambar (`input.png`) di direktori kerja Anda | +| The source we’ll read | Sumber yang akan kami baca | + +Jika ada yang terdengar tidak familiar, cukup instal paket placeholder dengan `pip install myocr ai‑postproc`. Kode di bawah juga menyertakan stub fallback sehingga Anda dapat menguji alur tanpa perpustakaan sebenarnya. + +--- + +## Langkah 1: Aktifkan Mode Output Terstruktur untuk Mesin OCR + +Hal pertama yang kami lakukan adalah memberi tahu mesin OCR untuk memberikan lebih dari sekadar teks biasa. Output terstruktur mengembalikan setiap kata beserta kotak‑pembatas dan skor kepercayaan, yang penting untuk **mengekstrak teks dengan koordinat** nanti. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Mengapa ini penting:* Tanpa mode terstruktur Anda hanya akan mendapatkan string panjang, dan Anda akan kehilangan informasi spasial yang dibutuhkan untuk menumpangkan teks pada gambar atau memberi analisis tata letak selanjutnya. + +--- + +## Langkah 2: Kenali Gambar dan Tangkap Kata, Kotak, serta Kepercayaan + +Sekarang kami memasukkan gambar ke dalam mesin. Hasilnya adalah sebuah objek yang berisi daftar objek kata, masing‑masing memiliki `text`, `x`, `y`, `width`, `height`, dan `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Kasus tepi:* Jika gambar kosong atau tidak dapat dibaca, `structured_result.words` akan menjadi daftar kosong. Sebaiknya periksa hal ini dan tangani dengan baik. + +--- + +## Langkah 3: Jalankan Post‑Processing Berbasis AI Sambil Mempertahankan Posisi + +Bahkan mesin OCR terbaik membuat kesalahan—misalnya “O” vs. “0” atau diakritik yang hilang. Model AI yang dilatih pada teks spesifik domain dapat memperbaiki kesalahan tersebut. Yang penting, kami mempertahankan koordinat asli sehingga tata letak spasial tetap utuh. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Mengapa kami mempertahankan koordinat:* Banyak tugas selanjutnya (misalnya, pembuatan PDF, pelabelan AR) bergantung pada penempatan yang tepat. AI hanya mengubah bidang `text`, meninggalkan `x`, `y`, `width`, `height` tidak tersentuh. + +--- + +## Langkah 4: Iterasi Kata yang Diperbaiki dan Tampilkan Teksnya dengan Koordinat + +Akhirnya, kami mengulangi kata‑kata yang telah diperbaiki dan mencetak setiap kata bersama sudut kiri‑atasnya `(x, y)`. Ini memenuhi tujuan **mengekstrak teks dengan koordinat**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Output yang diharapkan (contoh):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Setiap baris menampilkan kata yang telah diperbaiki dan lokasinya yang tepat pada gambar asli. + +--- + +## Contoh Kerja Lengkap + +Berikut adalah satu skrip yang menggabungkan semuanya. Anda dapat menyalin‑tempelnya, menyesuaikan pernyataan impor agar cocok dengan perpustakaan Anda yang sebenarnya, dan menjalankannya langsung. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Menjalankan skrip** + +```bash +python ocr_postprocess_demo.py +``` + +Jika Anda memiliki perpustakaan nyata yang terinstal, skrip akan memproses `input.png` Anda. Jika tidak, implementasi stub memungkinkan Anda melihat alur dan output yang diharapkan tanpa ketergantungan eksternal. + +--- + +## Pertanyaan yang Sering Diajukan (FAQ) + +| Pertanyaan | Jawaban | +|------------|---------| +| *Apakah ini bekerja dengan Tesseract?* | Tesseract sendiri tidak menyediakan mode terstruktur secara bawaan, tetapi pembungkus seperti `pytesseract.image_to_data` mengembalikan kotak‑pembatas yang dapat Anda masukkan ke dalam post‑processor AI yang sama. | +| *Bagaimana jika saya membutuhkan sudut kanan‑bawah alih‑alih sudut kiri‑atas?* | Setiap objek kata juga menyediakan `width` dan `height`. Hitung `x2 = x + width` dan `y2 = y + height` untuk mendapatkan sudut yang berlawanan. | +| *Bisakah saya memproses banyak gambar secara batch?* | Tentu saja. Bungkus langkah‑langkah dalam loop `for image_path in Path("folder").glob("*.png"):` dan kumpulkan hasil per file. | +| *Bagaimana saya memilih model AI untuk koreksi?* | Untuk teks umum, GPT‑2 kecil yang di‑fine‑tune pada kesalahan OCR bekerja. Untuk data spesifik domain (misalnya resep medis), latih model sequence‑to‑sequence pada data berpasangan noisy‑clean. | +| *Apakah skor kepercayaan berguna setelah koreksi AI?* | Anda masih dapat menyimpan kepercayaan asli untuk debugging, tetapi AI mungkin mengeluarkan kepercayaan sendiri jika model mendukungnya. | + +--- + +## Kasus Tepi & Praktik Terbaik + +1. **Gambar kosong atau rusak** – selalu verifikasi bahwa `structured_result.words` tidak kosong sebelum melanjutkan. +2. **Skrip non‑Latin** – pastikan mesin OCR Anda dikonfigurasi untuk bahasa target; post‑processor AI harus dilatih pada skrip yang sama. +3. **Kinerja** – koreksi AI dapat memakan biaya tinggi. Cache hasil jika Anda akan menggunakan kembali gambar yang sama, atau jalankan langkah AI secara asynchronous. +4. **Sistem koordinat** – perpustakaan OCR mungkin menggunakan asal yang berbeda (kiri‑atas vs. kiri‑bawah). Sesuaikan sesuai kebutuhan saat menumpangkan pada PDF atau kanvas. + +--- + +## Kesimpulan + +Anda kini memiliki resep menyeluruh yang solid untuk **cara memproses ulang OCR** dan secara andal **mengekstrak teks dengan koordinat**. Dengan mengaktifkan output terstruktur, mengalirkan hasil melalui lapisan koreksi AI, dan mempertahankan kotak‑pembatas asli, Anda dapat mengubah pemindaian OCR yang berisik menjadi teks bersih yang sadar spasial, siap untuk tugas selanjutnya seperti pembuatan PDF, otomatisasi entri data, atau overlay realitas tertambah. + +Siap untuk langkah selanjutnya? Coba ganti AI stub dengan panggilan OpenAI `gpt‑4o‑mini`, atau integrasikan pipeline ke dalam FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/indonesian/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..eb0226b85 --- /dev/null +++ b/ocr/indonesian/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-26 +description: Cara mengenali gambar dengan cepat menggunakan Python. Pelajari alur + kerja pengenalan gambar, pemrosesan batch, dan mengotomatiskan pengenalan gambar + menggunakan AI. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: id +og_description: Cara mengenali gambar dengan cepat menggunakan Python. Panduan ini + menjelaskan alur kerja pengenalan gambar, pemrosesan batch, dan otomatisasi menggunakan + AI. +og_title: Cara Mengenali Gambar – Mengotomatiskan Alur Pengakuan Gambar +tags: +- image-processing +- python +- ai +title: Cara Mengenali Gambar – Mengotomatiskan Alur Pengenalan Gambar +url: /id/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara Mengenali Gambar – Mengotomatiskan Pipeline Pengenalan Gambar + +Pernah bertanya‑tanya **bagaimana cara mengenali gambar** tanpa menulis ribuan baris kode? Anda tidak sendirian—banyak pengembang menemui hal yang sama saat pertama kali harus memproses puluhan atau ratusan foto. Kabar baiknya? Dengan beberapa langkah rapi Anda dapat membuat pipeline pengenalan gambar yang lengkap, yang memproses batch, menjalankan, dan membersihkan semuanya secara otomatis. + +Dalam tutorial ini kami akan menelusuri contoh lengkap yang dapat dijalankan yang menunjukkan **bagaimana cara mem-batch gambar**, memberi setiap gambar ke mesin AI, memproses hasilnya, dan akhirnya melepaskan sumber daya. Pada akhir tutorial Anda akan memiliki skrip mandiri yang dapat Anda masukkan ke proyek apa pun, baik Anda sedang membangun penanda foto, sistem kontrol kualitas, atau generator dataset riset. + +## Apa yang Akan Anda Pelajari + +- **Bagaimana cara mengenali gambar** menggunakan mesin AI tiruan (pola ini identik untuk layanan nyata seperti TensorFlow, PyTorch, atau API cloud). +- Cara membangun **pipeline pengenalan gambar** yang menangani batch secara efisien. +- Cara terbaik untuk **mengotomatiskan pengenalan gambar** sehingga Anda tidak perlu menulis loop manual untuk setiap file. +- Tips untuk menskalakan pipeline dan membebaskan sumber daya dengan aman. + +> **Prasyarat:** Python 3.8+, pemahaman dasar tentang fungsi dan loop, serta beberapa file gambar (atau path) yang ingin Anda proses. Tidak ada pustaka eksternal yang diperlukan untuk contoh inti, tetapi kami akan menyebutkan di mana Anda dapat menyambungkan SDK AI nyata. + +![Diagram cara mengenali gambar dalam pipeline pemrosesan batch](pipeline.png "Diagram cara mengenali gambar") + +## Langkah 1: Batch Gambar Anda – Cara Membuat Batch Gambar Secara Efisien + +Sebelum AI melakukan pekerjaan berat, Anda memerlukan kumpulan gambar untuk diberi makan. Anggap ini seperti daftar belanjaan; mesin nanti akan mengambil tiap item satu per satu. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Mengapa batch?** +Batching mengurangi jumlah kode boilerplate yang harus Anda tulis dan membuat penambahan paralelisme menjadi sangat mudah. Jika Anda pernah perlu memproses 10 000 foto, Anda hanya mengubah sumber `image_batch`—sisanya tetap tidak berubah. + +## Langkah 2: Jalankan Pipeline Pengenalan Gambar (Mengenali Gambar dengan AI) + +Sekarang kita menghubungkan batch ke pengenal sebenarnya. Dalam skenario dunia nyata Anda mungkin memanggil `torchvision.models` atau endpoint cloud; di sini kami meniru perilakunya agar tutorial tetap mandiri. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Penjelasan:** +- `engine.recognize_image` adalah inti dari **pipeline pengenalan gambar**; ini bisa menjadi panggilan ke model deep‑learning atau REST API. +- `postprocessor.run` mendemonstrasikan **mengotomatiskan pengenalan gambar** dengan menormalkan prediksi mentah menjadi kamus bersih yang dapat Anda simpan atau alirkan. +- Kami mengumpulkan setiap kamus `corrected` ke dalam `recognized_results` sehingga langkah selanjutnya (misalnya, penyisipan ke basis data) menjadi sederhana. + +## Langkah 3: Post‑proses dan Simpan – Mengotomatiskan Hasil Pengenalan Gambar + +Setelah Anda memiliki daftar prediksi yang rapi, biasanya Anda ingin menyimpannya. Contoh di bawah menulis file CSV; silakan ganti dengan basis data atau antrian pesan bila diperlukan. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Mengapa CSV?** +CSV dapat dibaca secara universal—Excel, pandas, bahkan editor teks biasa dapat membukanya. Jika Anda kemudian perlu **mengotomatiskan pengenalan gambar** dalam skala besar, ganti blok penulisan dengan penyisipan massal ke data lake Anda. + +## Langkah 4: Bersihkan – Lepaskan Sumber Daya AI dengan Aman + +Banyak SDK AI mengalokasikan memori GPU atau memunculkan thread pekerja. Lupa membebaskannya dapat menyebabkan kebocoran memori dan crash yang tidak diinginkan. Meskipun objek tiruan kami tidak memerlukannya, kami akan menunjukkan pola yang tepat. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +Menjalankan skrip akan mencetak konfirmasi ramah, memberi tahu Anda bahwa pipeline telah selesai dengan bersih. + +## Skrip Lengkap yang Berfungsi + +Menggabungkan semuanya, berikut adalah program lengkap yang siap disalin‑tempel: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Output yang Diharapkan + +Saat Anda menjalankan skrip (dengan asumsi tiga path placeholder ada), Anda akan melihat sesuatu seperti: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +Dan file `recognition_results.csv` yang dihasilkan akan berisi: + +| image | label | confidence | +|---------------------|-------|------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Kesimpulan + +Anda kini memiliki contoh menyeluruh, end‑to‑end tentang **cara mengenali gambar** dengan Python, lengkap dengan **pipeline pengenalan gambar**, penanganan batch, dan post‑proses otomatis. Polanya dapat diskalakan: ganti kelas tiruan dengan model nyata, beri batch `image_batch` yang lebih besar, dan Anda memiliki solusi siap produksi. + +Ingin melangkah lebih jauh? Coba langkah selanjutnya berikut: + +- Ganti `MockEngine` dengan model TensorFlow atau PyTorch untuk prediksi nyata. +- Paralelkan loop dengan `concurrent.futures.ThreadPoolExecutor` untuk mempercepat batch besar. +- Sambungkan penulis CSV ke bucket penyimpanan cloud untuk **mengotomatiskan pengenalan gambar** di antara pekerja terdistribusi. + +Silakan bereksperimen, pecahkan masalah, dan perbaiki—itulah cara menguasai pipeline pengenalan gambar secara sejati. Jika Anda menemui kendala atau memiliki ide perbaikan, tinggalkan komentar di bawah. Selamat coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/indonesian/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..2e8b6881c --- /dev/null +++ b/ocr/indonesian/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-04-26 +description: Sembunyikan nomor kartu kredit dengan cepat menggunakan post‑processing + OCR AsposeAI. Pelajari kepatuhan PCI, penyamaran dengan ekspresi reguler, dan sanitasi + data dalam tutorial langkah demi langkah. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: id +og_description: Menyamarkan nomor kartu kredit dalam hasil OCR dengan AsposeAI. Tutorial + ini mencakup kepatuhan PCI, penyamaran dengan ekspresi reguler, dan sanitasi data. +og_title: Menyamarkan Nomor Kartu Kredit – Panduan Lengkap Pemrosesan Pasca OCR dengan + Python +tags: +- OCR +- Python +- security +title: Menyamarkan Nomor Kartu Kredit dalam Output OCR – Panduan Python Lengkap +url: /id/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Menyamarkan Nomor Kartu Kredit – Panduan Python Lengkap + +Pernahkah Anda perlu **menyamarkan nomor kartu kredit** dalam teks yang berasal langsung dari mesin OCR? Anda bukan satu-satunya. Dalam industri yang diatur, mengungkapkan PAN (Primary Account Number) lengkap dapat menimbulkan masalah dengan auditor kepatuhan PCI. Kabar baik? Dengan beberapa baris Python dan hook post‑processing AsposeAI, Anda dapat secara otomatis menyembunyikan delapan digit tengah dan tetap aman. + +Dalam tutorial ini kami akan membahas skenario dunia nyata: menjalankan OCR pada gambar struk, lalu menerapkan fungsi **OCR post‑processing** khusus yang menyanitasi data PCI apa pun. Pada akhir tutorial Anda akan memiliki potongan kode yang dapat digunakan kembali dan dapat ditempatkan ke dalam alur kerja AsposeAI mana pun, serta beberapa tip praktis untuk menangani kasus pinggir dan menskalakan solusi. + +## Apa yang Akan Anda Pelajari + +- Cara mendaftarkan post‑processor khusus dengan **AsposeAI**. +- Mengapa pendekatan **regular expression masking** cepat dan dapat diandalkan. +- Dasar‑dasar **PCI compliance** terkait sanitasi data. +- Cara memperluas pola untuk berbagai format kartu atau nomor internasional. +- Output yang diharapkan dan cara memverifikasi bahwa penyamaran berhasil. + +> **Prasyarat** – Anda harus memiliki lingkungan Python 3 yang berfungsi, paket Aspose.AI for OCR terpasang (`pip install aspose-ocr`), dan contoh gambar (misalnya `receipt.png`) yang berisi nomor kartu kredit. Tidak ada layanan eksternal lain yang diperlukan. + +--- + +## Langkah 1: Definisikan Post‑Processor yang Menyamarkan Nomor Kartu Kredit + +Inti solusi berada dalam fungsi kecil yang menerima hasil OCR, menjalankan rutin **regular expression masking**, dan mengembalikan teks yang telah disanitasi. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Mengapa ini berhasil:** +- Regex `(\d{4})\d{8}(\d{4})` cocok tepat dengan 16 digit berurutan, format umum untuk Visa, MasterCard, dan banyak lainnya. +- Dengan menangkap empat digit pertama dan terakhir (`\1` dan `\2`) kami mempertahankan cukup informasi untuk debugging sambil mematuhi aturan **PCI compliance** yang melarang penyimpanan PAN lengkap. +- Substitusi `\1****\2` menyembunyikan delapan digit tengah yang sensitif, mengubah `1234567812345678` menjadi `1234****5678`. + +> **Pro tip:** Jika Anda perlu mendukung nomor American Express 15‑digit, tambahkan pola kedua seperti `r'(\d{4})\d{6}(\d{5})'` dan jalankan kedua penggantian secara berurutan. + +--- + +## Langkah 2: Inisialisasi Mesin AsposeAI + +Sebelum kita dapat menempelkan post‑processor kami, kita memerlukan sebuah instance dari mesin OCR. AsposeAI menyertakan model OCR dan API sederhana untuk pemrosesan khusus. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Mengapa inisialisasi di sini?** +Membuat objek `AsposeAI` sekali dan menggunakannya kembali pada banyak gambar mengurangi beban. Mesin juga menyimpan cache model bahasa, yang mempercepat panggilan berikutnya—berguna saat Anda memindai batch struk. + +--- + +## Langkah 3: Daftarkan Fungsi Penyaringan Kustom + +AsposeAI menyediakan metode `set_post_processor` yang memungkinkan Anda menyambungkan callable apa pun. Kami mengirim fungsi `mask_pci` bersama kamus pengaturan opsional (kosong untuk saat ini). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**Apa yang terjadi di balik layar?** +Ketika Anda kemudian memanggil `run_postprocessor`, AsposeAI akan menyerahkan hasil OCR mentah ke `mask_pci`. Fungsi tersebut menerima objek ringan (`data`) yang berisi teks yang dikenali, dan Anda mengembalikan string baru. Desain ini menjaga inti OCR tetap tidak tersentuh sambil memungkinkan Anda menegakkan kebijakan **data sanitization** di satu tempat. + +--- + +## Langkah 4: Jalankan OCR pada Gambar Resi + +Sekarang mesin tahu cara membersihkan output, kami memberikannya sebuah gambar. Untuk keperluan tutorial ini kami mengasumsikan Anda sudah memiliki objek `engine` yang dikonfigurasi dengan bahasa dan pengaturan resolusi yang tepat. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Tip:** Jika Anda belum memiliki objek yang sudah dikonfigurasi, Anda dapat membuatnya dengan: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +Pemanggilan `recognize_image` mengembalikan objek yang atribut `text`‑nya berisi string mentah yang belum disamarkan. + +--- + +## Langkah 5: Terapkan Post‑Processor yang Terdaftar + +Dengan data OCR mentah di tangan, kami menyerahkannya ke instance AI. Mesin secara otomatis menjalankan fungsi `mask_pci` yang kami daftarkan sebelumnya. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Mengapa menggunakan `run_postprocessor` alih‑alih memanggil fungsi secara manual?** +Hal ini menjaga alur kerja tetap konsisten, terutama ketika Anda memiliki beberapa post‑processor (misalnya pemeriksaan ejaan, deteksi bahasa). AsposeAI menempatkannya dalam urutan pendaftaran, menjamin output yang deterministik. + +--- + +## Langkah 6: Verifikasi Output yang Disanitasi + +Akhirnya, mari cetak teks yang telah disanitasi dan pastikan bahwa semua nomor kartu kredit telah disamarkan dengan benar. + +```python +print(final_result.text) +``` + +**Output yang diharapkan** (kutipan): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Jika struk tidak mengandung nomor kartu, teks tetap tidak berubah—tidak ada yang perlu disamarkan, tidak ada yang perlu dikhawatirkan. + +--- + +## Menangani Kasus Pinggir dan Variasi Umum + +### Banyak Nomor Kartu dalam Satu Dokumen +Jika sebuah struk mencakup lebih dari satu PAN (misalnya kartu loyalitas plus kartu pembayaran), regex dijalankan secara global, menyamarkan semua kecocokan secara otomatis. Tidak perlu kode tambahan. + +### Format Non‑Standar +Kadang OCR menyisipkan spasi atau tanda hubung (`1234 5678 1234 5678` atau `1234-5678-1234-5678`). Perluas pola untuk mengabaikan karakter tersebut: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +Penambahan `[ -]?` memungkinkan spasi atau tanda hubung opsional di antara blok digit. + +### Kartu Internasional +Untuk PAN 19‑digit yang digunakan di beberapa wilayah, Anda dapat memperluas pola: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Ingat bahwa **PCI compliance** tetap mengharuskan penyamaran digit tengah, terlepas dari panjangnya. + +### Mencatat Nilai yang Disamarkan (Opsional) +Jika Anda memerlukan jejak audit, kirimkan flag melalui `custom_settings` dan sesuaikan fungsi: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Kemudian daftarkan dengan: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Contoh Lengkap yang Siap Pakai (Copy‑Paste Ready) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Menjalankan skrip ini pada struk yang berisi `4111111111111111` akan menghasilkan: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +Itulah seluruh pipeline—dari OCR mentah hingga **data sanitization**—dibungkus dalam beberapa baris Python yang bersih. + +--- + +## Kesimpulan + +Kami baru saja menunjukkan cara **menyamarkan nomor kartu kredit** dalam hasil OCR menggunakan hook post‑processing AsposeAI, rutin regular‑expression yang ringkas, dan beberapa tip praktik terbaik untuk **PCI compliance**. Solusinya sepenuhnya mandiri, bekerja dengan gambar apa pun yang dapat dibaca mesin OCR, dan dapat diperluas untuk mencakup format kartu yang lebih kompleks atau kebutuhan pencatatan. + +Siap untuk langkah selanjutnya? Cobalah menggabungkan penyamaran ini dengan rutinitas **penyisipan ke database** yang hanya menyimpan empat digit terakhir untuk referensi, atau integrasikan **batch processor** yang memindai seluruh folder struk semalaman. Anda juga dapat menjelajahi tugas **OCR post‑processing** lain seperti standarisasi alamat atau deteksi bahasa—semuanya mengikuti pola yang sama seperti yang kami gunakan di sini. + +Ada pertanyaan tentang kasus pinggir, kinerja, atau cara menyesuaikan kode untuk perpustakaan OCR lain? Tinggalkan komentar di bawah, dan mari teruskan diskusi. Selamat coding, dan tetap aman! + +![Diagram yang menggambarkan cara kerja penyamaran nomor kartu kredit dalam pipeline OCR](https://example.com/images/ocr-mask-flow.png "Diagram alur penyamaran post‑processing OCR") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/indonesian/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..166516548 --- /dev/null +++ b/ocr/indonesian/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-04-26 +description: Pelajari cara mengukur waktu inferensi di Python, memuat model GGUF dari + Hugging Face, dan mengoptimalkan penggunaan GPU untuk hasil yang lebih cepat. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: id +og_description: Ukur waktu inferensi di Python dengan memuat model GGUF dari Hugging + Face dan menyesuaikan lapisan GPU untuk kinerja optimal. +og_title: Ukur Waktu Inferensi – Muat Model GGUF & Optimalkan GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Ukur Waktu Inferensi – Muat Model GGUF & Optimalkan GPU +url: /id/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ukur Waktu Inferensi – Muat Model GGUF & Optimalkan GPU + +Pernah perlu **mengukur waktu inferensi** untuk model bahasa besar tetapi tidak yakin harus mulai dari mana? Anda tidak sendirian—banyak pengembang mengalami hal yang sama ketika pertama kali menarik file GGUF dari Hugging Face dan mencoba menjalankannya pada setup CPU/GPU campuran. + +Dalam panduan ini kami akan menjelaskan **cara memuat model GGUF**, mengkonfigurasikannya untuk Hugging Face, dan **mengukur waktu inferensi** dengan potongan kode Python yang bersih. Sepanjang jalan kami juga akan menunjukkan **cara mengoptimalkan inferensi GPU** sehingga proses Anda secepat mungkin. Tanpa basa‑basi, hanya solusi praktis end‑to‑end yang dapat Anda salin‑tempel hari ini. + +## Apa yang Akan Anda Pelajari + +- Cara **mengonfigurasi model HuggingFace** dengan `AsposeAIModelConfig`. +- Langkah tepat untuk **memuat model GGUF** (kuantisasi `fp16`) dari hub Hugging Face. +- Pola yang dapat digunakan kembali untuk **mengukur waktu kode Python** di sekitar panggilan inferensi. +- Tips untuk **mengoptimalkan inferensi GPU** dengan menyesuaikan `gpu_layers`. +- Output yang diharapkan dan cara memverifikasi bahwa waktu Anda masuk akal. + +### Prerequisites + +| Persyaratan | Mengapa penting | +|-------------|-----------------| +| Python 3.9+ | Sintaks modern dan petunjuk tipe. | +| `asposeai` package (or the equivalent SDK) | Menyediakan `AsposeAI` dan `AsposeAIModelConfig`. | +| Access to the Hugging Face repo `bartowski/Qwen2.5-3B-Instruct-GGUF` | Model GGUF yang akan kami muat. | +| A GPU with at least 8 GB VRAM (optional but recommended) | Memungkinkan langkah **optimalkan inferensi GPU**. | + +Jika Anda belum menginstal SDK, jalankan: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![measure inference time diagram](https://example.com/measure-inference-time.png){alt="diagram mengukur waktu inferensi"} + +## Langkah 1: Muat Model GGUF – Konfigurasikan Model HuggingFace + +Hal pertama yang Anda butuhkan adalah objek konfigurasi yang tepat yang memberi tahu Aspose AI dari mana mengambil model dan bagaimana memperlakukannya. Di sinilah kami **memuat model GGUF** dan **mengonfigurasi parameter model huggingface**. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Mengapa ini penting:** +- `hugging_face_repo_id` menunjuk ke file GGUF yang tepat di Hub. +- `fp16` mengurangi bandwidth memori sambil mempertahankan sebagian besar fidelitas model. +- `gpu_layers` adalah pengaturan yang Anda ubah ketika ingin **mengoptimalkan performa inferensi GPU**; lebih banyak lapisan di GPU biasanya berarti latensi lebih cepat, asalkan Anda memiliki cukup VRAM. + +## Langkah 2: Buat Instance Aspose AI + +Sekarang model telah dijelaskan, kami membuat objek `AsposeAI`. Langkah ini sederhana, tetapi di sinilah SDK benar‑benar mengunduh file GGUF (jika belum di‑cache) dan menyiapkan runtime. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Tips pro:** Jalankan pertama akan memakan beberapa detik lebih lama karena model sedang diunduh dan dikompilasi untuk GPU. Jalankan berikutnya sangat cepat. + +## Langkah 3: Jalankan Inferensi dan **Ukur Waktu Inferensi** + +Berikut inti tutorial: membungkus panggilan inferensi dengan `time.time()` untuk **mengukur waktu inferensi**. Kami juga memberikan hasil OCR kecil hanya agar contoh tetap mandiri. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Apa yang akan Anda lihat:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Jika angkanya terasa tinggi, kemungkinan Anda menjalankan sebagian besar lapisan di CPU. Itu membawa kita ke langkah berikutnya. + +## Langkah 4: **Optimalkan Inferensi GPU** – Sesuaikan `gpu_layers` + +Kadang‑kadang nilai default `gpu_layers=40` terlalu agresif (menyebabkan OOM) atau terlalu konservatif (menurunkan performa). Berikut loop cepat yang dapat Anda gunakan untuk menemukan titik optimal: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Mengapa ini berhasil:** +- Setiap panggilan membangun ulang runtime dengan alokasi GPU yang berbeda, memungkinkan Anda melihat trade‑off latensi secara langsung. +- Loop ini juga menunjukkan **mengukur waktu kode python** secara dapat digunakan kembali, yang dapat Anda sesuaikan untuk tes performa lainnya. + +Output tipikal pada RTX 3080 16 GB mungkin terlihat seperti: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +Dari situ, Anda akan memilih `gpu_layers=40` sebagai titik optimal untuk perangkat keras ini. + +## Contoh Kerja Lengkap + +Menggabungkan semuanya, berikut skrip tunggal yang dapat Anda letakkan ke dalam file (`measure_inference.py`) dan jalankan: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Jalankan dengan: + +```bash +python measure_inference.py +``` + +Anda akan melihat latensi kurang dari satu detik pada GPU yang layak, mengonfirmasi bahwa Anda berhasil **mengukur waktu inferensi** dan **mengoptimalkan inferensi GPU**. + +--- + +## Pertanyaan yang Sering Diajukan (FAQ) + +**T: Apakah ini bekerja dengan format kuantisasi lain?** +J: Tentu saja. Ganti `hugging_face_quantization="int8"` (atau `q4_0`, dll.) dalam konfigurasi dan jalankan kembali benchmark. Harapkan trade‑off: penggunaan memori lebih rendah vs. penurunan akurasi sedikit. + +**T: Bagaimana jika saya tidak memiliki GPU?** +J: Setel `gpu_layers=0`. Kode akan sepenuhnya beralih ke CPU, dan Anda tetap dapat **mengukur waktu inferensi**—hanya harapkan angka yang lebih tinggi. + +**T: Bisakah saya mengukur waktu hanya pada forward pass model, tanpa post‑processing?** +J: Ya. Panggil `ai_engine.run_model(...)` (atau metode setara) secara langsung dan bungkus panggilan tersebut dengan `time.time()`. Pola untuk **mengukur waktu kode python** tetap sama. + +--- + +## Kesimpulan + +Anda kini memiliki solusi lengkap, siap salin‑tempel untuk **mengukur waktu inferensi** pada model GGUF, **memuat model gguf** dari Hugging Face, dan menyetel **optimalkan inferensi GPU**. Dengan menyesuaikan `gpu_layers` dan bereksperimen dengan kuantisasi, Anda dapat mengoptimalkan setiap milidetik performa. + +Selanjutnya, Anda mungkin ingin: + +- Mengintegrasikan logika pengukuran waktu ini ke dalam pipeline CI untuk menangkap regresi. +- Mengeksplorasi inferensi batch untuk meningkatkan throughput lebih lanjut. +- Menggabungkan model dengan pipeline OCR nyata alih‑alih teks dummy yang kami gunakan di sini. + +Selamat coding, semoga angka latensi Anda selalu rendah! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/indonesian/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..ed405def2 --- /dev/null +++ b/ocr/indonesian/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-04-26 +description: Mengenali teks tulisan tangan menggunakan mesin OCR Python. Pelajari + cara mengekstrak teks dari gambar, mengaktifkan mode tulisan tangan, dan membaca + catatan tulisan tangan dengan cepat. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: id +og_description: Mengenali teks tulisan tangan dengan Python. Tutorial ini menunjukkan + cara mengekstrak teks dari gambar, mengaktifkan mode tulisan tangan, dan membaca + catatan tulisan tangan menggunakan mesin OCR sederhana. +og_title: Mengenali teks tulisan tangan di Python – Panduan OCR Lengkap +tags: +- OCR +- Python +- Handwriting Recognition +title: Mengenali teks tulisan tangan di Python – Tutorial Mesin OCR +url: /id/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# mengenali teks tulisan tangan di Python – Tutorial Mesin OCR + +Pernah butuh **mengenali teks tulisan tangan** tetapi merasa terjebak pada “dari mana saya mulai?”? Anda tidak sendirian. Baik Anda mendigitalkan coretan rapat atau mengambil data dari formulir yang dipindai, mendapatkan hasil OCR yang dapat diandalkan bisa terasa seperti mengejar unicorn. + +Berita baik: dengan hanya beberapa baris Python Anda dapat **extract text from image** file, **turn on handwritten mode**, dan akhirnya **read handwritten notes** tanpa mencari perpustakaan yang obscure. Dalam panduan ini kami akan melangkah melalui seluruh proses, dari pengaturan gaya **create OCR engine python** hingga mencetak hasil di layar. + +## Apa yang Akan Anda Pelajari + +- Cara membuat instance **create OCR engine python** menggunakan paket `ocr`. +- Pengaturan bahasa mana yang memberi Anda dukungan tulisan tangan bawaan. +- Pemanggilan tepat untuk **turn on handwritten mode** sehingga mesin tahu Anda menangani tulisan kursif. +- Cara memberi gambar catatan dan **recognize handwritten text** darinya. +- Tips untuk menangani berbagai format gambar, memecahkan masalah umum, dan memperluas solusi. + +Tanpa basa-basi, tanpa dead‑ends “see the docs”—hanya skrip lengkap yang dapat dijalankan yang dapat Anda salin‑tempel dan uji hari ini. + +## Prasyarat + +1. Python 3.8+ terpasang (kode menggunakan f‑strings). +2. Pustaka `ocr` hipotetik (`pip install ocr‑engine` – ganti dengan nama paket nyata yang Anda gunakan). +3. File gambar yang jelas dari catatan tulisan tangan (JPEG, PNG, atau TIFF). +4. Sedikit rasa ingin tahu—semua hal lainnya dibahas di bawah. + +> **Pro tip:** Jika gambar Anda berisik, jalankan langkah pra‑pemrosesan cepat dengan Pillow (mis., `Image.open(...).convert('L')`) sebelum mengirimnya ke mesin OCR. Ini sering meningkatkan akurasi. + +## Cara mengenali teks tulisan tangan dengan Python + +Berikut adalah skrip lengkap yang **creates OCR engine python** objects, configures them for handwriting, and prints the extracted string. Simpan sebagai `handwriting_ocr.py` dan jalankan dari terminal Anda. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Output yang Diharapkan + +Ketika skrip berhasil dijalankan, Anda akan melihat sesuatu seperti: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Jika mesin OCR tidak dapat mendeteksi karakter apa pun, bidang `text` akan menjadi string kosong. Dalam kasus itu, periksa kembali kualitas gambar atau coba pemindaian dengan resolusi lebih tinggi. + +## Penjelasan Langkah‑per‑Langkah + +### Langkah 1 – instance **create OCR engine python** + +Kelas `OcrEngine` adalah titik masuk. Anggaplah seperti buku catatan kosong—tidak ada yang terjadi sampai Anda memberi tahu bahasa yang diharapkan dan apakah Anda menangani tulisan tangan. + +### Langkah 2 – Pilih bahasa yang mendukung tulisan tangan + +`ocr.Language.EXTENDED_LATIN` bukan hanya “English”. Ia menggabungkan sekumpulan skrip berbasis Latin dan, yang penting, menyertakan model yang dilatih pada contoh tulisan kursif. Melewatkan langkah ini sering menghasilkan output berantakan karena mesin default ke model teks cetak. + +### Langkah 3 – **turn on handwritten mode** + +Memanggil `enable_handwritten_mode(True)` mengubah flag internal. Mesin kemudian beralih ke jaringan saraf yang disetel untuk spasi tidak teratur dan lebar goresan variabel yang Anda lihat pada catatan dunia nyata. Lupa baris ini adalah kesalahan umum; mesin akan memperlakukan coretan Anda sebagai noise. + +### Langkah 4 – Beri gambar dan **recognize handwritten text** + +`recognize_image` melakukan pekerjaan berat: ia mempraproses bitmap, menjalankannya melalui model tulisan tangan, dan mengembalikan objek dengan atribut `text`. Anda juga dapat memeriksa `handwritten_result.confidence` jika membutuhkan metrik kualitas. + +### Langkah 5 – Cetak hasil dan **read handwritten notes** + +`print(handwritten_result.text)` adalah cara paling sederhana untuk memverifikasi bahwa Anda berhasil **extract text from image**. Dalam produksi Anda mungkin akan menyimpan string ke basis data atau mengirimnya ke layanan lain. + +## Menangani Kasus Edge & Variasi Umum + +| Situasi | Apa yang Harus Dilakukan | +|-----------|------------| +| **Gambar diputar** | Gunakan Pillow untuk memutar (`Image.rotate(angle)`) sebelum memanggil `recognize_image`. | +| **Kontras rendah** | Ubah menjadi grayscale dan terapkan threshold adaptif (`Image.point(lambda p: p > 128 and 255)`). | +| **Beberapa halaman** | Loop melalui daftar path file dan gabungkan hasil. | +| **Skrip non‑Latin** | Ganti `EXTENDED_LATIN` dengan `ocr.Language.CHINESE` (atau yang sesuai) dan pertahankan `enable_handwritten_mode(True)`. | +| **Kekhawatiran performa** | Gunakan kembali instance `ocr_engine` yang sama untuk banyak gambar; menginisialisasinya setiap kali menambah overhead. | + +### Pro tip tentang penggunaan memori + +Jika Anda memproses ratusan catatan dalam satu batch, panggil `ocr_engine.dispose()` setelah selesai. Ini membebaskan sumber daya native yang mungkin dipegang oleh wrapper Python. + +## Ringkasan Visual Cepat + +![contoh mengenali teks tulisan tangan](https://example.com/handwritten-note.png "contoh mengenali teks tulisan tangan") + +*Gambar di atas menunjukkan catatan tulisan tangan tipikal yang dapat diubah skrip kami menjadi teks biasa.* + +## Contoh Kerja Penuh (Skrip Satu‑File) + +Untuk mereka yang suka kesederhanaan copy‑paste, berikut seluruhnya lagi tanpa komentar penjelasan: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Jalankan dengan: + +```bash +python handwriting_ocr.py +``` + +Anda sekarang harus melihat output **recognize handwritten text** di konsol Anda. + +## Kesimpulan + +Kami baru saja membahas semua yang Anda butuhkan untuk **recognize handwritten text** di Python—dimulai dari pemanggilan **create OCR engine python** yang baru, memilih bahasa yang tepat, **turn on handwritten mode**, dan akhirnya **extract text from image** untuk **read handwritten notes**. + +Dalam satu skrip mandiri Anda dapat beralih dari foto buram coretan rapat ke teks bersih yang dapat dicari. Selanjutnya, pertimbangkan mengirim output ke pipeline bahasa alami, menyimpannya di indeks yang dapat dicari, atau bahkan mengirimnya kembali ke layanan transkripsi untuk menghasilkan suara. + +### Kemana Selanjutnya? + +- **Pemrosesan batch:** Bungkus skrip dalam loop untuk menangani folder pemindaian. +- **Penyaringan kepercayaan:** Gunakan `result.confidence` untuk membuang bacaan berkualitas rendah. +- **Pustaka alternatif:** Jika `ocr` tidak cocok, jelajahi `pytesseract` dengan `--psm 13` untuk mode tulisan tangan. +- **Integrasi UI:** Gabungkan dengan Flask atau FastAPI untuk menawarkan layanan unggah berbasis web. + +Memiliki pertanyaan tentang format gambar tertentu atau butuh bantuan menyetel model? Tinggalkan komentar di bawah, dan selamat coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/italian/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..2dbd314a6 --- /dev/null +++ b/ocr/italian/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,195 @@ +--- +category: general +date: 2026-04-26 +description: Impara come scaricare il modello HuggingFace in Python ed estrarre testo + da un'immagine in Python migliorando l'accuratezza OCR in Python con Aspose OCR + Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: it +og_description: Scarica il modello HuggingFace per Python e potenzia il tuo pipeline + OCR. Segui questa guida per estrarre testo da un'immagine con Python e migliorare + l'accuratezza dell'OCR con Python. +og_title: Scarica modello HuggingFace Python – Tutorial completo di miglioramento + OCR +tags: +- OCR +- HuggingFace +- Python +- AI +title: Scarica modello HuggingFace Python – Guida passo‑passo per potenziare OCR +url: /it/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – Tutorial completo di miglioramento OCR + +Hai mai provato a **download HuggingFace model python** e ti sei sentito un po' perso? Non sei l'unico. In molti progetti il collo di bottiglia più grande è ottenere un buon modello sulla tua macchina e poi rendere i risultati OCR realmente utili. + +In questa guida percorreremo un esempio pratico che ti mostra esattamente come **download HuggingFace model python**, estrarre testo da un'immagine con **extract text from image python**, e poi **improve OCR accuracy python** usando il post‑processore AI di Aspose. Alla fine avrai uno script pronto all'uso che trasforma un'immagine di fattura rumorosa in testo pulito e leggibile—niente magia, solo passaggi chiari. + +## Di cosa avrai bisogno + +- Python 3.9+ (il codice funziona anche su 3.11) +- Una connessione internet per il download una tantum del modello +- Il pacchetto `asposeocrcloud` (`pip install asposeocrcloud`) +- Un'immagine di esempio (ad es., `sample_invoice.png`) posizionata in una cartella di tua scelta + +Questo è tutto—nessun framework pesante, nessun driver specifico per GPU a meno che tu non voglia accelerare le cose. + +Ora, immergiamoci nell'implementazione reale. + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## Passo 1: Configura il motore OCR e scegli una lingua +*(Qui è dove iniziamo a **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Perché è importante:** +Il motore OCR è la prima linea di difesa; scegliere il pacchetto lingua corretto riduce subito gli errori di riconoscimento dei caratteri, che è una parte fondamentale di **improve OCR accuracy python**. + +## Passo 2: Configura il modello AsposeAI – Download da HuggingFace +*(Qui effettuiamo realmente il **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**Cosa succede dietro le quinte?** +Quando `allow_auto_download` è true, l'SDK contatta HuggingFace, scarica il modello `Qwen2.5‑3B‑Instruct‑GGUF` e lo salva nella cartella specificata. Questo è il fulcro di **download huggingface model python**—l'SDK si occupa del lavoro pesante, così non devi scrivere comandi `git clone` o `wget`. +*Consiglio:* Mantieni `directory_model_path` su un SSD per tempi di caricamento più rapidi; il modello è circa 3 GB anche in forma `int8`. + +## Passo 3: Collega il motore AI al motore OCR +*(Collegando i due componenti così possiamo **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Perché collegarli?** +Il motore OCR ci fornisce testo grezzo, che può contenere errori di ortografia, linee interrotte o punteggiatura sbagliata. Il motore AI agisce come un editor intelligente, pulendo questi problemi—esattamente ciò di cui hai bisogno per **improve OCR accuracy python**. + +## Passo 4: Esegui OCR sulla tua immagine +*(Il momento in cui finalmente **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` ora contiene un attributo `text` con i caratteri grezzi visti dal motore. In pratica noterai qualche piccolo intoppo—magari “Invoice” trasformato in “Inv0ice” o un'interruzione di riga nel mezzo di una frase. + +## Passo 5: Pulizia con il post‑processore AI +*(Questo passo migliora direttamente **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +Il modello AI riscrive il testo, applicando correzioni consapevoli della lingua. Poiché abbiamo usato un modello istruzione‑tuned da HuggingFace, l'output è solitamente fluido e pronto per l'elaborazione successiva. + +## Passo 6: Mostra il prima e dopo +*(Un rapido controllo di coerenza per vedere quanto bene **extract text from image python** e **improve OCR accuracy python**.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Output previsto + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Nota come l'AI ha corretto “Inv0ice” in “Invoice” e ha eliminato le interruzioni di riga indesiderate. Questo è il risultato tangibile di **improve OCR accuracy python** usando un modello HuggingFace scaricato. + +## Domande frequenti (FAQ) + +### Ho bisogno di una GPU per eseguire il modello? + +No. L'impostazione `gpu_layers=20` indica all'SDK di usare fino a 20 layer GPU se è presente una GPU compatibile; altrimenti ricade sulla CPU. Su un laptop moderno il percorso CPU elabora ancora qualche centinaio di token al secondo—perfetto per l'analisi occasionale di fatture. + +### Cosa succede se il modello non riesce a scaricarsi? + +Assicurati che il tuo ambiente possa raggiungere `https://huggingface.co`. Se sei dietro un proxy aziendale, imposta le variabili d'ambiente `HTTP_PROXY` e `HTTPS_PROXY`. L'SDK riproverà automaticamente, ma puoi anche eseguire manualmente `git lfs pull` del repository in `directory_model_path`. + +### Posso sostituire il modello con uno più piccolo? + +Assolutamente. Basta sostituire `hugging_face_repo_id` con un altro repository (ad es., `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) e regolare `hugging_face_quantization` di conseguenza. I modelli più piccoli si scaricano più velocemente e consumano meno RAM, anche se potresti perdere un po' di qualità nella correzione. + +### Come mi aiuta questo a **extract text from image python** in altri ambiti? + +La stessa pipeline funziona per ricevute, passaporti o note scritte a mano. L'unica modifica è il pacchetto lingua (`ocr.Language.FRENCH`, ecc.) e possibilmente un modello fine‑tuned specifico per il dominio da HuggingFace. + +## Bonus: Automazione di più file + +Se hai una cartella piena di immagini, avvolgi la chiamata OCR in un semplice ciclo: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +Questa piccola aggiunta ti permette di **download huggingface model python** una volta, poi elaborare in batch decine di file—ottimo per scalare la tua pipeline di automazione documenti. + +## Conclusione + +Abbiamo appena percorso un esempio completo, end‑to‑end, che ti mostra come **download HuggingFace model python**, **extract text from image python**, e **improve OCR accuracy python** usando Aspose OCR Cloud e un post‑processore AI. Lo script è pronto all'esecuzione, i concetti sono spiegati, e hai visto l'output prima e dopo così sai che funziona. + +Cosa fare dopo? Prova a sostituire con un modello HuggingFace diverso, sperimenta altri pacchetti lingua, o invia il testo pulito a una pipeline NLP successiva (ad es., estrazione di entità per le righe di fattura). Il cielo è il limite, e la base che hai appena costruito è solida. + +Hai domande o un'immagine difficile che ancora blocca l'OCR? Lascia un commento qui sotto, e risolviamo insieme. Buon coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/italian/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..33b569717 --- /dev/null +++ b/ocr/italian/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-04-26 +description: Scarica rapidamente il modello OCR usando Aspose OCR Python. Scopri come + impostare la directory del modello, configurare il percorso del modello e come scaricare + il modello in poche righe. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: it +og_description: Scarica il modello OCR in pochi secondi con Aspose OCR Python. Questa + guida mostra come impostare la directory del modello, configurare il percorso del + modello e come scaricare il modello in modo sicuro. +og_title: Scarica modello OCR – Tutorial completo Aspose OCR Python +tags: +- OCR +- Python +- Aspose +title: Scarica il modello OCR con Aspose OCR Python – Guida passo passo +url: /it/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – Tutorial completo Aspose OCR Python + +Ti sei mai chiesto come **download ocr model** usando Aspose OCR in Python senza dover setacciare una quantità infinita di documentazione? Non sei l'unico. Molti sviluppatori si trovano di fronte a un ostacolo quando il modello non è presente localmente e l'SDK genera un errore criptico. La buona notizia? La soluzione è costituita da poche righe di codice, e avrai il modello pronto all'uso in pochi minuti. + +In questo tutorial percorreremo tutto ciò che devi sapere: dall'importare le classi corrette, a **set model directory**, fino a **how to download model**, e infine verificare il percorso. Alla fine sarai in grado di eseguire l'OCR su qualsiasi immagine con una singola chiamata di funzione, e comprenderai le opzioni **configure model path** che mantengono il tuo progetto ordinato. Niente superfluo, solo un esempio pratico e eseguibile per gli utenti **aspose ocr python**. + +## Cosa imparerai + +- Come importare correttamente le classi Aspose OCR Cloud. +- I passaggi esatti per **download ocr model** automaticamente. +- Modi per **set model directory** e **configure model path** per build riproducibili. +- Come verificare che il modello sia inizializzato e dove risiede su disco. +- Problemi comuni (permessi, directory mancanti) e soluzioni rapide. + +### Prerequisiti + +- Python 3.8+ installato sulla tua macchina. +- Pacchetto `asposeocrcloud` (`pip install asposeocrcloud`). +- Permesso di scrittura su una cartella dove desideri memorizzare il modello (ad esempio, `C:\models` o `~/ocr_models`). + +--- + +## Passo 1: Importare le classi Aspose OCR Cloud + +La prima cosa di cui hai bisogno è la dichiarazione di importazione corretta. Questa importa le classi che gestiscono la configurazione del modello e le operazioni OCR. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Perché è importante:* `AsposeAI` è il motore che eseguirà l'OCR, mentre `AsposeAIModelConfig` indica al motore **dove** cercare il modello e **se** deve scaricarlo automaticamente. Saltare questo passo o importare il modulo sbagliato causerà un `ModuleNotFoundError` prima ancora di arrivare alla parte di download. + +--- + +## Passo 2: Definire la configurazione del modello (Set Model Directory & Configure Model Path) + +Ora diciamo ad Aspose dove conservare i file del modello. Qui è dove **set model directory** e **configure model path**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Suggerimenti e avvertenze** + +- **Percorsi assoluti** evitano confusione quando lo script viene eseguito da una directory di lavoro diversa. +- Su Linux/macOS potresti usare `"/home/you/ocr_models"`; su Windows, aggiungi il prefisso `r` per trattare le barre inverse letteralmente. +- Impostare `allow_auto_download="true"` è la chiave per **how to download model** senza scrivere codice aggiuntivo. + +--- + +## Passo 3: Creare l'istanza AsposeAI usando la configurazione + +Con la configurazione pronta, istanzia il motore OCR. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Perché è importante:* L'oggetto `ocr_ai` ora contiene la configurazione che abbiamo appena definito. Se il modello non è presente, la chiamata successiva avvierà il download automaticamente—questo è il fulcro di **how to download model** in modo automatico. + +--- + +## Passo 4: Avviare il download del modello (se necessario) + +Prima di poter eseguire l'OCR, devi assicurarti che il modello sia effettivamente su disco. Il metodo `is_initialized()` verifica e forza l'inizializzazione. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**Cosa succede dietro le quinte?** + +- La prima chiamata a `is_initialized()` restituisce `False` perché la cartella del modello è vuota. +- Il `print` informa l'utente che sta per iniziare il download. +- La seconda chiamata forza Aspose a recuperare il modello dal repository Hugging Face specificato in precedenza. +- Una volta scaricato, il metodo restituisce `True` nei controlli successivi. + +**Caso limite:** Se la tua rete blocca Hugging Face, vedrai un'eccezione. In tal caso, scarica manualmente il file zip del modello, estrailo in `directory_model_path` e riesegui lo script. + +--- + +## Passo 5: Segnalare il percorso locale dove il modello è ora disponibile + +Dopo che il download è terminato, probabilmente vuoi sapere dove sono stati salvati i file. Questo aiuta nel debugging e nella configurazione delle pipeline CI. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +L'output tipico appare così: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Ora hai scaricato con successo **download ocr model**, impostato la directory e confermato il percorso. + +--- + +## Panoramica visiva + +Below is a simple diagram that shows the flow from configuration to a ready‑to‑use model. + +![diagramma del flusso download ocr model che mostra configurazione, download automatico e percorso locale](/images/download-ocr-model-flow.png) + +*Il testo alternativo include la parola chiave principale per SEO.* + +--- + +## Varianti comuni e come gestirle + +### 1. Utilizzare un repository di modello diverso + +Se ti serve un modello diverso da `openai/gpt2`, basta sostituire il valore `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Assicurati che il repository sia pubblico o che tu abbia impostato il token necessario nel tuo ambiente. + +### 2. Disabilitare il download automatico + +A volte vuoi controllare il download tu stesso (ad esempio, in ambienti isolati). Imposta `allow_auto_download` su `"false"` e chiama uno script di download personalizzato prima dell'inizializzazione: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Cambiare la directory del modello a runtime + +Puoi riconfigurare il percorso senza ricreare l'oggetto `AsposeAI`: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Consigli professionali per l'uso in produzione + +- **Cache the model**: Mantieni la directory su un'unità di rete condivisa se più servizi necessitano dello stesso modello. Questo evita download ridondanti. +- **Version pinning**: Il repository Hugging Face può aggiornarsi. Per fissare a una versione specifica, aggiungi `@v1.0.0` all'ID del repository (`"openai/gpt2@v1.0.0"`). +- **Permissions**: Assicurati che l'utente che esegue lo script abbia diritti di lettura/scrittura su `directory_model_path`. Su Linux, `chmod 755` è solitamente sufficiente. +- **Logging**: Sostituisci le semplici istruzioni `print` con il modulo `logging` di Python per una migliore osservabilità nelle applicazioni più grandi. + +--- + +## Esempio completo funzionante (pronto per copia‑incolla) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Output previsto** (la prima esecuzione scaricherà, le successive salteranno il download): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Esegui nuovamente lo script; vedrai solo la riga del percorso perché il modello è già nella cache. + +--- + +## Conclusione + +Abbiamo appena coperto l'intero processo per **download ocr model** usando Aspose OCR Python, mostrato come **set model directory**, e spiegato le sfumature di **configure model path**. Con poche righe di codice puoi automatizzare il download, evitare passaggi manuali e mantenere la tua pipeline OCR riproducibile. + +Successivamente, potresti voler esplorare la chiamata OCR reale (`ocr_ai.recognize_image(...)`) o sperimentare con un modello Hugging Face diverso per migliorare la precisione. In ogni caso, le basi che hai costruito qui—configurazione chiara, download automatico e verifica del percorso—renderanno qualsiasi integrazione futura un gioco da ragazzi. + +Hai domande su casi limite, o vuoi condividere come hai modificato la directory del modello per le distribuzioni cloud? Lascia un commento qui sotto, e buona programmazione! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/italian/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..72fc98fc2 --- /dev/null +++ b/ocr/italian/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-26 +description: Come post‑processare i risultati OCR ed estrarre il testo con le coordinate. + Scopri una soluzione passo‑passo usando output strutturato e correzione AI. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: it +og_description: Come post‑elaborare i risultati OCR ed estrarre il testo con le coordinate. + Segui questo tutorial completo per un flusso di lavoro affidabile. +og_title: Come post‑processare OCR – Guida completa +tags: +- OCR +- Python +- AI +- Text Extraction +title: Come post‑elaborare l'OCR – Estrarre il testo con coordinate in Python +url: /it/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come post‑processare l'OCR – Estrarre testo con coordinate in Python + +Hai mai dovuto **post‑processare l'OCR** perché l'output grezzo era rumoroso o disallineato? Non sei l'unico. In molti progetti reali—scansione di fatture, digitalizzazione di ricevute o anche il potenziamento di esperienze AR—il motore OCR ti fornisce parole grezze, ma devi comunque pulirle e tenere traccia di dove ogni parola si trovi nella pagina. È qui che una modalità di output strutturato combinata con un post‑processore guidato da AI brilla. + +In questo tutorial percorreremo una pipeline Python completa e eseguibile che **estrae testo con coordinate** da un'immagine, esegue un passaggio di correzione basato su AI e stampa ogni parola insieme alla sua posizione (x, y). Nessuna importazione mancante, nessun vago “vedi la documentazione” — solo una soluzione autonoma che puoi inserire nel tuo progetto oggi. + +> **Pro tip:** Se usi una libreria OCR diversa, cerca una modalità “structured” o “layout”; i concetti rimangono gli stessi. + +--- + +## Prerequisiti + +Prima di immergerci, assicurati di avere: + +| Requisito | Perché è importante | +|-----------|----------------------| +| Python 3.9+ | Sintassi moderna e type hints | +| libreria `ocr` che supporta `OutputMode.STRUCTURED` (ad es., un fittizio `myocr`) | Necessaria per i dati delle bounding‑box | +| Un modulo di post‑processing AI (può essere OpenAI, HuggingFace o un modello personalizzato) | Migliora l'accuratezza dopo l'OCR | +| Un file immagine (`input.png`) nella tua directory di lavoro | La sorgente che leggeremo | + +Se qualcuno di questi ti è sconosciuto, installa i pacchetti placeholder con `pip install myocr ai‑postproc`. Il codice sotto include anche stub di fallback così puoi testare il flusso senza le librerie reali. + +--- + +## Passo 1: Abilitare la Modalità di Output Strutturato per il Motore OCR + +La prima cosa che facciamo è dire al motore OCR di darci più del semplice testo. L'output strutturato restituisce ogni parola insieme alla sua bounding box e al punteggio di confidenza, essenziale per **estrarre testo con coordinate** più avanti. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Perché è importante:* Senza la modalità strutturata otterresti solo una lunga stringa e perderesti le informazioni spaziali necessarie per sovrapporre il testo alle immagini o per alimentare analisi di layout a valle. + +--- + +## Passo 2: Riconoscere l'Immagine e Catturare Parole, Box e Confidenza + +Ora passiamo l'immagine al motore. Il risultato è un oggetto che contiene una lista di oggetti parola, ognuno dei quali espone `text`, `x`, `y`, `width`, `height` e `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Caso limite:* Se l'immagine è vuota o illeggibile, `structured_result.words` sarà una lista vuota. È buona pratica controllare questo e gestirlo in modo appropriato. + +--- + +## Passo 3: Eseguire il Post‑Processing Basato su AI Mantenendo le Posizioni + +Anche i migliori motori OCR commettono errori—pensa a “O” vs. “0” o a diacritici mancanti. Un modello AI addestrato su testo specifico al dominio può correggere quegli errori. Crucialmente, manteniamo le coordinate originali così il layout spaziale rimane intatto. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Perché preserviamo le coordinate:* Molti compiti a valle (ad es., generazione di PDF, etichettatura AR) dipendono da un posizionamento esatto. L'AI modifica solo il campo `text`, lasciando intatti `x`, `y`, `width`, `height`. + +--- + +## Passo 4: Iterare sulle Parole Corrette e Visualizzare il Testo con le Coordinate + +Infine, cicliamo sulle parole corrette e stampiamo ogni parola insieme al suo angolo in alto a sinistra `(x, y)`. Questo soddisfa l'obiettivo di **estrarre testo con coordinate**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Output previsto (esempio):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Ogni riga mostra la parola corretta e la sua posizione esatta sull'immagine originale. + +--- + +## Esempio Completo Funzionante + +Di seguito trovi uno script unico che collega tutto. Puoi copiarlo, adattare le istruzioni di importazione alle tue librerie effettive e eseguirlo direttamente. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Esecuzione dello script** + +```bash +python ocr_postprocess_demo.py +``` + +Se hai le librerie reali installate, lo script elaborerà il tuo `input.png`. Altrimenti, l'implementazione stub ti permette di vedere il flusso e l'output attesi senza dipendenze esterne. + +--- + +## Domande Frequenti (FAQ) + +| Domanda | Risposta | +|----------|----------| +| *Funziona con Tesseract?* | Tesseract di per sé non espone una modalità strutturata, ma wrapper come `pytesseract.image_to_data` restituiscono bounding box che puoi passare allo stesso post‑processore AI. | +| *E se ho bisogno dell'angolo in basso a destra invece di quello in alto a sinistra?* | Ogni oggetto parola fornisce anche `width` e `height`. Calcola `x2 = x + width` e `y2 = y + height` per ottenere l'angolo opposto. | +| *Posso elaborare più immagini in batch?* | Assolutamente. Avvolgi i passaggi in un ciclo `for image_path in Path("folder").glob("*.png"):` e raccogli i risultati per file. | +| *Come scelgo un modello AI per la correzione?* | Per testo generico, un piccolo GPT‑2 fine‑tuned sugli errori OCR funziona. Per dati specifici al dominio (ad es., prescrizioni mediche), addestra un modello sequence‑to‑sequence su dati accoppiati rumorosi‑puliti. | +| *Il punteggio di confidenza è utile dopo la correzione AI?* | Puoi comunque conservare la confidenza originale per il debug, ma l'AI potrebbe restituire una sua confidenza se il modello lo supporta. | + +--- + +## Casi Limite & Best Practices + +1. **Immagini vuote o corrotte** – verifica sempre che `structured_result.words` non sia vuoto prima di procedere. +2. **Script non latini** – assicurati che il tuo motore OCR sia configurato per la lingua di destinazione; il post‑processore AI deve essere addestrato sullo stesso script. +3. **Performance** – la correzione AI può essere costosa. Cache i risultati se riutilizzi la stessa immagine, o esegui il passaggio AI in modo asincrono. +4. **Sistema di coordinate** – le librerie OCR possono usare origini diverse (alto‑sinistra vs. basso‑sinistra). Adatta di conseguenza quando sovrapponi su PDF o canvas. + +--- + +## Conclusione + +Ora disponi di una ricetta solida, end‑to‑end, per **post‑processare l'OCR** e **estrarre testo con coordinate** in modo affidabile. Abilitando l'output strutturato, passando il risultato attraverso uno strato di correzione AI e preservando le bounding box originali, puoi trasformare scansioni OCR rumorose in testo pulito e consapevole dello spazio, pronto per compiti a valle come generazione di PDF, automazione di inserimento dati o overlay in realtà aumentata. + +Pronto per il passo successivo? Prova a sostituire l'AI stub con una chiamata OpenAI `gpt‑4o‑mini`, oppure integra la pipeline in una FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/italian/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..45b66f451 --- /dev/null +++ b/ocr/italian/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,249 @@ +--- +category: general +date: 2026-04-26 +description: Come riconoscere rapidamente le immagini con Python. Impara una pipeline + di riconoscimento delle immagini, l'elaborazione batch e automatizza il riconoscimento + delle immagini usando l'IA. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: it +og_description: Come riconoscere rapidamente le immagini con Python. Questa guida + illustra una pipeline di riconoscimento delle immagini, il batching e l'automazione + usando l'IA. +og_title: Come riconoscere le immagini – Automatizzare una pipeline di riconoscimento + delle immagini +tags: +- image-processing +- python +- ai +title: Come riconoscere le immagini – Automatizzare una pipeline di riconoscimento + delle immagini +url: /it/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come Riconoscere le Immagini – Automatizzare una Pipeline di Riconoscimento Immagini + +Ti sei mai chiesto **come riconoscere le immagini** senza scrivere migliaia di righe di codice? Non sei solo: molti sviluppatori si trovano davanti allo stesso ostacolo quando, per la prima volta, devono elaborare decine o centinaia di foto. La buona notizia? Con pochi passaggi ordinati puoi creare una pipeline di riconoscimento immagini completa che gestisce i batch, esegue l'elaborazione e pulisce tutto da sola. + +In questo tutorial percorreremo un esempio completo e funzionante che mostra **come batchare le immagini**, inviarle a un motore AI, post‑processare i risultati e, infine, rilasciare le risorse. Alla fine avrai uno script autonomo da inserire in qualsiasi progetto, sia che tu stia costruendo un tagger fotografico, un sistema di controllo qualità o un generatore di dataset di ricerca. + +## Cosa Imparerai + +- **Come riconoscere le immagini** usando un motore AI simulato (il modello è identico per servizi reali come TensorFlow, PyTorch o API cloud). +- Come costruire una **pipeline di riconoscimento immagini** che gestisce i batch in modo efficiente. +- Il modo migliore per **automatizzare il riconoscimento immagini** così da non dover ciclare manualmente sui file ogni volta. +- Consigli per scalare la pipeline e liberare le risorse in modo sicuro. + +> **Prerequisiti:** Python 3.8+, familiarità di base con funzioni e cicli, e una manciata di file immagine (o percorsi) da elaborare. Non sono richieste librerie esterne per l'esempio base, ma indicheremo dove potresti collegare SDK AI reali. + +![Diagramma di come riconoscere le immagini in una pipeline di elaborazione batch](pipeline.png "Diagramma di come riconoscere le immagini") + +## Passo 1: Batch delle Tue Immagini – Come Batchare le Immagini Efficientemente + +Prima che l'AI faccia qualsiasi lavoro pesante, ti serve una collezione di immagini da alimentarla. Pensala come la tua lista della spesa; il motore prenderà ogni elemento dalla lista uno alla volta. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Perché batchare?** +Il batch riduce la quantità di codice boilerplate che devi scrivere e rende banale aggiungere parallelismo in seguito. Se dovessi elaborare 10 000 foto, dovrai modificare solo la sorgente di `image_batch`—il resto della pipeline rimane intatto. + +## Passo 2: Eseguire la Pipeline di Riconoscimento Immagini (Riconoscere le Immagini con AI) + +Ora colleghiamo il batch al riconoscitore vero e proprio. In uno scenario reale potresti chiamare `torchvision.models` o un endpoint cloud; qui simuliamo il comportamento così il tutorial resta autonomo. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Spiegazione:** +- `engine.recognize_image` è il cuore della **pipeline di riconoscimento immagini**; potrebbe essere una chiamata a un modello di deep‑learning o a una REST API. +- `postprocessor.run` dimostra **automatizzare il riconoscimento immagini** normalizzando le previsioni grezze in un dizionario pulito da salvare o trasmettere. +- Raccogliamo ogni dizionario `corrected` in `recognized_results` così i passaggi successivi (ad es. inserimento in database) sono semplici. + +## Passo 3: Post‑processare e Salvare – Automatizzare i Risultati del Riconoscimento Immagini + +Dopo aver ottenuto una lista ordinata di previsioni, di solito vuoi persisterle. L'esempio qui sotto scrive un file CSV; sentiti libero di sostituirlo con un database o una coda di messaggi. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Perché un CSV?** +Il CSV è leggibile universalmente—Excel, pandas, anche editor di testo semplice possono aprirlo. Se in seguito devi **automatizzare il riconoscimento immagini** su larga scala, sostituisci il blocco di scrittura con un inserimento bulk nel tuo data lake. + +## Passo 4: Pulizia – Rilasciare le Risorse AI in Sicurezza + +Molti SDK AI allocano memoria GPU o avviano thread di lavoro. Dimenticare di liberarli può causare perdite di memoria e crash. Anche se i nostri oggetti simulati non ne hanno bisogno, mostreremo il pattern corretto. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +L'esecuzione dello script stampa una conferma amichevole, indicandoti che la pipeline è terminata correttamente. + +## Script Completo Funzionante + +Mettendo tutto insieme, ecco il programma completo, pronto per il copy‑and‑paste: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Output Previsto + +Quando esegui lo script (supponendo che i tre percorsi segnaposto esistano), vedrai qualcosa di simile: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +E il file `recognition_results.csv` generato conterrà: + +| immagine | etichetta | fiducia | +|---------------------|-----------|---------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Conclusione + +Ora disponi di un esempio solido, end‑to‑end, di **come riconoscere le immagini** in Python, completo di **pipeline di riconoscimento immagini**, gestione dei batch e post‑processing automatizzato. Il modello è scalabile: sostituisci le classi simulate con un modello reale, alimenta un `image_batch` più grande, e avrai una soluzione pronta per la produzione. + +Vuoi andare oltre? Prova questi prossimi passi: + +- Sostituisci `MockEngine` con un modello TensorFlow o PyTorch per previsioni reali. +- Parallelizza il ciclo con `concurrent.futures.ThreadPoolExecutor` per velocizzare batch di grandi dimensioni. +- Collega il writer CSV a un bucket di storage cloud per **automatizzare il riconoscimento immagini** su worker distribuiti. + +Sentiti libero di sperimentare, rompere le cose e poi sistemarle—è così che si padroneggia davvero una pipeline di riconoscimento immagini. Se incontri problemi o hai idee per miglioramenti, lascia un commento qui sotto. Buona programmazione! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/italian/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..4c9e3cacb --- /dev/null +++ b/ocr/italian/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-04-26 +description: Maschera rapidamente i numeri delle carte di credito usando il post‑processing + OCR di AsposeAI. Impara la conformità PCI, il mascheramento con espressioni regolari + e la sanitizzazione dei dati in un tutorial passo‑passo. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: it +og_description: Maschera i numeri delle carte di credito nei risultati OCR con AsposeAI. + Questo tutorial copre la conformità PCI, la mascheratura con espressioni regolari + e la sanitizzazione dei dati. +og_title: Mascherare i numeri delle carte di credito – Guida completa al post‑processing + OCR in Python +tags: +- OCR +- Python +- security +title: Mascherare i numeri delle carte di credito nell'output OCR – Guida completa + Python +url: /it/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mascherare i numeri delle carte di credito – Guida completa Python + +Hai mai dovuto **mascherare i numeri delle carte di credito** in un testo proveniente direttamente da un motore OCR? Non sei l'unico. Nei settori regolamentati, esporre un PAN completo (Primary Account Number) può metterti nei guai con gli auditor della conformità PCI. La buona notizia? Con poche righe di Python e il hook di post‑processing di AsposeAI, puoi nascondere automaticamente le otto cifre centrali e rimanere al sicuro. + +In questo tutorial seguirà uno scenario reale: eseguire l'OCR su un'immagine di una ricevuta, quindi applicare una funzione personalizzata di **post‑processing OCR** che sanifica qualsiasi dato PCI. Alla fine avrai uno snippet riutilizzabile da inserire in qualsiasi workflow AsposeAI, oltre a una serie di consigli pratici per gestire i casi limite e scalare la soluzione. + +## Cosa imparerai + +- Come registrare un post‑processor personalizzato con **AsposeAI**. +- Perché un approccio di **mascheramento con espressioni regolari** è sia veloce che affidabile. +- Le basi della **conformità PCI** relative alla sanificazione dei dati. +- Modi per estendere il pattern a più formati di carte o numeri internazionali. +- Output previsto e come verificare che il mascheramento abbia funzionato. + +> **Prerequisiti** – Dovresti avere un ambiente Python 3 funzionante, il pacchetto Aspose.AI for OCR installato (`pip install aspose-ocr`), e un'immagine di esempio (ad es. `receipt.png`) che contenga un numero di carta di credito. Non sono richiesti altri servizi esterni. + +--- + +## Passo 1: Definire un Post‑Processor che Maschera i Numeri delle Carte di Credito + +Il cuore della soluzione risiede in una piccola funzione che riceve il risultato OCR, esegue una routine di **mascheramento con espressioni regolari** e restituisce il testo sanificato. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Perché funziona:** +- L'espressione regolare `(\d{4})\d{8}(\d{4})` corrisponde esattamente a 16 cifre consecutive, il formato comune per Visa, MasterCard e molte altre. +- Catturando le prime quattro e le ultime quattro cifre (`\1` e `\2`) preserviamo informazioni sufficienti per il debug rispettando le regole di **conformità PCI** che vietano la memorizzazione del PAN completo. +- La sostituzione `\1****\2` nasconde le otto cifre sensibili al centro, trasformando `1234567812345678` in `1234****5678`. + +> **Suggerimento professionale:** Se devi supportare numeri American Express a 15 cifre, aggiungi un secondo pattern come `r'(\d{4})\d{6}(\d{5})'` ed esegui entrambe le sostituzioni in sequenza. + +--- + +## Passo 2: Inizializzare il Motore AsposeAI + +Prima di poter collegare il nostro post‑processor, ci serve un'istanza del motore OCR. AsposeAI include il modello OCR e una semplice API per l'elaborazione personalizzata. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Perché inizializzare qui?** +Creare l'oggetto `AsposeAI` una sola volta e riutilizzarlo su più immagini riduce l'overhead. Il motore inoltre memorizza nella cache i modelli linguistici, accelerando le chiamate successive—utile quando si scansionano lotti di ricevute. + +--- + +## Passo 3: Registrare la Funzione di Mascheramento Personalizzata + +AsposeAI espone un metodo `set_post_processor` che consente di collegare qualsiasi callable. Passiamo la nostra funzione `mask_pci` insieme a un dizionario di impostazioni opzionale (vuoto per ora). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**Cosa succede dietro le quinte?** +Quando in seguito invochi `run_postprocessor`, AsposeAI passerà il risultato OCR grezzo a `mask_pci`. La funzione riceve un oggetto leggero (`data`) che contiene il testo riconosciuto, e restituisci una nuova stringa. Questo design mantiene intatto il core OCR consentendoti di applicare le politiche di **sanificazione dei dati** in un unico punto. + +--- + +## Passo 4: Eseguire l'OCR sull'Immagine della Ricevuta + +Ora che il motore sa come pulire l'output, gli forniamo un'immagine. Per il tutorial assumiamo che tu abbia già un oggetto `engine` configurato con le impostazioni di lingua e risoluzione corrette. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Suggerimento:** Se non hai un oggetto pre‑configurato, puoi crearne uno con: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +La chiamata `recognize_image` restituisce un oggetto il cui attributo `text` contiene la stringa grezza, non mascherata. + +--- + +## Passo 5: Applicare il Post‑Processor Registrato + +Con i dati OCR grezzi a disposizione, li passiamo all'istanza AI. Il motore esegue automaticamente la funzione `mask_pci` che abbiamo registrato in precedenza. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Perché usare `run_postprocessor` invece di chiamare la funzione manualmente?** +In questo modo il flusso di lavoro rimane coerente, soprattutto quando hai più post‑processor (ad es., correzione ortografica, rilevamento della lingua). AsposeAI li accoda nell'ordine in cui li registri, garantendo un output deterministico. + +--- + +## Passo 6: Verificare l'Output Sanificato + +Infine, stampiamo il testo sanificato e confermiamo che tutti i numeri delle carte di credito siano correttamente mascherati. + +```python +print(final_result.text) +``` + +**Output previsto** (estratto): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Se la ricevuta non contiene alcun numero di carta, il testo rimane invariato—nulla da mascherare, nulla di cui preoccuparsi. + +--- + +## Gestione dei Casi Limite e delle Variazioni Comuni + +### Più Numeri di Carta in un Documento +Se una ricevuta include più di un PAN (ad es., una carta fedeltà più una carta di pagamento), l'espressione regolare viene eseguita globalmente, mascherando automaticamente tutte le corrispondenze. Nessun codice aggiuntivo necessario. + +### Formattazione Non Standard +A volte l'OCR inserisce spazi o trattini (`1234 5678 1234 5678` o `1234-5678-1234-5678`). Estendi il pattern per ignorare questi caratteri: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +Il `[ -]?` aggiunto tollera spazi o trattini opzionali tra i blocchi di cifre. + +### Carte Internazionali +Per PAN a 19 cifre usati in alcune regioni, puoi ampliare il pattern: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Ricorda solo che la **conformità PCI** richiede comunque di mascherare le cifre centrali, indipendentemente dalla lunghezza. + +### Registrare i Valori Mascherati (Opzionale) +Se hai bisogno di tracciamenti di audit, passa un flag tramite `custom_settings` e adatta la funzione: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Quindi registra con: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Esempio Completo (Pronto per Copia‑Incolla) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Eseguendo questo script su una ricevuta che contiene `4111111111111111` otterrai: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +Questo è l'intero pipeline—dal OCR grezzo alla **sanificazione dei dati**—racchiuso in poche linee pulite di Python. + +--- + +## Conclusione + +Ti abbiamo appena mostrato come **mascherare i numeri delle carte di credito** nei risultati OCR usando il hook di post‑processing di AsposeAI, una routine concisa di espressioni regolari e una serie di consigli di best practice per la **conformità PCI**. La soluzione è completamente autonoma, funziona con qualsiasi immagine che il motore OCR può leggere e può essere estesa per coprire formati di carta più complessi o requisiti di registrazione. + +Pronto per il passo successivo? Prova a combinare questo mascheramento con una routine di **inserimento nel database** che memorizzi solo le ultime quattro cifre per riferimento, oppure integra un **processore batch** che scansioni un'intera cartella di ricevute durante la notte. Potresti anche esplorare altri compiti di **post‑processing OCR** come la standardizzazione degli indirizzi o il rilevamento della lingua—ognuno segue lo stesso pattern che abbiamo usato qui. + +Hai domande sui casi limite, sulle prestazioni o su come adattare il codice a una libreria OCR diversa? Lascia un commento qui sotto e continuiamo la discussione. Buon coding e rimani al sicuro! + + + +![Diagram illustrating how mask credit card numbers works in an OCR pipeline](https://example.com/images/ocr-mask-flow.png "Diagram of OCR post‑processing masking flow") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/italian/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..a2a238046 --- /dev/null +++ b/ocr/italian/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-04-26 +description: Impara a misurare il tempo di inferenza in Python, a caricare un modello + GGUF da Hugging Face e a ottimizzare l'uso della GPU per ottenere risultati più + rapidi. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: it +og_description: Misura il tempo di inferenza in Python caricando un modello GGUF da + Hugging Face e ottimizzando i layer GPU per prestazioni ottimali. +og_title: Misura il tempo di inferenza – Carica il modello GGUF e ottimizza la GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Misura il tempo di inferenza – Carica modello GGUF e ottimizza GPU +url: /it/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Misurare il Tempo di Inferenza – Caricare Modello GGUF & Ottimizzare GPU + +Hai mai dovuto **misurare il tempo di inferenza** per un modello di linguaggio di grandi dimensioni ma non sapevi da dove cominciare? Non sei solo—molti sviluppatori incontrano lo stesso ostacolo quando, per la prima volta, scaricano un file GGUF da Hugging Face e cercano di eseguirlo su una configurazione CPU/GPU mista. + +In questa guida percorreremo **come caricare un modello GGUF**, configurarlo per Hugging Face, e **misurare il tempo di inferenza** con uno snippet Python pulito. Lungo il percorso ti mostreremo anche come **ottimizzare l'uso della GPU per l'inferenza** così le tue esecuzioni saranno il più veloci possibile. Nessun superfluo, solo una soluzione pratica end‑to‑end che puoi copiare‑incollare oggi. + +## Cosa Imparerai + +- Come **configurare un modello HuggingFace** con `AsposeAIModelConfig`. +- I passaggi esatti per **caricare un modello GGUF** (quantizzazione `fp16`) dal hub di Hugging Face. +- Un pattern riutilizzabile per **cronometrare il codice Python** attorno a una chiamata di inferenza. +- Consigli per **ottimizzare l'inferenza GPU** regolando `gpu_layers`. +- Output atteso e come verificare che i tempi abbiano senso. + +### Prerequisiti + +| Requisito | Perché è importante | +|-------------|----------------| +| Python 3.9+ | Sintassi moderna e type hints. | +| pacchetto `asposeai` (o l'SDK equivalente) | Fornisce `AsposeAI` e `AsposeAIModelConfig`. | +| Accesso al repository Hugging Face `bartowski/Qwen2.5-3B-Instruct-GGUF` | Il modello GGUF che caricheremo. | +| Una GPU con almeno 8 GB VRAM (opzionale ma consigliata) | Abilita il passaggio **ottimizzare l'inferenza GPU**. | + +Se non hai ancora installato l'SDK, esegui: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![diagramma di misurazione del tempo di inferenza](https://example.com/measure-inference-time.png){alt="diagramma di misurazione del tempo di inferenza"} + +## Passo 1: Caricare il Modello GGUF – Configurare Modello HuggingFace + +La prima cosa di cui hai bisogno è un oggetto di configurazione corretto che dica ad Aspose AI dove recuperare il modello e come trattarlo. Qui è dove **carichiamo un modello GGUF** e **configuriamo i parametri del modello huggingface**. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Perché è importante:** +- `hugging_face_repo_id` punta al file GGUF esatto sul Hub. +- `fp16` riduce la larghezza di banda della memoria mantenendo la maggior parte della fedeltà del modello. +- `gpu_layers` è il parametro che modifichi quando vuoi **ottimizzare l'inferenza GPU**; più strati sulla GPU solitamente significano latenza più bassa, a patto di avere abbastanza VRAM. + +## Passo 2: Creare l'Istanza Aspose AI + +Ora che il modello è descritto, avviamo un oggetto `AsposeAI`. Questo passaggio è semplice, ma è dove l'SDK scarica effettivamente il file GGUF (se non è nella cache) e prepara l'ambiente di esecuzione. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Consiglio professionale:** La prima esecuzione richiederà qualche secondo in più perché il modello viene scaricato e compilato per la GPU. Le esecuzioni successive saranno fulminee. + +## Passo 3: Eseguire l'Inferenza e **Misurare il Tempo di Inferenza** + +Ecco il cuore del tutorial: avvolgere la chiamata di inferenza con `time.time()` per **misurare il tempo di inferenza**. Inseriamo anche un piccolo risultato OCR solo per mantenere l'esempio autonomo. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Cosa dovresti vedere:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Se il valore sembra alto, probabilmente stai eseguendo la maggior parte degli strati sulla CPU. Questo ci porta al passo successivo. + +## Passo 4: **Ottimizzare l'Inferenza GPU** – Regolare `gpu_layers` + +A volte il valore predefinito `gpu_layers=40` è troppo aggressivo (causando OOM) o troppo conservativo (lasciando prestazioni sul tavolo). Ecco un breve ciclo che puoi usare per trovare il punto ottimale: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Perché funziona:** +- Ogni chiamata ricostruisce l'ambiente di esecuzione con una diversa allocazione GPU, permettendoti di vedere immediatamente il trade‑off di latenza. +- Il ciclo dimostra anche **time python code** in modo riutilizzabile, che puoi adattare ad altri test di performance. + +Un output tipico su una RTX 3080 da 16 GB potrebbe apparire così: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +Da questo, sceglieresti `gpu_layers=40` come punto ottimale per questo hardware. + +## Esempio Completo Funzionante + +Mettendo tutto insieme, ecco uno script unico che puoi salvare in un file (`measure_inference.py`) ed eseguire: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Eseguilo con: + +```bash +python measure_inference.py +``` + +Dovresti vedere una latenza inferiore a un secondo su una GPU decente, confermando che hai **misurato il tempo di inferenza** e **ottimizzato l'inferenza GPU** con successo. + +--- + +## Domande Frequenti (FAQ) + +**D: Funziona con altri formati di quantizzazione?** +R: Assolutamente. Sostituisci `hugging_face_quantization="int8"` (o `q4_0`, ecc.) nella configurazione e riesegui il benchmark. Aspettati un trade‑off: minore utilizzo di memoria vs. una leggera perdita di accuratezza. + +**D: E se non ho una GPU?** +R: Imposta `gpu_layers=0`. Il codice ricadrà interamente sulla CPU, e potrai comunque **misurare il tempo di inferenza**—aspettati solo valori più alti. + +**D: Posso cronometrizzare solo il forward del modello, escludendo il post‑processing?** +R: Sì. Chiama direttamente `ai_engine.run_model(...)` (o il metodo equivalente) e avvolgi quella chiamata con `time.time()`. Il pattern per **time python code** rimane lo stesso. + +--- + +## Conclusione + +Ora disponi di una soluzione completa, pronta al copia‑incolla, per **misurare il tempo di inferenza** di un modello GGUF, **caricare il modello gguf** da Hugging Face, e perfezionare le impostazioni di **ottimizzare l'inferenza GPU**. Regolando `gpu_layers` e sperimentando con la quantizzazione, potrai spremere ogni millisecondo di performance. + +Prossimi passi consigliati: + +- Integrare questa logica di timing in una pipeline CI per rilevare regressioni. +- Esplorare l'inferenza batch per migliorare ulteriormente il throughput. +- Combinare il modello con una pipeline OCR reale invece del testo fittizio usato qui. + +Buon coding, e che i tuoi numeri di latenza rimangano sempre bassi! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/italian/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..e7dc824d7 --- /dev/null +++ b/ocr/italian/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-26 +description: Riconosci il testo scritto a mano usando il motore OCR di Python. Scopri + come estrarre il testo da un'immagine, attivare la modalità scrittura a mano e leggere + rapidamente gli appunti scritti a mano. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: it +og_description: Riconosci il testo scritto a mano con Python. Questo tutorial mostra + come estrarre il testo da un'immagine, attivare la modalità scrittura a mano e leggere + le note scritte a mano usando un semplice motore OCR. +og_title: Riconoscere il testo scritto a mano in Python – Guida completa all'OCR +tags: +- OCR +- Python +- Handwriting Recognition +title: Riconoscere il testo scritto a mano in Python – Tutorial sul motore OCR +url: /it/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# riconoscere il testo scritto a mano in Python – OCR Engine Tutorial + +Ti è mai capitato di dover **recognize handwritten text** ma di sentirti bloccato al “da dove comincio?”? Non sei l’unico. Che tu stia digitalizzando gli scarabocchi di una riunione o estraendo dati da un modulo scansionato, ottenere un risultato OCR affidabile può sembrare come inseguire un unicorno. + +Buone notizie: con poche righe di Python puoi **extract text from image** file, **turn on handwritten mode**, e finalmente **read handwritten notes** senza cercare librerie oscure. In questa guida percorreremo l’intero processo, dalla configurazione in stile **create OCR engine python** alla stampa del risultato sullo schermo. + +## Cosa imparerai + +- Come creare un'istanza **create OCR engine python** usando il pacchetto `ocr`. +- Quale impostazione della lingua fornisce supporto integrato per la scrittura a mano. +- La chiamata esatta per **turn on handwritten mode** così il motore sa che stai trattando testo corsivo. +- Come fornire un'immagine di una nota e **recognize handwritten text** da essa. +- Suggerimenti per gestire diversi formati di immagine, risolvere problemi comuni e ampliare la soluzione. + +Niente fronzoli, niente “vedi la documentazione” dead‑ends—solo uno script completo e eseguibile che puoi copiare‑incollare e testare oggi. + +## Prerequisiti + +Prima di immergerci, assicurati di avere: + +1. Python 3.8+ installato (il codice usa le f‑string). +2. La libreria ipotetica `ocr` (`pip install ocr‑engine` – sostituisci con il nome reale del pacchetto che stai usando). +3. Un file immagine chiaro di una nota scritta a mano (JPEG, PNG o TIFF funzionano). +4. Una modesta dose di curiosità—tutto il resto è coperto qui sotto. + +> **Consiglio professionale:** Se la tua immagine è rumorosa, esegui un rapido passo di pre‑elaborazione con Pillow (ad esempio, `Image.open(...).convert('L')`) prima di inviarla al motore OCR. Spesso aumenta l'accuratezza. + +## Come riconoscere il testo scritto a mano con Python + +Di seguito lo script completo che **creates OCR engine python** oggetti, li configura per la scrittura a mano e stampa la stringa estratta. Salvalo come `handwriting_ocr.py` ed eseguilo dal terminale. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Output previsto + +Quando lo script viene eseguito correttamente, vedrai qualcosa del genere: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Se il motore OCR non riesce a rilevare alcun carattere, il campo `text` sarà una stringa vuota. In tal caso, ricontrolla la qualità dell'immagine o prova una scansione a risoluzione più alta. + +## Spiegazione passo‑passo + +### Passo 1 – istanza **create OCR engine python** + +La classe `OcrEngine` è il punto di ingresso. Pensala come un quaderno vuoto—non succede nulla finché non le dici quale lingua aspettarti e se stai trattando scrittura a mano. + +### Passo 2 – Scegli una lingua che supporta la scrittura a mano + +`ocr.Language.EXTENDED_LATIN` non è solo “Inglese”. Raggruppa un insieme di script basati sul latino e, soprattutto, include modelli addestrati su campioni di corsivo. Saltare questo passo porta spesso a output incomprensibili perché il motore usa di default un modello di testo stampato. + +### Passo 3 – **turn on handwritten mode** + +Chiamare `enable_handwritten_mode(True)` attiva un flag interno. Il motore passa quindi alla sua rete neurale ottimizzata per la spaziatura irregolare e le larghezze di tratto variabili che si trovano nelle note reali. Dimenticare questa riga è un errore comune; il motore tratterà i tuoi scarabocchi come rumore. + +### Passo 4 – Fornisci l'immagine e **recognize handwritten text** + +`recognize_image` fa il lavoro pesante: pre‑elabora il bitmap, lo passa attraverso il modello di scrittura a mano e restituisce un oggetto con l'attributo `text`. Puoi anche ispezionare `handwritten_result.confidence` se ti serve una metrica di qualità. + +### Passo 5 – Stampa il risultato e **read handwritten notes** + +`print(handwritten_result.text)` è il modo più semplice per verificare di aver **extract text from image** con successo. In produzione probabilmente memorizzerai la stringa in un database o la passerai a un altro servizio. + +## Gestione dei casi limite e variazioni comuni + +| Situazione | Cosa fare | +|-----------|------------| +| **L'immagine è ruotata** | Usa Pillow per ruotare (`Image.rotate(angle)`) prima di chiamare `recognize_image`. | +| **Basso contrasto** | Converti in scala di grigi e applica una soglia adattiva (`Image.point(lambda p: p > 128 and 255)`). | +| **Pagine multiple** | Itera su una lista di percorsi file e concatena i risultati. | +| **Script non latini** | Sostituisci `EXTENDED_LATIN` con `ocr.Language.CHINESE` (o appropriato) e mantieni `enable_handwritten_mode(True)`. | +| **Problemi di prestazioni** | Riutilizza la stessa istanza `ocr_engine` per molte immagini; inizializzarla ogni volta aggiunge overhead. | + +### Consiglio professionale sull'uso della memoria + +Se stai elaborando centinaia di note in batch, chiama `ocr_engine.dispose()` al termine. Libera le risorse native che il wrapper Python potrebbe trattenere. + +## Riepilogo visivo rapido + +![recognize handwritten text example](https://example.com/handwritten-note.png "recognize handwritten text example") + +*L'immagine sopra mostra una tipica nota scritta a mano che il nostro script può trasformare in testo semplice.* + +## Esempio completo funzionante (script a file unico) + +Per chi ama la semplicità del copia‑incolla, ecco di nuovo tutto senza i commenti esplicativi: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Eseguilo con: + +```bash +python handwriting_ocr.py +``` + +Dovresti ora vedere l'output **recognize handwritten text** nella tua console. + +## Conclusione + +Abbiamo appena coperto tutto ciò di cui hai bisogno per **recognize handwritten text** in Python—partendo da una nuova chiamata **create OCR engine python**, selezionando la lingua giusta, **turn on handwritten mode**, e infine **extract text from image** per **read handwritten notes**. + +In un unico script autonomo puoi passare da una foto sfocata di uno scarabocchio di riunione a testo pulito e ricercabile. Successivamente, considera di inviare l'output a una pipeline di linguaggio naturale, memorizzarlo in un indice ricercabile, o anche di reinserirlo in un servizio di trascrizione per la generazione di voice‑over. + +### Dove andare da qui? + +- **Elaborazione batch:** Avvolgi lo script in un ciclo per gestire una cartella di scansioni. +- **Filtraggio per confidenza:** Usa `result.confidence` per scartare letture di bassa qualità. +- **Librerie alternative:** Se `ocr` non è adatto, esplora `pytesseract` con `--psm 13` per la modalità scrittura a mano. +- **Integrazione UI:** Combinalo con Flask o FastAPI per offrire un servizio di upload basato sul web. + +Hai domande su un formato immagine specifico o hai bisogno di aiuto per ottimizzare il modello? Lascia un commento qui sotto, e buona programmazione! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/japanese/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..af36e61ed --- /dev/null +++ b/ocr/japanese/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,188 @@ +--- +category: general +date: 2026-04-26 +description: HuggingFace の Python 用モデルのダウンロード方法と、Python で画像からテキストを抽出する方法を学び、Aspose + OCR Cloud を使用して OCR の精度を向上させましょう。 +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: ja +og_description: huggingfaceモデルをPythonでダウンロードし、OCRパイプラインを強化しましょう。このガイドに従って、Pythonで画像からテキストを抽出し、OCR精度を向上させましょう。 +og_title: HuggingFaceモデルをPythonでダウンロード – 完全OCR強化チュートリアル +tags: +- OCR +- HuggingFace +- Python +- AI +title: huggingfaceモデルをPythonでダウンロード – ステップバイステップ OCRブーストガイド +url: /ja/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – 完全OCR強化チュートリアル + +**download HuggingFace model python** をダウンロードしようとして、ちょっと戸惑ったことはありませんか? あなただけではありません。多くのプロジェクトで最大のボトルネックは、良いモデルをマシンに入手し、OCR結果を実用的にすることです。 + +このガイドでは、**download HuggingFace model python** をダウンロードし、**extract text from image python** で画像からテキストを抽出し、Aspose の AI ポストプロセッサを使って **improve OCR accuracy python** を実現するハンズオン例をステップバイステップで解説します。最後には、ノイズの多い請求書画像をクリーンで読みやすいテキストに変換できるスクリプトが完成します—魔法はなく、明確な手順だけです。 + +## 必要なもの + +- Python 3.9+(コードは 3.11 でも動作します) +- 一度だけモデルをダウンロードするためのインターネット接続 +- `asposeocrcloud` パッケージ(`pip install asposeocrcloud`) +- 任意のサンプル画像(例: `sample_invoice.png`)を自分で管理できるフォルダーに配置 + +以上です—重厚なフレームワークは不要、GPU 用ドライバーも必要ありません(高速化したい場合を除く)。 + +それでは実装に入りましょう。 + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## Step 1: OCR エンジンのセットアップと使用言語の選択 +*(ここから **extract text from image python** を開始します。)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**重要なポイント:** +OCR エンジンは最初の防御ラインです。適切な言語パックを選ぶことで、文字認識エラーをすぐに減らせます。これは **improve OCR accuracy python** の核心部分です。 + +## Step 2: AsposeAI モデルの設定 – HuggingFace からのダウンロード +*(ここで実際に **download HuggingFace model python** を行います。)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**内部で何が起きているか?** +`allow_auto_download` が true の場合、SDK は HuggingFace にアクセスし、`Qwen2.5‑3B‑Instruct‑GGUF` モデルを取得して、指定したフォルダーに保存します。これが **download huggingface model python** の核心です—SDK が重い作業を処理するので、`git clone` や `wget` コマンドを書く必要はありません。 + +*プロのコツ:* `directory_model_path` は SSD 上に置くとロード時間が速くなります。モデルは `int8` 形式でも約 3 GB です。 + +## Step 3: AI エンジンを OCR エンジンに結合 +*(2 つのコンポーネントを結びつけて **improve OCR accuracy python** を実現します。)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**なぜ結合するのか?** +OCR エンジンは生のテキストを出力しますが、誤字脱字や改行の乱れ、句読点の誤りが含まれることがあります。AI エンジンはスマートエディタとしてそれらを修正し、**improve OCR accuracy python** に必要なクリーンアップを行います。 + +## Step 4: 画像に対して OCR を実行 +*(いよいよ **extract text from image python** を行います。)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` にはエンジンが認識した生の文字列が `text` 属性として格納されます。実際に使用すると、たとえば “Invoice” が “Inv0ice” になったり、文の途中で改行が入ったりすることがあります。 + +## Step 5: AI ポストプロセッサでクリーンアップ +*(このステップが直接 **improve OCR accuracy python** を実現します。)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +AI モデルがテキストを書き直し、言語に合わせた修正を適用します。HuggingFace の指示チューニング済みモデルを使用しているため、出力は自然で下流処理にすぐ使えます。 + +## Step 6: ビフォーアフターを表示 +*(**extract text from image python** と **improve OCR accuracy python** の効果を素早く確認します。)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### 期待される出力 + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +AI が “Inv0ice” を “Invoice” に修正し、余計な改行も除去しているのが分かります。これが **improve OCR accuracy python** を、ダウンロードした HuggingFace モデルで実現した具体的な結果です。 + +## Frequently Asked Questions (FAQ) + +### GPU が必要ですか? +いいえ。`gpu_layers=20` の設定は、互換性のある GPU があれば最大 20 層を GPU で処理し、無い場合は CPU にフォールバックします。最新のノートパソコンでも CPU だけで数百トークン/秒の処理速度が出るので、たまに請求書を解析する程度なら十分です。 + +### モデルのダウンロードに失敗したら? +`https://huggingface.co` にアクセスできるか確認してください。社内プロキシ環境下の場合は `HTTP_PROXY` と `HTTPS_PROXY` 環境変数を設定します。SDK は自動でリトライしますが、手動で `git lfs pull` して `directory_model_path` にリポジトリを取得することも可能です。 + +### より小さいモデルに差し替えられますか? +もちろんです。`hugging_face_repo_id` を別のリポジトリ(例: `TinyLlama/TinyLlama-1.1B-Chat-v0.1`)に置き換え、`hugging_face_quantization` も合わせて調整してください。小型モデルはダウンロードが速く RAM 消費も少ないですが、修正品質が若干低下する可能性があります。 + +### 他の領域で **extract text from image python** を行うにはどうすれば? +レシート、パスポート、手書きメモなどでも同じパイプラインが使えます。変更が必要なのは言語パック(例: `ocr.Language.FRENCH`)と、場合によっては領域特化のファインチューニング済み HuggingFace モデルだけです。 + +## Bonus: 複数ファイルの自動化 + +画像が多数入ったフォルダーがある場合は、OCR 呼び出しをシンプルなループで包みます: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +この小さな追加で **download huggingface model python** を一度だけ実行し、その後多数のファイルをバッチ処理できます—ドキュメント自動化パイプラインのスケールアウトに最適です。 + +## Conclusion + +今回は **download HuggingFace model python**、**extract text from image python**、そして Aspose の OCR Cloud と AI ポストプロセッサを組み合わせて **improve OCR accuracy python** を実現する、エンドツーエンドの完全例を解説しました。スクリプトはすぐに実行可能で、概念も説明済み、ビフォーアフターの出力も確認済みです。 + +次は何をしますか?別の HuggingFace モデルに差し替えてみる、他の言語パックで実験する、あるいはクリーンアップしたテキストを下流の NLP パイプライン(例: 請求書項目のエンティティ抽出)に流すなど、可能性は無限です。今回構築した基盤はしっかりしています。 + +質問や、まだ OCR がうまくいかない画像があればコメントで教えてください。一緒にトラブルシュートしましょう。Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/japanese/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..23c602902 --- /dev/null +++ b/ocr/japanese/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-04-26 +description: Aspose OCR Python を使用して OCR モデルをすばやくダウンロードします。モデルディレクトリの設定方法、モデルパスの構成方法、数行でモデルをダウンロードする方法を学びましょう。 +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: ja +og_description: Aspose OCR Pythonで数秒でOCRモデルをダウンロード。このガイドでは、モデルディレクトリの設定方法、モデルパスの構成方法、そしてモデルを安全にダウンロードする方法を示します。 +og_title: OCRモデルをダウンロード – 完全なAspose OCR Pythonチュートリアル +tags: +- OCR +- Python +- Aspose +title: Aspose OCR PythonでOCRモデルをダウンロードする – ステップバイステップガイド +url: /ja/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – 完全な Aspose OCR Python チュートリアル + +Python で Aspose OCR を使って **download ocr model** を、膨大なドキュメントを探さずに行う方法を考えたことはありませんか? あなただけではありません。ローカルにモデルが存在せず、SDK が意味不明なエラーを投げると、多くの開発者が壁にぶつかります。良いニュースは、解決策は数行のコードで、数分でモデルを使用可能にできることです。 + +このチュートリアルでは、必要なすべてを順に解説します。正しいクラスのインポートから **set model directory**、実際の **how to download model**、そして最終的にパスの検証までです。最後まで読むと、1つの関数呼び出しだけで任意の画像に OCR を実行でき、プロジェクトを整理整頓できる **configure model path** オプションも理解できます。余計な説明は省き、**aspose ocr python** ユーザー向けの実用的で実行可能な例だけを提供します。 + +## 本チュートリアルで学べること + +- Aspose OCR Cloud クラスを正しくインポートする方法。 +- **download ocr model** を自動的に取得する正確な手順。 +- 再現性のあるビルドのために **set model directory** と **configure model path** を設定する方法。 +- モデルが初期化されているか、ディスク上の場所を確認する方法。 +- よくある落とし穴(権限、ディレクトリ欠如)と迅速な対処法。 + +### 前提条件 + +- マシンに Python 3.8+ がインストールされていること。 +- `asposeocrcloud` パッケージ(`pip install asposeocrcloud`)。 +- モデルを保存したいフォルダーへの書き込み権限(例: `C:\models` または `~/ocr_models`)。 + +--- + +## Step 1: Aspose OCR Cloud クラスのインポート + +最初に必要なのは正しいインポート文です。これにより、モデル設定と OCR 操作を管理するクラスが取り込まれます。 + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Why this matters:* `AsposeAI` は OCR を実行するエンジンで、`AsposeAIModelConfig` はエンジンにモデルの **場所** と **自動取得の有無** を指示します。このステップを省略したり、間違ったモジュールをインポートすると、ダウンロード部分に入る前に `ModuleNotFoundError` が発生します。 + +--- + +## Step 2: モデル設定の定義(Set Model Directory と Configure Model Path) + +ここで、Aspose にモデルファイルの保存場所を指示します。ここで **set model directory** と **configure model path** を行います。 + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**ヒントと注意点** + +- **絶対パス** を使用すると、スクリプトが別の作業ディレクトリから実行されたときの混乱を防げます。 +- Linux/macOS では `"/home/you/ocr_models"` を、Windows ではバックスラッシュを文字列として扱うために `r` プレフィックスを付けます。 +- `allow_auto_download="true"` を設定することで、余計なコードを書かずに **how to download model** が実現できます。 + +--- + +## Step 3: 設定を使って AsposeAI インスタンスを作成 + +設定が整ったら、OCR エンジンのインスタンスを作成します。 + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Why this matters:* `ocr_ai` オブジェクトは先ほど定義した設定を保持しています。モデルが存在しない場合、次の呼び出しで自動的にダウンロードがトリガーされます。これが **how to download model** のハンズオフ方式の核心です。 + +--- + +## Step 4: 必要に応じてモデルダウンロードをトリガー + +OCR を実行する前に、モデルが実際にディスク上にあることを確認する必要があります。`is_initialized()` メソッドは、チェックと初期化の両方を行います。 + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**内部で何が起きているか** + +- 最初の `is_initialized()` 呼び出しは、モデルフォルダーが空であるため `False` を返します。 +- `print` がダウンロード開始をユーザーに通知します。 +- 2 回目の呼び出しで、Aspose が先に指定した Hugging Face リポジトリからモデルを取得します。 +- ダウンロード完了後、以降のチェックでは `True` が返ります。 + +**エッジケース:** ネットワークが Hugging Face をブロックしている場合、例外が発生します。その場合は、モデルの zip を手動でダウンロードし、`directory_model_path` に展開してからスクリプトを再実行してください。 + +--- + +## Step 5: モデルが利用可能になったローカルパスを報告 + +ダウンロードが完了したら、ファイルがどこに配置されたか知りたくなるでしょう。デバッグや CI パイプラインの設定に役立ちます。 + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +典型的な出力例は次の通りです: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +これで **download ocr model** に成功し、ディレクトリを設定し、パスを確認できました。 + +--- + +## ビジュアル概要 + +以下は、設定から使用可能なモデルまでのフローを示すシンプルな図です。 + +![download ocr model flow diagram showing configuration, automatic download, and local path](/images/download-ocr-model-flow.png) + +*Alt テキストには SEO 用の主要キーワードが含まれています。* + +--- + +## よくあるバリエーションと対処方法 + +### 1. 別のモデルリポジトリを使用する場合 + +`openai/gpt2` 以外のモデルが必要な場合は、`hugging_face_repo_id` の値を置き換えるだけです: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +リポジトリが公開されていること、または環境変数に必要なトークンが設定されていることを確認してください。 + +### 2. 自動ダウンロードを無効化する + +場合によっては、ダウンロードを自分で管理したいことがあります(例:エアギャップ環境)。`allow_auto_download` を `"false"` に設定し、初期化前にカスタムダウンロードスクリプトを呼び出します: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. 実行時にモデルディレクトリを変更する + +`AsposeAI` オブジェクトを再作成せずに、パスを再設定できます: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## 本番環境でのプロ向けヒント + +- **モデルをキャッシュ**: 複数のサービスが同じモデルを使用する場合は、共有ネットワークドライブにディレクトリを置き、重複ダウンロードを防ぎます。 +- **バージョン固定**: Hugging Face リポジトリは更新される可能性があります。特定バージョンに固定するには、リポジトリ ID に `@v1.0.0` を付加します(`"openai/gpt2@v1.0.0"`)。 +- **権限**: スクリプトを実行するユーザーが `directory_model_path` に対して読み書き権限を持っていることを確認してください。Linux では通常 `chmod 755` で十分です。 +- **ロギング**: シンプルな `print` 文を Python の `logging` モジュールに置き換えると、規模の大きいアプリケーションでの可観測性が向上します。 + +--- + +## 完全動作例(コピー&ペースト可能) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**期待される出力**(初回実行でダウンロードが行われ、以降の実行ではダウンロードがスキップされます): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +スクリプトを再度実行すると、モデルがすでにキャッシュされているためパスの行だけが表示されます。 + +--- + +## 結論 + +ここでは、Aspose OCR Python を使用して **download ocr model** を行う完全な手順を解説し、**set model directory** の方法と **configure model path** の微妙な違いを説明しました。数行のコードだけでダウンロードを自動化し、手作業を省き、OCR パイプラインの再現性を保つことができます。 + +次のステップとして、実際の OCR 呼び出し(`ocr_ai.recognize_image(...)`)を試したり、精度向上のために別の Hugging Face モデルを実験的に使用したりすると良いでしょう。いずれにせよ、ここで構築した明確な設定、自動ダウンロード、パス検証という基盤が、今後の統合をスムーズにします。 + +エッジケースに関する質問や、クラウド展開向けにモデルディレクトリを調整した方法を共有したい方は、下にコメントを残してください。Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/japanese/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..b3c8e1426 --- /dev/null +++ b/ocr/japanese/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-04-26 +description: OCR結果を後処理し、座標付きテキストを抽出する方法。構造化出力とAI補正を用いたステップバイステップの解決策を学びましょう。 +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: ja +og_description: OCR結果を後処理し、座標付きテキストを抽出する方法。信頼できるワークフローのための包括的なチュートリアルをご覧ください。 +og_title: OCRの後処理方法 – 完全ガイド +tags: +- OCR +- Python +- AI +- Text Extraction +title: OCRの後処理 – Pythonで座標付きテキストを抽出する +url: /ja/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCRのポストプロセス方法 – Pythonで座標付きテキストを抽出する + +生の出力がノイズが多かったり、ずれていたりして、**OCRのポストプロセス方法**が必要になったことはありませんか? あなただけではありません。実際のプロジェクト—請求書スキャン、レシートのデジタル化、あるいはAR体験の拡張—では、OCRエンジンが生の単語を提供しますが、まだそれらをクリーンアップし、各単語がページ上のどこにあるかを追跡する必要があります。そこで、構造化出力モードとAI駆動のポストプロセッサを組み合わせると効果的です。 + +このチュートリアルでは、画像から**座標付きテキストを抽出**し、AIベースの補正ステップを実行し、各単語とその (x, y) 位置を出力する、完全で実行可能なPythonパイプラインを順に解説します。インポートの抜けや「ドキュメント参照」のような曖昧な手順はありません—今日からプロジェクトに組み込める自己完結型のソリューションです。 + +> **プロチップ:** 別のOCRライブラリを使用している場合は、“structured” または “layout” モードを探してください。概念は同じです。 + +--- + +## 前提条件 + +本格的に始める前に、以下が揃っていることを確認してください: + +| 必要条件 | 重要性 | +|----------|--------| +| Python 3.9+ | モダンな構文と型ヒント | +| `ocr` ライブラリ(`OutputMode.STRUCTURED` をサポート、例: 架空の `myocr`) | バウンディングボックスデータに必要 | +| AI ポストプロセッシングモジュール(OpenAI、HuggingFace、またはカスタムモデル) | OCR 後の精度向上 | +| 画像ファイル(`input.png`)を作業ディレクトリに配置 | 読み込むソース | + +これらに心当たりがない場合は、`pip install myocr ai‑postproc` でプレースホルダーのパッケージをインストールしてください。以下のコードにはフォールバック用スタブも含まれているので、実際のライブラリがなくてもフローをテストできます。 + +--- + +## ステップ1: OCRエンジンで構造化出力モードを有効にする + +最初に行うのは、OCRエンジンにプレーンテキスト以上の情報を返すよう指示することです。構造化出力は各単語とそのバウンディングボックス、信頼度スコアを返し、後で**座標付きテキストを抽出**する際に不可欠です。 + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*重要性:* 構造化モードがなければ長い文字列しか得られず、画像上にテキストを重ね合わせたり、下流のレイアウト解析に必要な空間情報が失われます。 + +--- + +## ステップ2: 画像を認識し、単語、バウンディングボックス、信頼度を取得する + +ここで画像をエンジンに入力します。結果は単語オブジェクトのリストを含むオブジェクトで、各オブジェクトは `text`, `x`, `y`, `width`, `height`, `confidence` を提供します。 + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*エッジケース:* 画像が空または読み取れない場合、`structured_result.words` は空リストになります。これをチェックし、適切に処理するのがベストプラクティスです。 + +--- + +## ステップ3: 位置情報を保持しながらAIベースのポストプロセッシングを実行する + +最高のOCRエンジンでもミスは起こります—たとえば “O” と “0” の混同や、アクセント記号の欠落などです。ドメイン固有のテキストで訓練されたAIモデルがこれらのエラーを修正できます。重要なのは、空間レイアウトを保つために元の座標を保持することです。 + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*座標を保持する理由:* PDF生成やARラベリングなど多くの下流タスクは正確な配置に依存します。AIは `text` フィールドのみを変更し、`x`, `y`, `width`, `height` はそのままです。 + +--- + +## ステップ4: 修正された単語を反復し、座標付きテキストを表示する + +最後に、修正された単語をループし、各単語とその左上隅 `(x, y)` を出力します。これで**座標付きテキストを抽出**する目的が達成されます。 + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**期待される出力(例):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +各行は修正された単語と元画像上の正確な位置を示します。 + +--- + +## 完全な動作例 + +以下は全体を結びつけた単一のスクリプトです。コピーして貼り付け、インポート文を実際のライブラリに合わせて調整すれば、すぐに実行できます。 + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**スクリプトの実行** + +```bash +python ocr_postprocess_demo.py +``` + +実際のライブラリがインストールされていれば、スクリプトは `input.png` を処理します。そうでなければ、スタブ実装により外部依存なしで期待されるフローと出力を確認できます。 + +--- + +## よくある質問 (FAQ) + +| 質問 | 回答 | +|------|------| +| *Tesseractでも動作しますか?* | Tesseract自体は構造化モードを標準で提供していませんが、`pytesseract.image_to_data` のようなラッパーはバウンディングボックスを返すので、同じAIポストプロセッサに渡すことができます。 | +| *左上ではなく右下の座標が必要な場合は?* | 各単語オブジェクトは `width` と `height` も提供します。`x2 = x + width`、`y2 = y + height` と計算すれば反対側の角(右下)を取得できます。 | +| *複数画像をバッチ処理できますか?* | もちろん可能です。`for image_path in Path("folder").glob("*.png"):` のループで各ステップを包み、ファイルごとに結果を収集してください。 | +| *補正に使うAIモデルはどう選べばいいですか?* | 汎用テキストの場合、OCRエラーに微調整した小型のGPT‑2が有効です。ドメイン固有のデータ(例:医療処方箋)では、ノイズ付きとクリーンなペアデータでシーケンス‑ツー‑シーケンスモデルを学習させます。 | +| *AI補正後に信頼度スコアは有用ですか?* | デバッグのために元の信頼度は保持できますが、モデルが対応していればAIが独自の信頼度を出力することもあります。 | + +--- + +## エッジケースとベストプラクティス + +1. **空または破損した画像** – 進む前に必ず `structured_result.words` が空でないことを確認してください。 +2. **非ラテン文字スクリプト** – OCRエンジンが対象言語に設定されていることを確認し、AIポストプロセッサも同じスクリプトで訓練されている必要があります。 +3. **パフォーマンス** – AI補正はコストがかかることがあります。同じ画像を再利用する場合は結果をキャッシュするか、AIステップを非同期で実行してください。 +4. **座標系** – OCRライブラリは原点が異なる場合があります(左上か左下)。PDFやキャンバスに重ね合わせる際は適宜調整してください。 + +--- + +## 結論 + +これで、**OCRのポストプロセス方法**と、信頼性の高い**座標付きテキストの抽出**のためのエンドツーエンドの手順が手に入りました。構造化出力を有効にし、結果をAI補正レイヤーに通し、元のバウンディングボックスを保持することで、ノイズの多いOCRスキャンをクリーンで空間情報を持つテキストに変換でき、PDF生成、データ入力自動化、拡張現実のオーバーレイなどの下流タスクに活用できます。 + +次のステップに進みませんか?スタブAIをOpenAI の `gpt‑4o‑mini` 呼び出しに置き換えるか、パイプラインを FastAPI に統合してみてください。 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/japanese/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..085322f02 --- /dev/null +++ b/ocr/japanese/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-04-26 +description: Pythonで画像を素早く認識する方法。画像認識パイプライン、バッチ処理を学び、AIを活用して画像認識を自動化しましょう。 +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: ja +og_description: Pythonで画像を素早く認識する方法。このガイドでは、画像認識パイプライン、バッチ処理、AIを活用した自動化について解説します。 +og_title: 画像の認識方法 – 画像認識パイプラインを自動化する +tags: +- image-processing +- python +- ai +title: 画像の認識方法 – 画像認識パイプラインを自動化する +url: /ja/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 画像認識の方法 – 画像認識パイプラインを自動化する + +何千行ものコードを書かずに **画像を認識する方法** を知りたくありませんか? 同じ壁にぶつかる開発者は多く、最初に数十枚や数百枚の画像を処理しようとするときに悩むものです。朗報です! いくつかのシンプルな手順で、バッチ処理、実行、クリーンアップまで自動で行う本格的な画像認識パイプラインを構築できます。 + +このチュートリアルでは、**画像をバッチ処理する方法**、AI エンジンに各画像を渡す方法、結果を後処理する方法、そしてリソースを解放する方法を示す、完全に実行可能なサンプルを順を追って解説します。最後まで読めば、フォトタグ付け、品質管理システム、研究用データセット生成など、どんなプロジェクトにもすぐに組み込める自己完結型スクリプトが手に入ります。 + +## 学べること + +- **画像を認識する方法** をモック AI エンジンで体験(TensorFlow、PyTorch、クラウド API でも同様のパターンです)。 +- バッチ処理を効率的に扱う **画像認識パイプライン** の構築方法。 +- 手動でファイルをループする必要がなくなる **画像認識の自動化** のベストプラクティス。 +- パイプラインをスケールさせ、安全にリソースを解放するコツ。 + +> **Prerequisites:** Python 3.8+、関数とループの基本的な知識、処理したい画像ファイル(またはパス)数点。コア例では外部ライブラリは不要ですが、実際の AI SDK を組み込む場所はコメントで示します。 + +![バッチ処理パイプラインにおける画像認識の概要](pipeline.png "画像認識の方法図") + +## Step 1: Batch Your Images – How to Batch Images Efficiently + +AI が本格的な処理を始める前に、画像のコレクションを用意する必要があります。これは買い物リストのようなものです。エンジンは後でリストから項目を一つずつ取り出して処理します。 + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**なぜバッチ処理が必要か?** +バッチ化することで記述するボイラープレートが減り、後から並列処理を追加するのが簡単になります。たとえば 10 000 枚の画像を処理したい場合でも、`image_batch` の取得元を変えるだけで済み、パイプライン本体はそのままです。 + +## Step 2: Run the Image Recognition Pipeline (Recognize Images with AI) + +ここでバッチを実際の認識器に渡します。実際の環境では `torchvision.models` やクラウドエンドポイントを呼び出すことになるでしょうが、チュートリアルを自己完結させるために動作をモックしています。 + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**解説:** +- `engine.recognize_image` は **画像認識パイプライン** の中心です。ディープラーニングモデルや REST API への呼び出しに置き換えられます。 +- `postprocessor.run` は **画像認識の自動化** を示す例で、生の予測結果をクリーンな辞書形式に正規化します。 +- 各 `corrected` 辞書を `recognized_results` に蓄積することで、後続のデータベース挿入などがシンプルになります。 + +## Step 3: Post‑process and Store – Automate Image Recognition Results + +予測結果のリストが整ったら、通常は永続化します。以下の例では CSV ファイルに書き出していますが、データベースやメッセージキューに差し替えても構いません。 + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**なぜ CSV か?** +CSV は汎用性が高く、Excel、pandas、テキストエディタなどで簡単に開けます。大規模に **画像認識を自動化** したい場合は、書き込み部分をデータレイクへのバルクインサートに置き換えるだけです。 + +## Step 4: Clean Up – Release AI Resources Safely + +多くの AI SDK は GPU メモリを確保したり、ワーカースレッドを生成したりします。解放し忘れるとメモリリークやクラッシュの原因になります。モックオブジェクト自体は不要ですが、正しいパターンを示しておきます。 + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +スクリプトを実行すると、パイプラインが正常に完了したことを示すメッセージが表示されます。 + +## Full Working Script + +すべてを組み合わせた、コピー&ペースト可能な完全版スクリプトです。 + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Expected Output + +スクリプトを実行すると(プレースホルダーの 3 つのパスが存在すると仮定)、次のような出力が得られます。 + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +生成された `recognition_results.csv` の内容は以下の通りです。 + +| image | label | confidence | +|---------------------|-------|------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Conclusion + +これで Python における **画像を認識する方法** のエンドツーエンド例が完成しました。**画像認識パイプライン**、バッチ処理、結果の自動後処理がすべて含まれています。パターンはスケーラブルです:モッククラスを実際のモデルに差し替え、より大きな `image_batch` を渡すだけで、プロダクションレベルのソリューションが完成します。 + +さらに踏み込むには次のステップを試してください。 + +- `MockEngine` を TensorFlow や PyTorch のモデルに置き換えて、実際の予測を取得する。 +- `concurrent.futures.ThreadPoolExecutor` を使ってループを並列化し、大規模バッチの処理速度を向上させる。 +- CSV ライターをクラウドストレージバケットに接続し、分散ワーカー間で **画像認識を自動化** する。 + +自由に実験し、失敗し、そして修正してください。これが画像認識パイプラインを真にマスターする方法です。質問や改善案があれば、下のコメント欄にどうぞ。Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/japanese/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..38d263a22 --- /dev/null +++ b/ocr/japanese/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2026-04-26 +description: AsposeAI OCR の後処理を使用して、クレジットカード番号を迅速にマスクします。PCI コンプライアンス、正規表現によるマスク、データサニタイズについて、ステップバイステップのチュートリアルで学びましょう。 +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: ja +og_description: AsposeAIでOCR結果のクレジットカード番号をマスクします。このチュートリアルでは、PCIコンプライアンス、正規表現によるマスキング、データサニタイズについて解説します。 +og_title: クレジットカード番号のマスク – 完全Python OCRポストプロセッシングガイド +tags: +- OCR +- Python +- security +title: OCR出力でクレジットカード番号をマスクする – 完全Pythonガイド +url: /ja/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# クレジットカード番号のマスク – 完全な Python ガイド + +OCR エンジンから直接取得したテキストで **クレジットカード番号をマスク** する必要があったことはありませんか? あなただけではありません。規制の厳しい業界では、完全な PAN(Primary Account Number)を露出させると PCI コンプライアンス監査人から厳しい指摘を受ける可能性があります。良いニュースは、数行の Python と AsposeAI の post‑processing フックを使えば、真ん中の 8 桁を自動的に隠すことができ、安全に対応できるということです。 + +このチュートリアルでは、実際のシナリオを通して解説します。レシート画像に OCR を実行し、PCI データをサニタイズするカスタム **OCR post‑processing** 関数を適用します。最後まで進めば、任意の AsposeAI ワークフローに組み込める再利用可能なスニペットと、エッジケースの処理やスケーリングに関する実用的なヒントが手に入ります。 + +## 学べること + +- **AsposeAI** でカスタム post‑processor を登録する方法 +- **正規表現マスク** アプローチが高速かつ信頼できる理由 +- データサニタイズに関する **PCI コンプライアンス** の基本 +- 複数のカードフォーマットや国際番号に対応するためのパターン拡張方法 +- 期待される出力と、マスクが正しく機能したかを検証する方法 + +> **前提条件** – Python 3 環境が動作していること、Aspose.AI for OCR パッケージがインストールされていること(`pip install aspose-ocr`)、クレジットカード番号を含むサンプル画像(例: `receipt.png`)が用意されていることが必要です。その他の外部サービスは不要です。 + +--- + +## Step 1: Define a Post‑Processor that Masks Credit Card Numbers + +ソリューションの核心は、OCR 結果を受け取り **正規表現マスク** 処理を実行し、サニタイズされたテキストを返す小さな関数です。 + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Why this works:** +- 正規表現 `(\d{4})\d{8}(\d{4})` は、Visa、MasterCard などで一般的な 16 桁の連続数字に正確にマッチします。 +- 先頭と末尾の 4 桁(`\1` と `\2`)をキャプチャすることで、デバッグに必要な情報は保持しつつ、**PCI コンプライアンス** の規則である「完全な PAN を保存しない」要件を満たします。 +- 置換文字列 `\1****\2` により、センシティブな中間の 8 桁が隠され、`1234567812345678` は `1234****5678` に変換されます。 + +> **プロのコツ:** 15 桁の American Express 番号にも対応したい場合は、`r'(\d{4})\d{6}(\d{5})'` のような第2パターンを追加し、両方の置換を順に実行してください。 + +--- + +## Step 2: Initialise the AsposeAI Engine + +post‑processor を登録できるようにする前に、OCR エンジンのインスタンスを作成します。AsposeAI は OCR モデルとカスタム処理用のシンプルな API をバンドルしています。 + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Why initialise here?** +`AsposeAI` オブジェクトを一度作成して再利用することで、複数画像に対するオーバーヘッドが削減されます。エンジンは言語モデルをキャッシュするため、続く呼び出しが高速化され、レシートのバッチ処理に便利です。 + +--- + +## Step 3: Register the Custom Masking Function + +AsposeAI は任意の呼び出し可能オブジェクトを受け付ける `set_post_processor` メソッドを提供しています。ここでは `mask_pci` 関数と(現時点では空の)設定辞書を渡します。 + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**What’s happening behind the scenes?** +後で `run_postprocessor` を呼び出すと、AsposeAI は生の OCR 結果を `mask_pci` に渡します。関数は認識されたテキストを含む軽量オブジェクト(`data`)を受け取り、新しい文字列を返します。この設計により、コア OCR は変更せずに **データサニタイズ** ポリシーを一箇所で適用できます。 + +--- + +## Step 4: Run OCR on the Receipt Image + +エンジンが出力クリーンアップ方法を認識したので、画像を渡して OCR を実行します。このチュートリアルでは、すでに言語と解像度設定が済んだ `engine` オブジェクトがある前提です。 + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Tip:** 事前に設定したオブジェクトがない場合は、次のように作成できます。 + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +`recognize_image` 呼び出しは、`text` 属性に生の(マスクされていない)文字列を保持したオブジェクトを返します。 + +--- + +## Step 5: Apply the Registered Post‑Processor + +生の OCR データを取得したら、AI インスタンスに渡します。エンジンは自動的に先ほど登録した `mask_pci` 関数を実行します。 + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Why use `run_postprocessor` instead of calling the function manually?** +この方法により、ワークフローが一貫したものになります。特に複数の post‑processor(例: スペルチェック、言語検出)を持つ場合、AsposeAI は登録順にキューイングし、決定的な出力を保証します。 + +--- + +## Step 6: Verify the Sanitized Output + +最後にサニタイズされたテキストを出力し、クレジットカード番号が正しくマスクされていることを確認します。 + +```python +print(final_result.text) +``` + +**Expected output**(抜粋): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +レシートにカード番号が含まれていなければ、テキストはそのまま変更されません。マスク対象が無いだけなので安心です。 + +--- + +## Handling Edge Cases and Common Variations + +### Multiple Card Numbers in One Document +レシートに複数の PAN(例: ロイヤリティカードと決済カード)が含まれる場合でも、正規表現はグローバルに適用され、すべての一致が自動的にマスクされます。追加コードは不要です。 + +### Non‑Standard Formatting +OCR がスペースやハイフンを挿入することがあります(`1234 5678 1234 5678` や `1234-5678-1234-5678`)。このような文字を無視するパターンに拡張します: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +追加した `[ -]?` が、数字ブロック間の任意のスペースまたはハイフンを許容します。 + +### International Cards +一部地域で使用される 19 桁の PAN に対応するには、パターンを次のように広げます: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +長さが変わっても、**PCI コンプライアンス** では中間桁のマスクが必須であることを忘れないでください。 + +### Logging Masked Values (Optional) +監査証跡が必要な場合は、`custom_settings` 経由でフラグを渡し、関数を次のように調整します: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +その後、以下のように登録します: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Full Working Example (Copy‑Paste Ready) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +このスクリプトを `4111111111111111` を含むレシートで実行すると、次のように出力されます: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +これで、RAW OCR から **データサニタイズ** までの全パイプラインが、数行の Python で完結します。 + +--- + +## Conclusion + +AsposeAI の post‑processing フック、簡潔な正規表現ルーチン、そして **PCI コンプライアンス** に関するベストプラクティスを組み合わせて、OCR 結果中の **クレジットカード番号をマスク** する方法を紹介しました。ソリューションは完全に自己完結型で、OCR エンジンが読める画像であればどれでも動作し、より複雑なカードフォーマットやロギング要件にも拡張可能です。 + +次のステップに進みませんか?マスクした後に **データベース挿入** ルーチンで下4桁だけを保存したり、**バッチプロセッサ** を組んで一晩でフォルダ内のレシート全体を走査したりしてみましょう。また、住所標準化や言語検出といった他の **OCR post‑processing** タスクにも挑戦できます—いずれもここで示したパターンに沿って実装できます。 + +エッジケースやパフォーマンス、別の OCR ライブラリへの適用方法について質問があれば、下のコメント欄にどうぞ。皆さんのコードが安全であることを願っています。Happy coding, and stay secure! + +![クレジットカード番号のマスクが OCR パイプラインでどのように機能するかを示す図](https://example.com/images/ocr-mask-flow.png "OCR post‑processing マスクフローの図") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/japanese/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..ac3020f38 --- /dev/null +++ b/ocr/japanese/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-04-26 +description: Pythonで推論時間の測定方法を学び、Hugging FaceからGGUFモデルをロードし、GPUの使用を最適化してより高速な結果を得る方法を学びましょう。 +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: ja +og_description: Python で Hugging Face から GGUF モデルをロードし、GPU レイヤーをチューニングして最適なパフォーマンスを実現し、推論時間を測定します。 +og_title: 推論時間の測定 – GGUFモデルのロードとGPU最適化 +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: 推論時間の測定 – GGUFモデルをロードしてGPUを最適化 +url: /ja/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 推論時間の測定 – GGUFモデルのロードとGPU最適化 + +大規模言語モデルの **推論時間を測定** したいと思ったことはありますか?しかし、どこから始めればよいか分からないことも多いでしょう。初めて Hugging Face から GGUF ファイルを取得し、CPU と GPU を混在させた環境で実行しようとしたとき、多くの開発者が同じ壁にぶつかります。 + +このガイドでは **GGUFモデルのロード方法**、Hugging Face 用の設定方法、そしてクリーンな Python スニペットで **推論時間を測定** する手順を解説します。さらに **推論 GPU を最適化** する方法も示すので、実行は可能な限り高速になります。余計な説明は省き、すぐにコピー&ペーストできる実践的なエンドツーエンドソリューションをご提供します。 + +## 学習できること + +- `AsposeAIModelConfig` を使用して **HuggingFace モデルを構成** する方法。 +- Hugging Face ハブから **GGUFモデル**(`fp16` 量子化)を **ロード** する正確な手順。 +- 推論呼び出しの前後で **Pythonコードの計測** を行う再利用可能なパターン。 +- `gpu_layers` を調整して **推論 GPU を最適化** するためのヒント。 +- 期待される出力と、計測結果が妥当かどうかを確認する方法。 + +### 前提条件 + +| 必要条件 | 理由 | +|-------------|----------------| +| Python 3.9+ | 最新の構文と型ヒント。 | +| `asposeai` パッケージ(または同等の SDK) | `AsposeAI` と `AsposeAIModelConfig` を提供。 | +| Hugging Face リポジトリ `bartowski/Qwen2.5-3B-Instruct-GGUF` へのアクセス | ロードする GGUF モデル。 | +| 最低 8 GB VRAM を持つ GPU(任意だが推奨) | **推論 GPU の最適化** 手順を実行可能にする。 | + +SDK がまだインストールされていない場合は、以下を実行してください: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![推論時間測定図](https://example.com/measure-inference-time.png){alt="推論時間測定図"} + +## Step 1: GGUFモデルのロード – HuggingFaceモデルの設定 + +最初に必要なのは、Aspose AI がモデルをどこから取得し、どのように扱うかを指示する適切な構成オブジェクトです。ここで **GGUFモデルをロード** し、**huggingfaceモデル** のパラメータを設定します。 + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**なぜ重要か:** +- `hugging_face_repo_id` は Hub 上の正確な GGUF ファイルを指します。 +- `fp16` はメモリ帯域幅を削減しつつ、モデルの精度をほぼ維持します。 +- `gpu_layers` は **推論 GPU を最適化** したいときに調整するパラメータです。GPU 上に多くのレイヤーを配置すれば、十分な VRAM がある限りレイテンシが速くなります。 + +## Step 2: Create the Aspose AI Instance + +モデルの記述が完了したら、`AsposeAI` オブジェクトを作成します。このステップはシンプルですが、SDK が実際に GGUF ファイルをダウンロード(キャッシュに無い場合)し、ランタイムを準備する箇所です。 + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**プロのコツ:** 初回実行はモデルがダウンロードされ GPU 用にコンパイルされるため、数秒余分にかかります。2 回目以降は瞬時に実行されます。 + +## Step 3: Run Inference and **Measure Inference Time** + +チュートリアルの核心です:`time.time()` で推論呼び出しをラップして **推論時間を測定** します。例を自己完結させるために、ちょっとした OCR 結果も入力します。 + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**期待される出力:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +数値が高いと感じたら、ほとんどのレイヤーが CPU 上で実行されている可能性があります。次のステップへ進みましょう。 + +## Step 4: **Optimize Inference GPU** – Tune `gpu_layers` + +デフォルトの `gpu_layers=40` が過剰(OOM を引き起こす)か、保守的すぎて性能が出ていないことがあります。以下の簡易ループで最適な設定を見つけましょう。 + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**なぜ機能するのか:** +- 各呼び出しは異なる GPU 割り当てでランタイムを再構築し、レイテンシのトレードオフを即座に確認できます。 +- このループは **Pythonコードの計測** を再利用可能な形で示しており、他のパフォーマンステストにも応用できます。 + +16 GB RTX 3080 での典型的な出力例: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +この結果から、ハードウェアに対して最適なポイントとして `gpu_layers=40` を選択します。 + +## Full Working Example + +すべてをまとめた単一スクリプトを `measure_inference.py` というファイルに保存して実行できます: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +実行コマンド: + +```bash +python measure_inference.py +``` + +適切な GPU があればサブ秒レイテンシが確認でき、**推論時間を測定** し **推論 GPU を最適化** できたことが証明されます。 + +--- + +## Frequently Asked Questions (FAQs) + +**Q: 他の量子化フォーマットでも動作しますか?** +**A:** もちろんです。設定で `hugging_face_quantization="int8"`(または `q4_0` など)に変更してベンチマークを再実行してください。メモリ使用量が減る代わりに若干の精度低下というトレードオフが発生します。 + +**Q: GPU がない場合はどうすればいいですか?** +**A:** `gpu_layers=0` を設定します。コードは完全に CPU にフォールバックし、依然として **推論時間を測定** できますが、数値は高めになることを想定してください。 + +**Q: 後処理を除いたモデルのフォワードパスだけを計測できますか?** +**A:** はい。`ai_engine.run_model(...)`(または同等のメソッド)を直接呼び出し、その呼び出しを `time.time()` でラップします。**Pythonコードの計測** パターンは同じです。 + +## Conclusion + +これで、GGUFモデルの **推論時間を測定**、Hugging Face から **GGUFモデルをロード**、そして **推論 GPU を最適化** するための完全なコピー&ペースト可能なソリューションが手に入りました。`gpu_layers` を調整し、量子化を試すことで、パフォーマンスをミリ秒単位で最適化できます。 + +次にやってみると良いこと: + +- この計測ロジックを CI パイプラインに統合し、リグレッションを検出する。 +- バッチ推論を検討し、スループットをさらに向上させる。 +- ここで使用したダミーテキストの代わりに、実際の OCR パイプラインとモデルを組み合わせる。 + +Happy coding, and may your latency numbers always stay low! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/japanese/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..91afaf2c7 --- /dev/null +++ b/ocr/japanese/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,200 @@ +--- +category: general +date: 2026-04-26 +description: Python の OCR エンジンを使用して手書き文字を認識します。画像からテキストを抽出する方法、手書きモードをオンにする方法、そして手書きメモを素早く読む方法を学びましょう。 +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: ja +og_description: Pythonで手書き文字を認識する。このチュートリアルでは、画像からテキストを抽出し、手書きモードを有効にして、シンプルなOCRエンジンを使用して手書きメモを読み取る方法を示します。 +og_title: Pythonで手書き文字を認識する – 完全OCRガイド +tags: +- OCR +- Python +- Handwriting Recognition +title: Pythonで手書き文字を認識する – OCRエンジンチュートリアル +url: /ja/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Pythonで手書き文字を認識する – OCRエンジンチュートリアル + +手書き文字を**認識**したくて、でも「どこから始めればいいの?」で行き詰まったことはありませんか? あなただけではありません。会議のメモをデジタル化したり、スキャンしたフォームからデータを抽出したりする場合、信頼できるOCR結果を得るのはユニコーンを追いかけるように感じるかもしれません。 + +良いニュースです:Python数行で**画像からテキストを抽出**し、**手書きモードを有効化**し、ついに**手書きノートを読む**ことが、難解なライブラリを探し回ることなく可能になります。このガイドでは、**create OCR engine python**スタイルのセットアップから画面への結果表示まで、全プロセスを順に解説します。 + +## 学べること + +- `ocr` パッケージを使用して **create OCR engine python** インスタンスを作成する方法。 +- 手書きサポートが組み込まれた言語設定はどれか。 +- エンジンが手書きであることを認識できるように **turn on handwritten mode** を呼び出す正確な方法。 +- ノートの画像を入力し、そこから **recognize handwritten text** を行う方法。 +- さまざまな画像フォーマットの扱い方、一般的な落とし穴のトラブルシューティング、ソリューションの拡張に関するヒント。 + +余計な説明や「ドキュメントを見る」ような行き止まりはありません—今日すぐにコピー&ペーストしてテストできる、完全に実行可能なスクリプトだけです。 + +## 前提条件 + +1. Python 3.8+ がインストールされていること(コードは f‑strings を使用)。 +2. 仮想的な `ocr` ライブラリ(`pip install ocr‑engine` – 使用している実際のパッケージ名に置き換えてください)。 +3. 手書きノートの鮮明な画像ファイル(JPEG、PNG、または TIFF が使用可能)。 +4. ある程度の好奇心—その他は以下でカバーします。 + +> **プロのコツ:** 画像がノイズが多い場合、OCRエンジンに送る前に Pillow で簡単な前処理を行ってください(例: `Image.open(...).convert('L')`)。精度が向上することが多いです。 + +## Pythonで手書き文字を認識する方法 + +以下は **creates OCR engine python** オブジェクトを作成し、手書き用に設定し、抽出された文字列を出力する完全なスクリプトです。`handwriting_ocr.py` として保存し、ターミナルから実行してください。 + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### 期待される出力 + +スクリプトが正常に実行されると、以下のような出力が表示されます: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +OCRエンジンが文字を検出できない場合、`text` フィールドは空文字列になります。その場合は、画像の品質を再確認するか、より高解像度のスキャンを試してください。 + +## ステップバイステップ解説 + +### ステップ 1 – **create OCR engine python** インスタンス + +`OcrEngine` クラスがエントリーポイントです。空白のノートブックのようなもので、期待する言語や手書きかどうかを指定するまで何も起こりません。 + +### ステップ 2 – 手書きに対応した言語を選択 + +`ocr.Language.EXTENDED_LATIN` は単なる「英語」ではありません。ラテン系スクリプトのセットをまとめており、重要なのは手書きサンプルで訓練されたモデルが含まれていることです。このステップを省くと、エンジンが印刷文字モデルをデフォルトにするため、出力が乱れることがよくあります。 + +### ステップ 3 – **turn on handwritten mode** + +`enable_handwritten_mode(True)` を呼び出すと内部フラグが切り替わります。エンジンは実際のノートに見られる不規則な間隔や可変的な筆跡幅に合わせて調整されたニューラルネットに切り替わります。この行を忘れるのは一般的なミスで、エンジンはあなたの落書きをノイズとして扱ってしまいます。 + +### ステップ 4 – 画像を入力し **recognize handwritten text** を実行 + +`recognize_image` が主な処理を行います:ビットマップを前処理し、手書きモデルに通し、`text` 属性を持つオブジェクトを返します。品質指標が必要な場合は `handwritten_result.confidence` を確認することもできます。 + +### ステップ 5 – 結果を出力し **read handwritten notes** + +`print(handwritten_result.text)` は、**extract text from image** に成功したことを確認する最も簡単な方法です。本番環境では文字列をデータベースに保存したり、別のサービスに渡したりするでしょう。 + +## エッジケースと一般的なバリエーションの処理 + +| Situation | What to Do | +|-----------|------------| +| **画像が回転している** | `recognize_image` を呼び出す前に Pillow で回転させます(`Image.rotate(angle)`)。 | +| **コントラストが低い** | グレースケールに変換し、適応的閾値処理を適用します(`Image.point(lambda p: p > 128 and 255)`)。 | +| **複数ページ** | ファイルパスのリストをループし、結果を結合します。 | +| **ラテン文字以外のスクリプト** | `EXTENDED_LATIN` を `ocr.Language.CHINESE`(または適切なもの)に置き換え、`enable_handwritten_mode(True)` はそのまま保持します。 | +| **パフォーマンスの懸念** | 多数の画像で同じ `ocr_engine` インスタンスを再利用します。毎回初期化するとオーバーヘッドが増えます。 | + +### メモリ使用量に関するプロのコツ + +バッチで数百枚のノートを処理する場合、終了後に `ocr_engine.dispose()` を呼び出してください。これにより、Pythonラッパーが保持している可能性のあるネイティブリソースが解放されます。 + +## クイックビジュアルまとめ + +![手書き文字認識例](https://example.com/handwritten-note.png "手書き文字認識例") + +*上の画像は、スクリプトがプレーンテキストに変換できる典型的な手書きノートを示しています。* + +## 完全動作例(単一ファイルスクリプト) + +コピー&ペーストのシンプルさが好きな方のために、解説コメントを除いた全体コードを再掲します: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +以下のコマンドで実行します: + +```bash +python handwriting_ocr.py +``` + +コンソールに **recognize handwritten text** の出力が表示されるはずです。 + +## 結論 + +ここでは、Pythonで **recognize handwritten text** を行うために必要なすべてを網羅しました—新たに **create OCR engine python** を呼び出し、適切な言語を選択し、**turn on handwritten mode** を有効にし、最終的に **extract text from image** して **read handwritten notes** するまでの流れです。 + +単一の自己完結型スクリプトで、会議の落書きのぼやけた写真からクリーンで検索可能なテキストへと変換できます。次のステップとして、出力を自然言語処理パイプラインに流し込んだり、検索可能なインデックスに保存したり、さらには音声合成用の文字起こしサービスに再度渡すことも検討してください。 + +### 次にやるべきことは? + +- **バッチ処理:** フォルダ内のスキャン画像を処理するようにスクリプトをループでラップします。 +- **信頼度フィルタリング:** `result.confidence` を使用して低品質の読み取りを除外します。 +- **代替ライブラリ:** `ocr` が完全に合わない場合、手書きモード用に `--psm 13` を指定した `pytesseract` を検討してください。 +- **UI統合:** Flask や FastAPI と組み合わせて、ウェブベースのアップロードサービスを提供します。 + +特定の画像フォーマットについて質問がある、またはモデルのチューニングが必要ですか?下にコメントを残してください。コーディングを楽しんで! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/korean/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..4653de0ac --- /dev/null +++ b/ocr/korean/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-04-26 +description: HuggingFace 모델 파이썬을 다운로드하고 이미지에서 텍스트를 추출하는 방법을 배우면서 Aspose OCR Cloud를 + 사용해 OCR 정확도를 향상시키는 파이썬을 학습하세요. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: ko +og_description: huggingface 모델을 파이썬으로 다운로드하고 OCR 파이프라인을 강화하세요. 이 가이드를 따라 이미지에서 텍스트를 + 파이썬으로 추출하고 OCR 정확도를 향상시키세요. +og_title: huggingface 모델 파이썬 다운로드 – 완전한 OCR 향상 튜토리얼 +tags: +- OCR +- HuggingFace +- Python +- AI +title: huggingface 모델 파이썬 다운로드 – 단계별 OCR 부스트 가이드 +url: /ko/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – 완전 OCR 향상 튜토리얼 + +**download HuggingFace model python**을 시도해 본 적이 있지만 막막했던 적이 있나요? 당신만 그런 것이 아닙니다. 많은 프로젝트에서 가장 큰 병목 현상은 좋은 모델을 머신에 가져오는 것이며, 그 다음에 OCR 결과를 실제로 유용하게 만드는 것입니다. + +이 가이드에서는 **download HuggingFace model python**을 수행하고, **extract text from image python**으로 이미지에서 텍스트를 추출한 뒤, Aspose의 AI 후처리기를 사용해 **improve OCR accuracy python**을 구현하는 실전 예제를 단계별로 보여드립니다. 최종적으로는 잡음이 많은 청구서 이미지를 깨끗하고 읽기 쉬운 텍스트로 변환하는 스크립트를 얻을 수 있습니다—마법이 아니라 명확한 단계들입니다. + +## What You’ll Need + +- Python 3.9+ (코드는 3.11에서도 동작합니다) +- 한 번만 다운로드하면 되는 모델을 위한 인터넷 연결 +- `asposeocrcloud` 패키지 (`pip install asposeocrcloud`) +- 직접 관리하는 폴더에 넣은 샘플 이미지 (예: `sample_invoice.png`) + +그게 전부입니다—무거운 프레임워크도 없고, GPU 전용 드라이버도 필요하지 않습니다(속도를 높이고 싶다면 제외). + +그럼 실제 구현으로 들어가 보겠습니다. + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## Step 1: Set Up the OCR Engine and Choose a Language +*(여기서 **extract text from image python**을 시작합니다.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**왜 중요한가:** +OCR 엔진은 첫 번째 방어선이며, 올바른 언어 팩을 선택하면 문자 인식 오류를 즉시 줄일 수 있습니다. 이는 **improve OCR accuracy python**의 핵심 요소입니다. + +## Step 2: Configure the AsposeAI Model – Downloading from HuggingFace +*(여기서 실제로 **download HuggingFace model python**을 수행합니다.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**내부에서 무슨 일이 일어나나요?** +`allow_auto_download`가 true이면 SDK가 HuggingFace에 연결해 `Qwen2.5‑3B‑Instruct‑GGUF` 모델을 가져와 지정한 폴더에 저장합니다. 이것이 **download huggingface model python**의 핵심이며, SDK가 무거운 작업을 처리하므로 직접 `git clone`이나 `wget` 명령을 작성할 필요가 없습니다. + +*팁:* `directory_model_path`를 SSD에 두면 로드 시간이 빨라집니다; 모델은 `int8` 형태에서도 약 3 GB 정도입니다. + +## Step 3: Attach the AI Engine to the OCR Engine +*(두 구성 요소를 연결해 **improve OCR accuracy python**을 가능하게 합니다.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**왜 연결하나요?** +OCR 엔진은 원시 텍스트를 제공하지만, 여기에는 철자 오류, 끊어진 줄, 잘못된 구두점 등이 포함될 수 있습니다. AI 엔진은 이러한 문제를 스마트하게 정리해 주는 편집기 역할을 하며, 바로 **improve OCR accuracy python**에 필요한 작업입니다. + +## Step 4: Run OCR on Your Image +*(드디어 **extract text from image python**을 수행하는 순간입니다.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result`에는 엔진이 인식한 원시 문자들을 담은 `text` 속성이 들어갑니다. 실제로는 “Invoice”가 “Inv0ice”로 바뀌거나 문장 중간에 줄 바꿈이 삽입되는 등 작은 문제가 발생할 수 있습니다. + +## Step 5: Clean Up with the AI Post‑Processor +*(바로 **improve OCR accuracy python**을 수행하는 단계입니다.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +AI 모델이 텍스트를 재작성하면서 언어 인식 기반 수정을 적용합니다. HuggingFace에서 제공하는 instruction‑tuned 모델을 사용했기 때문에 출력은 보통 유창하고 후속 처리에 바로 사용할 수 있습니다. + +## Step 6: Show the Before and After +*(**extract text from image python**과 **improve OCR accuracy python**이 얼마나 잘 작동하는지 빠르게 확인해 봅니다.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Expected Output + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +AI가 “Inv0ice”를 “Invoice”로 교정하고 불필요한 줄 바꿈을 매끄럽게 정리한 것을 확인할 수 있습니다. 이것이 **improve OCR accuracy python**을 위해 다운로드한 HuggingFace 모델을 사용했을 때 얻을 수 있는 실질적인 결과입니다. + +## Frequently Asked Questions (FAQ) + +### Do I need a GPU to run the model? +No. The `gpu_layers=20` setting tells the SDK to use up to 20 GPU layers if a compatible GPU is present; otherwise it falls back to CPU. On a modern laptop the CPU path still processes a few hundred tokens per second—perfect for occasional invoice parsing. + +### What if the model fails to download? +Make sure your environment can reach `https://huggingface.co`. If you’re behind a corporate proxy, set the `HTTP_PROXY` and `HTTPS_PROXY` environment variables. The SDK will retry automatically, but you can also manually `git lfs pull` the repo into `directory_model_path`. + +### Can I swap the model for a smaller one? +Absolutely. Just replace `hugging_face_repo_id` with another repo (e.g., `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) and adjust `hugging_face_quantization` accordingly. Smaller models download faster and consume less RAM, though you may lose a bit of correction quality. + +### How does this help me **extract text from image python** in other domains? +The same pipeline works for receipts, passports, or handwritten notes. The only change is the language pack (`ocr.Language.FRENCH`, etc.) and possibly a domain‑specific fine‑tuned model from HuggingFace. + +## Bonus: Automating Multiple Files + +If you have a folder full of images, wrap the OCR call in a simple loop: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +This tiny addition lets you **download huggingface model python** once, then batch‑process dozens of files—great for scaling your document‑automation pipeline. + +## Conclusion + +We’ve just walked through a complete, end‑to‑end example that shows you how to **download HuggingFace model python**, **extract text from image python**, and **improve OCR accuracy python** using Aspose’s OCR Cloud and an AI post‑processor. The script is ready to run, the concepts are explained, and you’ve seen the before‑and‑after output so you know it works. + +What’s next? Try swapping in a different HuggingFace model, experiment with other language packs, or feed the cleaned text into a downstream NLP pipeline (e.g., entity extraction for invoice line items). The sky’s the limit, and the foundation you just built is solid. + +Got questions or a tricky image that still trips the OCR? Drop a comment below, and let’s troubleshoot together. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/korean/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..3d9d45acb --- /dev/null +++ b/ocr/korean/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-04-26 +description: Aspose OCR Python을 사용하여 OCR 모델을 빠르게 다운로드하세요. 모델 디렉터리를 설정하고, 모델 경로를 구성하며, + 몇 줄의 코드로 모델을 다운로드하는 방법을 배워보세요. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: ko +og_description: Aspose OCR Python으로 OCR 모델을 몇 초 만에 다운로드하세요. 이 가이드는 모델 디렉터리를 설정하고, + 모델 경로를 구성하며, 모델을 안전하게 다운로드하는 방법을 보여줍니다. +og_title: OCR 모델 다운로드 – 완전한 Aspose OCR 파이썬 튜토리얼 +tags: +- OCR +- Python +- Aspose +title: Aspose OCR Python으로 OCR 모델 다운로드 – 단계별 가이드 +url: /ko/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – 전체 Aspose OCR Python 튜토리얼 + +Python에서 Aspose OCR을 사용해 **download ocr model** 하는 방법을 끝없는 문서를 뒤져보지 않고 궁금해 본 적 있나요? 당신만 그런 것이 아닙니다. 모델이 로컬에 없고 SDK가 이해하기 어려운 오류를 던질 때 많은 개발자들이 막히곤 합니다. 좋은 소식은? 해결 방법은 몇 줄의 코드뿐이며, 몇 분 안에 모델을 준비할 수 있습니다. + +이 튜토리얼에서는 알아야 할 모든 내용을 단계별로 살펴보겠습니다: 올바른 클래스를 가져오는 것부터 **set model directory**까지, 실제 **how to download model**까지, 그리고 마지막으로 경로를 확인하는 과정까지. 끝까지 진행하면 단일 함수 호출만으로 모든 이미지에 OCR을 실행할 수 있게 되고, 프로젝트를 깔끔하게 유지하는 **configure model path** 옵션을 이해하게 됩니다. 불필요한 내용 없이 **aspose ocr python** 사용자를 위한 실용적이고 실행 가능한 예제만 제공합니다. + +## 배울 내용 + +- Aspose OCR Cloud 클래스를 올바르게 가져오는 방법. +- **download ocr model**을 자동으로 수행하는 정확한 단계. +- 재현 가능한 빌드를 위한 **set model directory** 및 **configure model path** 방법. +- 모델이 초기화되었는지와 디스크 상의 위치를 확인하는 방법. +- 일반적인 함정(권한, 누락된 디렉터리)과 빠른 해결책. + +### 사전 요구 사항 + +- 머신에 Python 3.8+이 설치되어 있어야 합니다. +- `asposeocrcloud` 패키지(`pip install asposeocrcloud`). +- 모델을 저장할 폴더에 대한 쓰기 권한(예: `C:\models` 또는 `~/ocr_models`). + +--- + +## 1단계: Aspose OCR Cloud 클래스 가져오기 + +먼저 필요한 것은 올바른 import 문입니다. 이 문은 모델 구성 및 OCR 작업을 관리하는 클래스를 가져옵니다. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Why this matters:* `AsposeAI`는 OCR을 실행할 엔진이며, `AsposeAIModelConfig`는 엔진에게 모델을 찾을 **where**와 자동으로 가져올 **whether**를 알려줍니다. 이 단계를 건너뛰거나 잘못된 모듈을 가져오면 다운로드 단계에 도달하기도 전에 `ModuleNotFoundError`가 발생합니다. + +--- + +## 2단계: 모델 구성 정의 (Set Model Directory & Configure Model Path) + +이제 Aspose에게 모델 파일을 저장할 위치를 알려줍니다. 여기서 **set model directory**와 **configure model path**를 수행합니다. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**팁 및 주의사항** + +- **Absolute paths**는 스크립트가 다른 작업 디렉터리에서 실행될 때 혼동을 방지합니다. +- Linux/macOS에서는 `"/home/you/ocr_models"`를 사용할 수 있고, Windows에서는 백슬래시를 문자 그대로 처리하기 위해 `r` 접두사를 사용합니다. +- `allow_auto_download="true"`를 설정하면 추가 코드를 작성하지 않고도 **how to download model**을 수행할 수 있는 핵심이 됩니다. + +--- + +## 3단계: 구성으로 AsposeAI 인스턴스 생성 + +구성이 준비되었으면 OCR 엔진을 인스턴스화합니다. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Why this matters:* `ocr_ai` 객체는 이제 방금 정의한 구성을 보유합니다. 모델이 없으면 다음 호출이 자동으로 다운로드를 트리거합니다—이는 **how to download model**을 손쉽게 수행하는 핵심입니다. + +--- + +## 4단계: 모델 다운로드 트리거 (필요한 경우) + +OCR을 실행하기 전에 모델이 실제로 디스크에 존재하는지 확인해야 합니다. `is_initialized()` 메서드는 확인과 초기화를 동시에 수행합니다. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**내부에서 무슨 일이 일어나나요?** + +- 첫 번째 `is_initialized()` 호출은 모델 폴더가 비어 있기 때문에 `False`를 반환합니다. +- `print`는 다운로드가 곧 시작될 것임을 사용자에게 알립니다. +- 두 번째 호출은 Aspose가 앞서 지정한 Hugging Face 저장소에서 모델을 가져오도록 강제합니다. +- 다운로드가 완료되면 이후 호출에서는 `True`를 반환합니다. + +**Edge case:** 네트워크에서 Hugging Face를 차단하면 예외가 발생합니다. 이 경우 모델 zip 파일을 수동으로 다운로드하고 `directory_model_path`에 압축을 풀은 뒤 스크립트를 다시 실행하십시오. + +--- + +## 5단계: 모델이 현재 사용 가능한 로컬 경로 보고 + +다운로드가 완료된 후 파일이 어디에 저장됐는지 확인하고 싶을 것입니다. 이는 디버깅 및 CI 파이프라인 설정에 도움이 됩니다. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +일반적인 출력 예시는 다음과 같습니다: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +이제 **download ocr model**을 성공적으로 수행하고, 디렉터리를 설정했으며, 경로를 확인했습니다. + +--- + +## 시각적 개요 + +아래는 구성에서 사용 준비가 된 모델까지의 흐름을 보여주는 간단한 다이어그램입니다. + +![download ocr model flow diagram showing configuration, automatic download, and local path](/images/download-ocr-model-flow.png) + +*Alt text includes the primary keyword for SEO.* + +--- + +## 일반적인 변형 및 처리 방법 + +### 1. 다른 모델 저장소 사용 + +`openai/gpt2`가 아닌 다른 모델이 필요하면 `hugging_face_repo_id` 값을 교체하면 됩니다: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +저장소가 공개되어 있거나 환경 변수에 필요한 토큰이 설정되어 있는지 확인하십시오. + +### 2. 자동 다운로드 비활성화 + +때때로 직접 다운로드를 제어하고 싶을 때가 있습니다(예: 공기 차단 환경). `allow_auto_download`를 `"false"`로 설정하고 초기화 전에 사용자 정의 다운로드 스크립트를 호출하십시오: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. 런타임 시 모델 디렉터리 변경 + +`AsposeAI` 객체를 다시 만들지 않고도 경로를 재구성할 수 있습니다: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## 프로덕션 사용을 위한 팁 + +- **Cache the model**: 여러 서비스가 동일한 모델을 필요로 할 경우 공유 네트워크 드라이브에 디렉터리를 보관하세요. 이렇게 하면 중복 다운로드를 방지할 수 있습니다. +- **Version pinning**: Hugging Face 저장소가 업데이트될 수 있습니다. 특정 버전에 고정하려면 repo ID에 `@v1.0.0`을 추가하십시오 (`"openai/gpt2@v1.0.0"`). +- **Permissions**: 스크립트를 실행하는 사용자가 `directory_model_path`에 대한 읽기/쓰기 권한을 가지고 있는지 확인하십시오. Linux에서는 일반적으로 `chmod 755`이면 충분합니다. +- **Logging**: 간단한 `print` 문을 Python의 `logging` 모듈로 교체하면 대규모 애플리케이션에서 가시성을 높일 수 있습니다. + +--- + +## 전체 작동 예제 (복사‑붙여넣기 준비) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Expected output** (첫 실행 시 다운로드가 진행되고, 이후 실행에서는 다운로드를 건너뜁니다): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +스크립트를 다시 실행하면 모델이 이미 캐시되어 있기 때문에 경로 라인만 표시됩니다. + +--- + +## 결론 + +우리는 이제 Aspose OCR Python을 사용해 **download ocr model** 하는 전체 과정을 다루었으며, **set model directory** 방법을 보여주고 **configure model path**의 미묘한 차이를 설명했습니다. 몇 줄의 코드만으로 다운로드를 자동화하고 수동 단계를 피하며 OCR 파이프라인을 재현 가능하게 유지할 수 있습니다. + +다음으로 실제 OCR 호출(`ocr_ai.recognize_image(...)`)을 살펴보거나 정확도를 높이기 위해 다른 Hugging Face 모델을 실험해 볼 수 있습니다. 어느 쪽이든 여기서 구축한 기반—명확한 구성, 자동 다운로드, 경로 검증—은 향후 통합을 손쉽게 만들어 줄 것입니다. + +에지 케이스에 대한 질문이 있거나 클라우드 배포를 위해 모델 디렉터리를 어떻게 조정했는지 공유하고 싶다면 아래에 댓글을 남겨 주세요. 즐거운 코딩 되세요! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/korean/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..ab3b1b006 --- /dev/null +++ b/ocr/korean/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-04-26 +description: OCR 결과를 후처리하고 좌표와 함께 텍스트를 추출하는 방법. 구조화된 출력과 AI 교정을 활용한 단계별 솔루션을 배워보세요. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: ko +og_description: OCR 결과를 후처리하고 좌표와 함께 텍스트를 추출하는 방법. 신뢰할 수 있는 워크플로를 위해 이 포괄적인 튜토리얼을 + 따라보세요. +og_title: OCR 후처리 방법 – 완전 가이드 +tags: +- OCR +- Python +- AI +- Text Extraction +title: OCR 후처리 방법 – 파이썬으로 좌표와 함께 텍스트 추출 +url: /ko/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR 후처리 방법 – 파이썬에서 좌표와 함께 텍스트 추출 + +원시 출력이 잡음이 많거나 정렬이 맞지 않아 **OCR 후처리 방법**이 필요했던 적이 있나요? 당신만 그런 것이 아닙니다. 인보이스 스캔, 영수증 디지털화, 혹은 AR 경험을 보강하는 등 많은 실제 프로젝트에서 OCR 엔진은 원시 단어들을 제공하지만, 여전히 이를 정리하고 각 단어가 페이지의 어느 위치에 있는지 추적해야 합니다. 여기서 구조화된 출력 모드와 AI 기반 후처리기가 결합되면 빛을 발합니다. + +이 튜토리얼에서는 이미지에서 **좌표와 함께 텍스트를 추출**하고, AI 기반 교정 단계를 실행하며, 각 단어와 그 (x, y) 위치를 출력하는 완전하고 실행 가능한 파이썬 파이프라인을 단계별로 살펴보겠습니다. 누락된 import 없이, “문서를 참고하세요” 같은 모호한 설명 없이—오늘 바로 프로젝트에 적용할 수 있는 독립형 솔루션입니다. + +> **Pro tip:** 다른 OCR 라이브러리를 사용한다면 “structured” 또는 “layout” 모드를 찾아보세요; 개념은 동일합니다. + +--- + +## 사전 요구 사항 + +시작하기 전에 다음을 확인하세요: + +| 요구 사항 | 왜 중요한가 | +|-------------|----------------| +| Python 3.9+ | 최신 구문 및 타입 힌트 | +| `ocr` library that supports `OutputMode.STRUCTURED` (예: 가상의 `myocr`) | 경계 상자 데이터에 필요 | +| AI post‑processing 모듈 (OpenAI, HuggingFace 또는 커스텀 모델 가능) | OCR 후 정확도 향상 | +| 이미지 파일 (`input.png`) (작업 디렉터리 내) | 읽어올 소스 파일 | + +위 항목 중 익숙하지 않은 것이 있다면 `pip install myocr ai‑postproc` 로 플레이스홀더 패키지를 설치하면 됩니다. 아래 코드는 실제 라이브러리가 없어도 흐름을 테스트할 수 있도록 대체 스텁을 포함하고 있습니다. + +## 단계 1: OCR 엔진에 구조화된 출력 모드 활성화 + +첫 번째로 OCR 엔진에 단순 텍스트 이상의 정보를 제공하도록 지시합니다. 구조화된 출력은 각 단어와 해당 경계 상자 및 신뢰도 점수를 반환하며, 이는 이후 **좌표와 함께 텍스트를 추출**하기 위해 필수적입니다. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*왜 중요한가:* 구조화 모드가 없으면 긴 문자열만 얻을 수 있고, 이미지에 텍스트를 오버레이하거나 후속 레이아웃 분석에 필요한 공간 정보를 잃게 됩니다. + +--- + +## 단계 2: 이미지 인식 및 단어, 박스, 신뢰도 캡처 + +이제 이미지를 엔진에 전달합니다. 결과는 `text`, `x`, `y`, `width`, `height`, `confidence` 를 제공하는 단어 객체 리스트를 포함하는 객체입니다. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*예외 상황:* 이미지가 비어 있거나 읽을 수 없는 경우 `structured_result.words` 는 빈 리스트가 됩니다. 이를 확인하고 적절히 처리하는 것이 좋은 습관입니다. + +--- + +## 단계 3: 위치를 보존하면서 AI 기반 후처리 실행 + +최고의 OCR 엔진도 실수를 합니다—예를 들어 “O”와 “0” 구분이나 결합문자 누락 등. 도메인 특화 텍스트로 학습된 AI 모델은 이러한 오류를 교정할 수 있습니다. 중요한 점은 원래 좌표를 유지하여 공간 레이아웃이 그대로 유지된다는 것입니다. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*좌표를 보존하는 이유:* 많은 후속 작업(예: PDF 생성, AR 라벨링)에서 정확한 위치가 필요합니다. AI는 `text` 필드만 수정하고 `x`, `y`, `width`, `height`는 그대로 둡니다. + +--- + +## 단계 4: 교정된 단어를 순회하며 텍스트와 좌표 표시 + +마지막으로 교정된 단어들을 순회하면서 각 단어와 그 좌상단 코너 `(x, y)` 를 출력합니다. 이는 **좌표와 함께 텍스트를 추출** 목표를 달성합니다. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**예상 출력 (예시):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +각 줄은 교정된 단어와 원본 이미지에서의 정확한 위치를 보여줍니다. + +## 전체 작동 예제 + +아래는 모든 과정을 하나로 연결한 단일 스크립트입니다. 복사‑붙여넣기하고 import 문을 실제 라이브러리에 맞게 조정한 뒤 바로 실행할 수 있습니다. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**스크립트 실행** + +```bash +python ocr_postprocess_demo.py +``` + +실제 라이브러리가 설치되어 있으면 스크립트가 `input.png` 를 처리합니다. 그렇지 않다면 스텁 구현을 통해 외부 의존성 없이 예상 흐름과 출력을 확인할 수 있습니다. + +## 자주 묻는 질문 (FAQ) + +| 질문 | 답변 | +|----------|--------| +| *Tesseract에서도 작동하나요?* | Tesseract 자체는 구조화된 모드를 기본 제공하지 않지만, `pytesseract.image_to_data` 같은 래퍼는 경계 상자를 반환하므로 동일한 AI 후처리기에 전달할 수 있습니다. | +| *좌상단 대신 우하단 코너가 필요하면 어떻게 하나요?* | 각 단어 객체는 `width`와 `height`도 제공합니다. `x2 = x + width`와 `y2 = y + height`를 계산하면 반대 코너를 얻을 수 있습니다. | +| *여러 이미지를 배치 처리할 수 있나요?* | 물론 가능합니다. `for image_path in Path("folder").glob("*.png"):` 루프로 단계들을 감싸고 파일별로 결과를 수집하면 됩니다. | +| *교정에 사용할 AI 모델은 어떻게 선택하나요?* | 일반 텍스트의 경우 OCR 오류에 대해 미세 조정된 작은 GPT‑2가 작동합니다. 도메인 특화 데이터(예: 의료 처방전)의 경우, 잡음‑깨끗한 쌍 데이터로 시퀀스‑투‑시퀀스 모델을 학습하십시오. | +| *AI 교정 후 신뢰도 점수가 유용한가요?* | 디버깅을 위해 원래 신뢰도를 유지할 수 있지만, 모델이 지원한다면 AI가 자체 신뢰도를 출력할 수도 있습니다. | + +## 엣지 케이스 및 모범 사례 + +1. **빈 이미지 또는 손상된 이미지** – 진행하기 전에 항상 `structured_result.words` 가 비어 있지 않은지 확인하세요. +2. **비라틴 문자** – OCR 엔진이 대상 언어에 맞게 설정되어 있는지 확인하고, AI 후처리기도 동일한 스크립트에 대해 학습되어야 합니다. +3. **성능** – AI 교정은 비용이 많이 들 수 있습니다. 같은 이미지를 재사용한다면 결과를 캐시하거나 AI 단계를 비동기로 실행하세요. +4. **좌표 시스템** – OCR 라이브러리는 원점이 다를 수 있습니다(좌상단 vs. 좌하단). PDF나 캔버스에 오버레이할 때 이에 맞게 조정하세요. + +## 결론 + +이제 **OCR 후처리 방법**과 신뢰할 수 있는 **좌표와 함께 텍스트를 추출**하는 완전한 레시피를 갖추었습니다. 구조화된 출력을 활성화하고 결과를 AI 교정 레이어에 통과시켜 원래 경계 상자를 보존함으로써, 잡음이 많은 OCR 스캔을 PDF 생성, 데이터 입력 자동화, 증강 현실 오버레이와 같은 후속 작업에 사용할 수 있는 깨끗하고 공간 정보를 가진 텍스트로 변환할 수 있습니다. + +다음 단계가 준비되셨나요? 스텁 AI를 OpenAI `gpt‑4o‑mini` 호출로 교체하거나 파이프라인을 FastAPI에 통합해 보세요. + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/korean/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..5ffb86089 --- /dev/null +++ b/ocr/korean/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-26 +description: Python으로 이미지를 빠르게 인식하는 방법. 이미지 인식 파이프라인, 배치 처리, 그리고 AI를 활용한 이미지 인식 자동화를 + 배워보세요. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: ko +og_description: Python으로 이미지를 빠르게 인식하는 방법. 이 가이드는 이미지 인식 파이프라인, 배치 처리 및 AI를 활용한 자동화를 + 단계별로 안내합니다. +og_title: 이미지를 인식하는 방법 – 이미지 인식 파이프라인 자동화 +tags: +- image-processing +- python +- ai +title: 이미지를 인식하는 방법 – 이미지 인식 파이프라인 자동화 +url: /ko/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 이미지 인식 방법 – 이미지 인식 파이프라인 자동화 + +천 줄이 넘는 코드를 작성하지 않고 **이미지를 인식하는 방법**을 궁금해 본 적 있나요? 당신만 그런 것이 아닙니다—많은 개발자들이 처음으로 수십에서 수백 장의 사진을 처리해야 할 때 같은 장벽에 부딪히곤 합니다. 좋은 소식은? 몇 가지 간단한 단계만으로 배치 처리하고 실행하며 자동으로 정리되는 완전한 이미지 인식 파이프라인을 구축할 수 있다는 것입니다. + +이 튜토리얼에서는 **이미지를 배치하는 방법**을 보여주는 완전하고 실행 가능한 예제를 단계별로 살펴보고, 각 이미지를 AI 엔진에 전달하고, 결과를 후처리하며, 마지막으로 리소스를 해제하는 과정을 보여드립니다. 끝까지 따라오면 사진 태거, 품질 관리 시스템, 혹은 연구용 데이터셋 생성기 등 어떤 프로젝트에도 바로 넣어 사용할 수 있는 독립형 스크립트를 얻게 됩니다. + +## 배울 내용 + +- **이미지 인식 방법**을 모의 AI 엔진을 사용해 배웁니다(패턴은 TensorFlow, PyTorch, 클라우드 API와 같은 실제 서비스와 동일합니다). +- 배치를 효율적으로 처리하는 **이미지 인식 파이프라인**을 구축하는 방법. +- 파일을 매번 수동으로 반복하지 않아도 되는 **이미지 인식 자동화** 최선의 방법. +- 파이프라인을 확장하고 리소스를 안전하게 해제하는 팁. + +> **전제 조건:** Python 3.8+, 함수와 루프에 대한 기본적인 이해, 그리고 처리하려는 이미지 파일(또는 경로) 몇 개. 핵심 예제에는 외부 라이브러리가 필요 없지만, 실제 AI SDK를 연결할 수 있는 위치는 언급할 것입니다. + +![배치 처리 파이프라인에서 이미지 인식 방법에 대한 다이어그램](pipeline.png "이미지 인식 방법 다이어그램") + +## 단계 1: 이미지 배치하기 – 이미지를 효율적으로 배치하는 방법 + +AI가 무거운 작업을 수행하기 전에, 엔진에 전달할 이미지 컬렉션이 필요합니다. 이것을 장보기 리스트라고 생각하면 됩니다; 엔진은 나중에 리스트에 있는 항목을 하나씩 꺼내게 됩니다. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**왜 배치할까요?** +배치를 사용하면 작성해야 하는 보일러플레이트 코드 양이 줄어들고, 나중에 병렬 처리를 추가하기도 쉬워집니다. 10 000장의 사진을 처리해야 할 경우에도 `image_batch`의 소스만 바꾸면 되며, 파이프라인의 나머지 부분은 그대로 유지됩니다. + +## 단계 2: 이미지 인식 파이프라인 실행 (AI로 이미지 인식) + +이제 배치를 실제 인식기로 연결합니다. 실제 환경에서는 `torchvision.models`나 클라우드 엔드포인트를 호출할 수 있지만, 여기서는 동작을 모의하여 튜토리얼이 독립적으로 유지되도록 합니다. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**설명:** +- `engine.recognize_image`는 **이미지 인식 파이프라인**의 핵심이며, 딥러닝 모델 호출이나 REST API 호출이 될 수 있습니다. +- `postprocessor.run`은 원시 예측을 저장하거나 스트리밍할 수 있는 깔끔한 딕셔너리로 정규화함으로써 **이미지 인식 자동화**를 보여줍니다. +- 각 `corrected` 딕셔너리를 `recognized_results`에 수집하면, 이후 단계(예: 데이터베이스 삽입)가 간단해집니다. + +## 단계 3: 후처리 및 저장 – 이미지 인식 결과 자동화 + +정돈된 예측 리스트를 얻은 후에는 보통 이를 영구 저장하고 싶습니다. 아래 예제는 CSV 파일을 작성하지만, 데이터베이스나 메시지 큐로 교체해도 됩니다. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**왜 CSV인가요?** +CSV는 보편적으로 읽을 수 있습니다—Excel, pandas, 심지어 일반 텍스트 편집기에서도 열 수 있죠. 나중에 **이미지 인식 자동화**를 대규모로 수행해야 한다면, 쓰기 블록을 데이터 레이크에 대한 대량 삽입으로 교체하면 됩니다. + +## 단계 4: 정리 – AI 리소스를 안전하게 해제 + +많은 AI SDK가 GPU 메모리를 할당하거나 워커 스레드를 생성합니다. 이를 해제하지 않으면 메모리 누수와 심각한 충돌이 발생할 수 있습니다. 우리의 모의 객체는 필요 없지만, 올바른 패턴을 보여드리겠습니다. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +스크립트를 실행하면 친절한 확인 메시지가 출력되어 파이프라인이 정상적으로 종료되었음을 알려줍니다. + +## 전체 작동 스크립트 + +모든 것을 합치면, 복사‑붙여넣기만 하면 되는 완전한 프로그램은 다음과 같습니다: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### 예상 출력 + +스크립트를 실행하면(세 개의 플레이스홀더 경로가 존재한다고 가정) 다음과 같은 결과가 표시됩니다: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +그리고 생성된 `recognition_results.csv` 파일에는 다음과 같은 내용이 들어갑니다: + +| 이미지 | 레이블 | 신뢰도 | +|--------|--------|--------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## 결론 + +이제 Python에서 **이미지를 인식하는 방법**에 대한 견고하고 엔드‑투‑엔드 예제를 갖추었습니다. **이미지 인식 파이프라인**, 배치 처리, 자동 후처리까지 모두 포함되어 있습니다. 이 패턴은 확장 가능합니다: 모의 클래스를 실제 모델로 교체하고, 더 큰 `image_batch`를 제공하면 프로덕션 수준의 솔루션이 완성됩니다. + +더 나아가고 싶나요? 다음 단계들을 시도해 보세요: + +- `MockEngine`을 TensorFlow 또는 PyTorch 모델로 교체하여 실제 예측을 수행합니다. +- `concurrent.futures.ThreadPoolExecutor`를 사용해 루프를 병렬화하고 대용량 배치를 가속화합니다. +- CSV 라이터를 클라우드 스토리지 버킷에 연결해 **이미지 인식 자동화**를 분산 워커에서도 수행하도록 합니다. + +실험하고, 오류를 만들고, 다시 고쳐 보세요—그것이 이미지 인식 파이프라인을 진정으로 마스터하는 방법입니다. 문제가 발생하거나 개선 아이디어가 있으면 아래에 댓글을 남겨 주세요. 즐거운 코딩 되세요! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/korean/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..a474cd470 --- /dev/null +++ b/ocr/korean/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-04-26 +description: AsposeAI OCR 후처리를 사용하여 신용카드 번호를 빠르게 마스킹하세요. 단계별 튜토리얼에서 PCI 규정 준수, 정규식 + 마스킹 및 데이터 정화 방법을 배웁니다. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: ko +og_description: AsposeAI를 사용하여 OCR 결과에서 신용카드 번호를 마스킹합니다. 이 튜토리얼에서는 PCI 규정 준수, 정규식 + 마스킹 및 데이터 정화에 대해 다룹니다. +og_title: 신용카드 번호 마스킹 – 파이썬 OCR 후처리 완전 가이드 +tags: +- OCR +- Python +- security +title: OCR 출력에서 신용카드 번호 마스킹 – 완전 파이썬 가이드 +url: /ko/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 마스크된 신용카드 번호 – 완전 Python 가이드 + +OCR 엔진에서 바로 추출한 텍스트에서 **신용카드 번호를 마스크**해야 할 때가 있나요? 당신만 그런 것이 아닙니다. 규제 산업에서는 전체 PAN(Primary Account Number)을 노출하면 PCI 컴플라이언스 감사에서 큰 문제가 될 수 있습니다. 좋은 소식은? 몇 줄의 Python 코드와 AsposeAI의 후처리 훅을 사용하면 중간 8자리 숫자를 자동으로 숨겨 안전하게 처리할 수 있다는 것입니다. + +이 튜토리얼에서는 실제 시나리오를 따라가 보겠습니다: 영수증 이미지에 OCR을 실행하고, PCI 데이터를 정화하는 맞춤형 **OCR 후처리** 함수를 적용합니다. 최종적으로는 어떤 AsposeAI 워크플로에도 삽입할 수 있는 재사용 가능한 스니펫과, 엣지 케이스 처리 및 솔루션 확장에 대한 실용적인 팁을 제공하게 됩니다. + +## 배울 내용 + +- **AsposeAI**에 맞춤형 후처리기를 등록하는 방법 +- **정규식 마스킹** 접근법이 빠르고 신뢰할 수 있는 이유 +- 데이터 정화와 관련된 **PCI 컴플라이언스** 기본 +- 여러 카드 형식이나 국제 번호에 맞게 패턴을 확장하는 방법 +- 예상 출력 및 마스킹이 정상 작동했는지 확인하는 방법 + +> **전제 조건** – Python 3 환경이 정상적으로 동작하고, Aspose.AI for OCR 패키지가 설치되어 있어야 합니다(`pip install aspose-ocr`). 또한 신용카드 번호가 포함된 샘플 이미지(예: `receipt.png`)가 필요합니다. 다른 외부 서비스는 필요하지 않습니다. + +--- + +## 1단계: 신용카드 번호를 마스크하는 후처리기 정의 + +솔루션의 핵심은 OCR 결과를 받아 **정규식 마스킹**을 수행하고 정화된 텍스트를 반환하는 작은 함수에 있습니다. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**동작 원리:** +- 정규식 `(\d{4})\d{8}(\d{4})`은 16자리 연속 숫자를 정확히 매치합니다. 이는 Visa, MasterCard 등 대부분의 카드 형식에 해당합니다. +- 첫 번째와 마지막 네 자리(`\1`과 `\2`)를 캡처함으로써 디버깅에 필요한 최소 정보를 유지하면서 **PCI 컴플라이언스** 규정(전체 PAN 저장 금지)을 준수합니다. +- 치환 문자열 `\1****\2`는 민감한 중간 8자리를 가려 `1234567812345678`을 `1234****5678`으로 변환합니다. + +> **프로 팁:** 15자리 American Express 번호를 지원하려면 `r'(\d{4})\d{6}(\d{5})'`와 같은 두 번째 패턴을 추가하고 두 치환을 순차적으로 실행하세요. + +--- + +## 2단계: AsposeAI 엔진 초기화 + +후처리기를 연결하기 전에 OCR 엔진 인스턴스를 생성해야 합니다. AsposeAI는 OCR 모델과 맞춤 처리용 간단한 API를 함께 제공합니다. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**왜 여기서 초기화하나요?** +`AsposeAI` 객체를 한 번 생성하고 여러 이미지에 재사용하면 오버헤드가 감소합니다. 엔진은 언어 모델을 캐시해 이후 호출을 빠르게 처리하므로 영수증을 대량으로 스캔할 때 유용합니다. + +--- + +## 3단계: 맞춤형 마스킹 함수 등록 + +AsposeAI는 `set_post_processor` 메서드를 제공해任意의 호출 가능한 객체를 연결할 수 있게 합니다. 여기서는 `mask_pci` 함수와 (현재는 비어 있는) 설정 딕셔너리를 전달합니다. + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**내부에서 무슨 일이 일어나나요?** +나중에 `run_postprocessor`를 호출하면 AsposeAI가 원시 OCR 결과를 `mask_pci`에 전달합니다. 함수는 인식된 텍스트를 포함하는 가벼운 객체(`data`)를 받고, 새로운 문자열을 반환합니다. 이 설계는 핵심 OCR 로직을 건드리지 않으면서 **데이터 정화** 정책을 한 곳에서 적용할 수 있게 합니다. + +--- + +## 4단계: 영수증 이미지에 OCR 실행 + +엔진이 출력 정화 방법을 알게 되었으니 이제 이미지를 전달합니다. 이 튜토리얼에서는 이미 언어 및 해상도 설정이 완료된 `engine` 객체가 있다고 가정합니다. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**팁:** 사전 설정된 객체가 없다면 다음과 같이 만들 수 있습니다: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +`recognize_image` 호출은 `text` 속성에 원시, 마스크되지 않은 문자열을 담은 객체를 반환합니다. + +--- + +## 5단계: 등록된 후처리기 적용 + +원시 OCR 데이터를 확보했으니 AI 인스턴스에 전달합니다. 엔진은 자동으로 앞서 등록한 `mask_pci` 함수를 실행합니다. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**왜 `run_postprocessor`를 사용하고 직접 함수를 호출하지 않을까요?** +이렇게 하면 워크플로가 일관성을 유지합니다. 특히 맞춤법 검사, 언어 감지 등 여러 후처리기가 있을 때 유용합니다. AsposeAI는 등록 순서대로 후처리기를 큐에 넣어 결정론적 출력을 보장합니다. + +--- + +## 6단계: 정화된 출력 확인 + +마지막으로 정화된 텍스트를 출력하고 신용카드 번호가 올바르게 마스크됐는지 확인합니다. + +```python +print(final_result.text) +``` + +**예상 출력** (발췌): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +영수증에 카드 번호가 없었다면 텍스트는 그대로 유지됩니다—마스크할 것이 없으니 걱정할 필요가 없습니다. + +--- + +## 엣지 케이스 및 일반적인 변형 처리 + +### 하나의 문서에 여러 카드 번호가 있는 경우 +영수증에 PAN이 두 개 이상(예: 멤버십 카드와 결제 카드) 포함돼도 정규식이 전역으로 적용돼 모든 매치를 자동으로 마스크합니다. 추가 코드는 필요 없습니다. + +### 비표준 포맷 +OCR 결과에 공백이나 대시가 삽입될 수 있습니다(`1234 5678 1234 5678` 또는 `1234-5678-1234-5678`). 다음과 같이 패턴을 확장해 이러한 문자를 무시하도록 합니다: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +추가된 `[ -]?`는 숫자 블록 사이에 선택적인 공백이나 하이픈을 허용합니다. + +### 국제 카드 +일부 지역에서는 19자리 PAN이 사용됩니다. 패턴을 다음과 같이 넓힐 수 있습니다: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +길이에 관계없이 **PCI 컴플라이언스**는 중간 숫자를 마스크하도록 요구한다는 점을 기억하세요. + +### 마스크된 값 로깅 (선택 사항) +감사 추적이 필요하면 `custom_settings`를 통해 플래그를 전달하고 함수를 다음과 같이 조정합니다: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +그 후 다음과 같이 등록합니다: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## 전체 작업 예시 (복사‑붙여넣기 가능) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +이 스크립트를 `4111111111111111`이 포함된 영수증에 실행하면 다음과 같은 결과가 나옵니다: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +원시 OCR부터 **데이터 정화**까지 전체 파이프라인이 몇 줄의 깔끔한 Python 코드로 구현되었습니다. + +--- + +## 결론 + +우리는 AsposeAI의 후처리 훅, 간결한 정규식 루틴, 그리고 **PCI 컴플라이언스**를 위한 몇 가지 모범 사례를 활용해 OCR 결과에서 **신용카드 번호를 마스크**하는 방법을 보여드렸습니다. 이 솔루션은 완전 자립형이며 OCR 엔진이 읽을 수 있는 모든 이미지에 적용 가능하고, 더 복잡한 카드 형식이나 로깅 요구 사항을 다루도록 확장할 수 있습니다. + +다음 단계는? 마스크된 번호 중 마지막 네 자리만 저장하는 **데이터베이스 삽입** 루틴과 결합하거나, 영수증 폴더 전체를 야간에 스캔하는 **배치 프로세서**와 통합해 보세요. 또한 주소 표준화나 언어 감지와 같은 다른 **OCR 후처리** 작업을 탐색해 볼 수 있습니다—모두 여기서 사용한 패턴을 그대로 적용하면 됩니다. + +엣지 케이스, 성능, 혹은 다른 OCR 라이브러리로 코드를 옮기는 방법에 대한 질문이 있나요? 아래 댓글로 남겨 주세요. 함께 이야기를 이어가며 더 안전하고 효율적인 코딩을 즐기시길 바랍니다. Happy coding, and stay secure! + +![신용카드 번호 마스크가 OCR 파이프라인에서 작동하는 방식을 보여주는 다이어그램](https://example.com/images/ocr-mask-flow.png "OCR 후처리 마스크 흐름도") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/korean/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..037946b93 --- /dev/null +++ b/ocr/korean/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-04-26 +description: Python에서 추론 시간을 측정하는 방법을 배우고, Hugging Face에서 GGUF 모델을 로드하며, 더 빠른 결과를 + 위해 GPU 사용을 최적화하세요. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: ko +og_description: Hugging Face에서 GGUF 모델을 로드하고 GPU 레이어를 최적화하여 Python에서 추론 시간을 측정합니다. +og_title: 추론 시간 측정 – GGUF 모델 로드 및 GPU 최적화 +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: 추론 시간 측정 – GGUF 모델 로드 및 GPU 최적화 +url: /ko/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 추론 시간 측정 – GGUF 모델 로드 및 GPU 최적화 + +대형 언어 모델의 **추론 시간을 측정**하고 싶지만 어디서 시작해야 할지 몰라 고민한 적 있나요? 혼자가 아닙니다—많은 개발자들이 처음으로 Hugging Face에서 GGUF 파일을 받아와 혼합 CPU/GPU 환경에서 실행하려 할 때 같은 장벽에 부딪힙니다. + +이 가이드에서는 **GGUF 모델을 로드하는 방법**, Hugging Face에 맞게 구성하는 방법, 그리고 깔끔한 Python 스니펫으로 **추론 시간을 측정**하는 방법을 단계별로 살펴봅니다. 또한 **GPU 추론 최적화**를 통해 실행 속도를 최대화하는 방법도 함께 보여드립니다. 불필요한 내용 없이 바로 복사‑붙여넣기 가능한 실용적인 엔드‑투‑엔드 솔루션을 제공합니다. + +## 배울 내용 + +- `AsposeAIModelConfig` 로 **HuggingFace 모델을 구성**하는 방법 +- Hugging Face 허브에서 **GGUF 모델(`fp16` 양자화)를 로드**하는 정확한 단계 +- 추론 호출을 감싸는 **Python 코드 타이밍** 재사용 패턴 +- `gpu_layers` 를 조정하여 **GPU 추론 최적화** 하는 팁 +- 예상 출력 및 타이밍이 정상인지 확인하는 방법 + +### 사전 요구 사항 + +| 요구 사항 | 이유 | +|-------------|----------------| +| Python 3.9+ | 최신 문법 및 타입 힌트를 사용하기 위해. | +| `asposeai` 패키지(또는 동등한 SDK) | `AsposeAI` 와 `AsposeAIModelConfig` 를 제공합니다. | +| Hugging Face 레포 `bartowski/Qwen2.5-3B-Instruct-GGUF` 에 대한 접근 권한 | 로드할 GGUF 모델입니다. | +| 최소 8 GB VRAM을 가진 GPU (선택 사항이지만 권장) | **GPU 추론 최적화** 단계를 수행할 수 있게 해줍니다. | + +SDK를 아직 설치하지 않았다면 다음 명령을 실행하세요: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![measure inference time diagram](https://example.com/measure-inference-time.png){alt="추론 시간 측정 다이어그램"} + +## 단계 1: GGUF 모델 로드 – HuggingFace 모델 구성 + +먼저 Aspose AI가 모델을 어디서 가져올지, 어떻게 다룰지를 알려주는 구성 객체가 필요합니다. 여기서 **GGUF 모델을 로드**하고 **huggingface 모델** 파라미터를 **구성**합니다. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**왜 중요한가요:** +- `hugging_face_repo_id` 는 허브에 있는 정확한 GGUF 파일을 가리킵니다. +- `fp16` 은 메모리 대역폭을 줄이면서 모델의 대부분 정확성을 유지합니다. +- `gpu_layers` 는 **GPU 추론 최적화** 성능을 조정하는 노브이며, GPU에 충분한 VRAM이 있다면 더 많은 레이어를 GPU에 배치할수록 지연 시간이 감소합니다. + +## 단계 2: Aspose AI 인스턴스 생성 + +모델 구성이 끝났으니 이제 `AsposeAI` 객체를 생성합니다. 이 단계는 간단하지만, SDK가 GGUF 파일을 (캐시되지 않은 경우) 다운로드하고 런타임을 준비하는 과정이 포함됩니다. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**프로 팁:** 첫 실행은 모델을 다운로드하고 GPU용으로 컴파일하느라 몇 초 정도 더 걸립니다. 이후 실행은 번개처럼 빠릅니다. + +## 단계 3: 추론 실행 및 **추론 시간 측정** + +튜토리얼의 핵심: `time.time()` 으로 추론 호출을 감싸 **추론 시간을 측정**합니다. 예시를 자체적으로 유지하기 위해 작은 OCR 결과를 입력으로 제공합니다. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**예상 출력:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +숫자가 크게 나오면 대부분의 레이어가 CPU에서 실행되고 있는 것입니다. 다음 단계로 넘어가 보세요. + +## 단계 4: **GPU 추론 최적화** – `gpu_layers` 튜닝 + +기본값 `gpu_layers=40` 이 너무 공격적이어서 OOM이 발생하거나, 너무 보수적이라 성능을 놓치고 있을 수 있습니다. 아래와 같은 간단한 루프를 사용해 최적 지점을 찾을 수 있습니다: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**왜 효과가 있나요:** +- 각 호출마다 다른 GPU 할당으로 런타임을 재구성하므로 지연 시간 변화를 즉시 확인할 수 있습니다. +- 이 루프는 **Python 코드 타이밍**을 재사용 가능한 형태로 보여주며, 다른 성능 테스트에도 적용할 수 있습니다. + +예를 들어 16 GB RTX 3080에서의 전형적인 출력은 다음과 같습니다: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +이 결과를 바탕으로 `gpu_layers=40` 을 해당 하드웨어에 최적의 값으로 선택하면 됩니다. + +## 전체 작업 예시 + +모든 내용을 하나로 합친 스크립트(`measure_inference.py`)를 아래에 제공합니다. 파일에 저장하고 실행하면 됩니다: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +실행 방법: + +```bash +python measure_inference.py +``` + +적절한 GPU가 있다면 1초 미만의 지연 시간을 확인할 수 있으며, 이를 통해 **추론 시간을 측정**하고 **GPU 추론 최적화**에 성공했음을 확인할 수 있습니다. + +--- + +## 자주 묻는 질문 (FAQs) + +**Q: 다른 양자화 형식에도 적용할 수 있나요?** +A: 물론입니다. 설정에서 `hugging_face_quantization="int8"`(또는 `q4_0` 등) 로 교체하고 벤치마크를 다시 실행하면 됩니다. 메모리 사용량 감소와 약간의 정확도 감소 사이의 트레이드오프가 발생합니다. + +**Q: GPU가 없으면 어떻게 하나요?** +A: `gpu_layers=0` 으로 설정하면 코드가 완전히 CPU로 전환됩니다. 이 경우에도 **추론 시간을 측정**할 수 있지만 숫자가 더 크게 나올 것입니다. + +**Q: 후처리를 제외하고 모델 순전파만 시간 측정하고 싶어요.** +A: 가능합니다. `ai_engine.run_model(...)`(또는 동등한 메서드)를 직접 호출하고 그 호출을 `time.time()` 으로 감싸면 됩니다. **Python 코드 타이밍** 패턴은 동일하게 유지됩니다. + +--- + +## 결론 + +이제 **GGUF 모델에 대한 추론 시간 측정**, Hugging Face에서 **GGUF 모델 로드**, 그리고 **GPU 추론 최적화** 설정을 위한 완전한 복사‑붙여넣기 솔루션을 갖추었습니다. `gpu_layers` 를 조정하고 양자화를 실험함으로써 매밀리초 단위의 성능을 끌어낼 수 있습니다. + +다음 단계로 고려해볼 수 있는 내용: + +- 이 타이밍 로직을 CI 파이프라인에 통합하여 회귀를 감지 +- 배치 추론을 탐색해 처리량 향상 +- 여기서 사용한 더미 텍스트 대신 실제 OCR 파이프라인과 모델을 결합 + +코딩을 즐기세요, 그리고 지연 시간이 언제나 낮게 유지되길 바랍니다! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/korean/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..914ef6233 --- /dev/null +++ b/ocr/korean/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-04-26 +description: Python의 OCR 엔진을 사용해 손글씨 텍스트를 인식합니다. 이미지에서 텍스트를 추출하고, 손글씨 모드를 켜며, 손글씨 + 메모를 빠르게 읽는 방법을 배워보세요. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: ko +og_description: Python으로 손글씨 텍스트를 인식합니다. 이 튜토리얼에서는 이미지에서 텍스트를 추출하고, 손글씨 모드를 켜며, 간단한 + OCR 엔진을 사용해 손글씨 메모를 읽는 방법을 보여줍니다. +og_title: Python으로 손글씨 텍스트 인식 – 완전한 OCR 가이드 +tags: +- OCR +- Python +- Handwriting Recognition +title: Python에서 손글씨 인식하기 – OCR 엔진 튜토리얼 +url: /ko/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python에서 손글씨 인식 – OCR Engine 튜토리얼 + +손글씨를 **recognize handwritten text** 해야 할 때, “어디서 시작해야 할까?” 라는 막막함을 느낀 적 있나요? 당신만 그런 것이 아닙니다. 회의 필기를 디지털화하거나 스캔한 양식에서 데이터를 추출하든, 신뢰할 수 있는 OCR 결과를 얻는 것은 유니콘을 잡는 듯한 느낌일 수 있습니다. + +좋은 소식: 몇 줄의 Python 코드만으로 **extract text from image** 파일을 처리하고, 손글씨 모드를 켜며, 이제는 **read handwritten notes** 를 위해 별도의 희귀 라이브러리를 찾지 않아도 됩니다. 이 가이드에서는 **create OCR engine python** 스타일 설정부터 화면에 결과를 출력하기까지 전체 과정을 단계별로 안내합니다. + +## What You’ll Learn + +- `ocr` 패키지를 사용해 **create OCR engine python** 인스턴스를 만드는 방법. +- 손글씨 지원이 내장된 언어 설정. +- 엔진에 손글씨임을 알리기 위한 **turn on handwritten mode** 정확한 호출 방법. +- 메모 사진을 입력해 **recognize handwritten text** 를 추출하는 방법. +- 다양한 이미지 포맷 처리, 흔히 발생하는 문제 해결 팁, 확장 방법. + +불필요한 내용 없이, “문서를 참고하세요” 같은 막다른 길 없이—오늘 바로 복사‑붙여넣기하고 테스트할 수 있는 완전 실행 가능한 스크립트를 제공합니다. + +## Prerequisites + +시작하기 전에 다음을 준비하세요: + +1. Python 3.8+ 설치 (코드에 f‑strings 사용). +2. 가상의 `ocr` 라이브러리 (`pip install ocr‑engine` – 실제 사용 중인 패키지 이름으로 교체). +3. 손글씨 메모가 담긴 선명한 이미지 파일 (JPEG, PNG, TIFF 지원). +4. 약간의 호기심—다른 모든 것은 아래에 설명됩니다. + +> **Pro tip:** 이미지에 노이즈가 많다면 Pillow로 간단히 전처리(`Image.open(...).convert('L')`)한 뒤 OCR 엔진에 전달하세요. 정확도가 크게 향상됩니다. + +## How to recognize handwritten text with Python + +아래는 **create OCR engine python** 객체를 만들고, 손글씨용으로 설정한 뒤 추출된 문자열을 출력하는 전체 스크립트입니다. `handwriting_ocr.py` 로 저장하고 터미널에서 실행하세요. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Expected Output + +스크립트가 정상적으로 실행되면 다음과 같은 출력이 나타납니다: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +OCR 엔진이 문자를 하나도 감지하지 못하면 `text` 필드가 빈 문자열이 됩니다. 이 경우 이미지 품질을 다시 확인하거나 고해상도 스캔을 시도하세요. + +## Step‑by‑Step Explanation + +### Step 1 – **create OCR engine python** instance + +`OcrEngine` 클래스가 진입점입니다. 빈 노트북과 같으며, 어떤 언어를 기대하고 손글씨인지 여부를 알려줄 때까지 아무 일도 일어나지 않습니다. + +### Step 2 – Choose a language that supports handwriting + +`ocr.Language.EXTENDED_LATIN` 은 단순히 “English” 가 아니라 라틴 기반 스크립트 집합이며, 손글씨 샘플로 학습된 모델을 포함합니다. 이 단계를 건너뛰면 엔진이 인쇄된 텍스트 모델을 기본으로 사용해 출력이 엉망이 될 수 있습니다. + +### Step 3 – **turn on handwritten mode** + +`enable_handwritten_mode(True)` 를 호출하면 내부 플래그가 전환됩니다. 엔진은 실제 메모에서 보이는 불규칙한 간격과 가변적인 획 두께에 맞춰 조정된 신경망으로 전환됩니다. 이 줄을 빼먹는 경우 엔진이 필기를 잡음으로 처리하는 흔한 실수입니다. + +### Step 4 – Feed the image and **recognize handwritten text** + +`recognize_image` 가 핵심 작업을 수행합니다: 비트맵을 전처리하고, 손글씨 모델을 통해 실행한 뒤 `text` 속성을 가진 객체를 반환합니다. 품질 지표가 필요하면 `handwritten_result.confidence` 도 확인할 수 있습니다. + +### Step 5 – Print the result and **read handwritten notes** + +`print(handwritten_result.text)` 는 **extract text from image** 가 성공했는지 가장 간단히 확인하는 방법입니다. 실제 서비스에서는 문자열을 데이터베이스에 저장하거나 다른 서비스에 전달할 것입니다. + +## Handling Edge Cases & Common Variations + +| Situation | What to Do | +|-----------|------------| +| **Image is rotated** | `recognize_image` 호출 전에 Pillow의 `Image.rotate(angle)` 로 회전시킵니다. | +| **Low contrast** | 그레이스케일로 변환하고 적응형 임계값(`Image.point(lambda p: p > 128 and 255)`)을 적용합니다. | +| **Multiple pages** | 파일 경로 리스트를 순회하면서 결과를 연결합니다. | +| **Non‑Latin scripts** | `EXTENDED_LATIN` 을 `ocr.Language.CHINESE`(또는 해당 언어) 로 교체하고 `enable_handwritten_mode(True)` 를 유지합니다. | +| **Performance concerns** | 여러 이미지에 대해 동일한 `ocr_engine` 인스턴스를 재사용하세요; 매번 초기화하면 오버헤드가 발생합니다. | + +### Pro tip on memory usage + +수백 개의 메모를 배치 처리한다면 작업이 끝난 뒤 `ocr_engine.dispose()` 를 호출해 주세요. Python 래퍼가 보유하고 있을 수 있는 네이티브 리소스를 해제합니다. + +## Quick Visual Recap + +![recognize handwritten text example](https://example.com/handwritten-note.png "recognize handwritten text example") + +*위 이미지는 스크립트가 일반 텍스트로 변환할 수 있는 전형적인 손글씨 메모를 보여줍니다.* + +## Full Working Example (One‑File Script) + +복사‑붙여넣기만으로 간편하게 사용하고 싶은 분들을 위해, 설명 주석을 제외한 전체 코드를 다시 제공합니다: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +다음 명령으로 실행합니다: + +```bash +python handwriting_ocr.py +``` + +콘솔에 **recognize handwritten text** 결과가 표시될 것입니다. + +## Conclusion + +우리는 **recognize handwritten text** 를 Python에서 수행하기 위한 모든 과정을 다루었습니다—새로운 **create OCR engine python** 호출, 올바른 언어 선택, **turn on handwritten mode** 활성화, 그리고 **extract text from image** 로 **read handwritten notes** 를 얻는 과정까지. + +단일, 독립형 스크립트 하나로 흐릿한 회의 사진을 깔끔하고 검색 가능한 텍스트로 변환할 수 있습니다. 다음 단계로는 출력 결과를 자연어 파이프라인에 연결하거나, 검색 가능한 인덱스에 저장하거나, 음성 합성을 위한 전사 서비스에 다시 전달하는 것을 고려해 보세요. + +### Where to Go From Here? + +- **Batch processing:** 폴더에 있는 스캔 파일들을 처리하도록 스크립트를 루프로 감싸세요. +- **Confidence filtering:** `result.confidence` 를 사용해 품질이 낮은 결과를 걸러냅니다. +- **Alternative libraries:** `ocr` 가 완벽하지 않다면 `pytesseract` 와 `--psm 13` 옵션을 활용해 손글씨 모드를 시도해 보세요. +- **UI integration:** Flask 또는 FastAPI와 결합해 웹 기반 업로드 서비스를 제공합니다. + +특정 이미지 포맷에 대한 질문이 있거나 모델 튜닝이 필요하면 아래 댓글로 알려 주세요. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/polish/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..b5a907913 --- /dev/null +++ b/ocr/polish/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,192 @@ +--- +category: general +date: 2026-04-26 +description: Dowiedz się, jak pobrać model HuggingFace w Pythonie i wyodrębnić tekst + z obrazu w Pythonie, jednocześnie poprawiając dokładność OCR w Pythonie przy użyciu + Aspose OCR Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: pl +og_description: pobierz model huggingface w Pythonie i zwiększ wydajność swojego potoku + OCR. Postępuj zgodnie z tym przewodnikiem, aby wyodrębnić tekst z obrazu w Pythonie + i poprawić dokładność OCR w Pythonie. +og_title: pobierz model huggingface python – Kompletny samouczek ulepszania OCR +tags: +- OCR +- HuggingFace +- Python +- AI +title: pobierz model huggingface python – Przewodnik krok po kroku po zwiększeniu + OCR +url: /pl/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – Kompletny samouczek ulepszania OCR + +Czy kiedykolwiek próbowałeś **download HuggingFace model python** i czułeś się nieco zagubiony? Nie jesteś jedyny. W wielu projektach największym wąskim gardłem jest pobranie dobrego modelu na swój komputer, a następnie uczynienie wyników OCR naprawdę użytecznymi. + +W tym przewodniku przeprowadzimy Cię przez praktyczny przykład, który pokaże dokładnie, jak **download HuggingFace model python**, wyodrębnić tekst z obrazu przy użyciu **extract text from image python**, a następnie **improve OCR accuracy python** z wykorzystaniem AI post‑processora Aspose. Na koniec będziesz mieć gotowy do uruchomienia skrypt, który zamieni zaszumiony obraz faktury w czysty, czytelny tekst — bez magii, tylko jasne kroki. + +## Czego będziesz potrzebować + +- Python 3.9+ (kod działa również na 3.11) +- Połączenie internetowe do jednorazowego pobrania modelu +- Pakiet `asposeocrcloud` (`pip install asposeocrcloud`) +- Przykładowy obraz (np. `sample_invoice.png`) umieszczony w folderze, którym zarządzasz + +To wszystko — bez ciężkich frameworków, bez sterowników specyficznych dla GPU, chyba że chcesz przyspieszyć działanie. + +Teraz zanurzmy się w rzeczywistą implementację. + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## Krok 1: Skonfiguruj silnik OCR i wybierz język +*(Tutaj zaczynamy **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Dlaczego to ważne:** +Silnik OCR jest pierwszą linią obrony; wybór odpowiedniego pakietu językowego natychmiast zmniejsza błędy rozpoznawania znaków, co jest kluczową częścią **improve OCR accuracy python**. + +## Krok 2: Skonfiguruj model AsposeAI – pobieranie z HuggingFace +*(Tutaj faktycznie **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**Co się dzieje w tle?** +Gdy `allow_auto_download` jest ustawione na true, SDK kontaktuje się z HuggingFace, pobiera model `Qwen2.5‑3B‑Instruct‑GGUF` i zapisuje go w wskazanym folderze. To jest sedno **download huggingface model python** — SDK zajmuje się ciężką pracą, więc nie musisz sam pisać poleceń `git clone` ani `wget`. + +*Wskazówka:* Trzymaj `directory_model_path` na dysku SSD, aby przyspieszyć ładowanie; model ma około 3 GB nawet w formacie `int8`. + +## Krok 3: Połącz silnik AI z silnikiem OCR +*(Łącząc oba elementy, abyśmy mogli **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Dlaczego je łączyć?** +Silnik OCR dostarcza surowy tekst, który może zawierać literówki, przerwane linie lub niewłaściwą interpunkcję. Silnik AI działa jak inteligentny edytor, usuwając te problemy — dokładnie to, czego potrzebujesz, aby **improve OCR accuracy python**. + +## Krok 4: Uruchom OCR na swoim obrazie +*(Moment, w którym w końcu **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` teraz zawiera atrybut `text` z surowymi znakami, które silnik rozpoznał. W praktyce zauważysz kilka drobnych problemów — np. „Invoice” zamieni się w „Inv0ice” lub pojawi się podział linii w środku zdania. + +## Krok 5: Oczyść wynik przy użyciu AI Post‑Processora +*(Ten krok bezpośrednio **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +Model AI przepisuje tekst, stosując poprawki zależne od języka. Ponieważ użyliśmy modelu dostosowanego instrukcją z HuggingFace, wynik jest zazwyczaj płynny i gotowy do dalszego przetwarzania. + +## Krok 6: Pokaż przed i po +*(Szybka kontrola, aby zobaczyć, jak dobrze **extract text from image python** i **improve OCR accuracy python**.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Oczekiwany wynik + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Zauważ, jak AI poprawiło „Inv0ice” na „Invoice” i wygładziło niechciane podziały linii. To namacalny rezultat **improve OCR accuracy python** przy użyciu pobranego modelu HuggingFace. + +## Najczęściej zadawane pytania (FAQ) + +### Czy potrzebuję GPU do uruchomienia modelu? +Nie. Ustawienie `gpu_layers=20` instruuje SDK, aby używało do 20 warstw GPU, jeśli dostępny jest kompatybilny procesor graficzny; w przeciwnym razie przełącza się na CPU. Na nowoczesnym laptopie ścieżka CPU nadal przetwarza kilkaset tokenów na sekundę — idealne do okazjonalnego parsowania faktur. + +### Co zrobić, jeśli model nie uda się pobrać? +Upewnij się, że Twoje środowisko może połączyć się z `https://huggingface.co`. Jeśli jesteś za korporacyjnym proxy, ustaw zmienne środowiskowe `HTTP_PROXY` i `HTTPS_PROXY`. SDK będzie automatycznie ponawiało próbę, ale możesz także ręcznie wykonać `git lfs pull` repozytorium do `directory_model_path`. + +### Czy mogę zamienić model na mniejszy? +Oczywiście. Po prostu zamień `hugging_face_repo_id` na inne repozytorium (np. `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) i odpowiednio dostosuj `hugging_face_quantization`. Mniejsze modele pobierają się szybciej i zużywają mniej RAM, choć możesz stracić nieco jakości korekcji. + +### Jak to pomaga mi **extract text from image python** w innych dziedzinach? +Ten sam pipeline działa dla paragonów, paszportów czy odręcznych notatek. Jedyną zmianą jest pakiet językowy (`ocr.Language.FRENCH` itp.) oraz ewentualnie specyficzny dla domeny model dostrojony w HuggingFace. + +## Bonus: Automatyzacja wielu plików + +Jeśli masz folder pełen obrazów, otocz wywołanie OCR prostą pętlą: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +To małe rozszerzenie pozwala **download huggingface model python** raz, a następnie przetwarzać wsadowo dziesiątki plików — świetne do skalowania Twojego pipeline’u automatyzacji dokumentów. + +## Zakończenie + +Przeszliśmy właśnie przez kompletny, end‑to‑end przykład, który pokazuje, jak **download HuggingFace model python**, **extract text from image python** i **improve OCR accuracy python** przy użyciu Aspose OCR Cloud oraz AI post‑processora. Skrypt jest gotowy do uruchomienia, koncepcje zostały wyjaśnione, a Ty widziałeś wynik przed i po, więc wiesz, że działa. + +Co dalej? Spróbuj zamienić na inny model HuggingFace, poeksperymentuj z innymi pakietami językowymi lub przekaż wyczyszczony tekst do dalszego pipeline’u NLP (np. ekstrakcja encji dla pozycji faktury). Nie ma granic, a fundament, który właśnie zbudowałeś, jest solidny. + +Masz pytania lub trudny obraz, który wciąż sprawia problemy OCR? Dodaj komentarz poniżej i rozwiążmy to razem. Szczęśliwego kodowania! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/polish/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..3029bef8e --- /dev/null +++ b/ocr/polish/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-04-26 +description: Szybko pobierz model OCR używając Aspose OCR Python. Dowiedz się, jak + ustawić katalog modelu, skonfigurować ścieżkę modelu i jak pobrać model w kilku + linijkach. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: pl +og_description: Pobierz model OCR w kilka sekund za pomocą Aspose OCR Python. Ten + przewodnik pokazuje, jak ustawić katalog modelu, skonfigurować ścieżkę modelu oraz + jak bezpiecznie pobrać model. +og_title: pobierz model OCR – Kompletny samouczek Aspose OCR w Pythonie +tags: +- OCR +- Python +- Aspose +title: Pobierz model OCR z Aspose OCR Python – Przewodnik krok po kroku +url: /pl/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – Kompletny samouczek Aspose OCR w Pythonie + +Zastanawiałeś się kiedyś, jak **pobrać model OCR** przy użyciu Aspose OCR w Pythonie, nie przeszukując nieskończonych dokumentacji? Nie jesteś sam. Wielu programistów napotyka problem, gdy model nie jest dostępny lokalnie, a SDK wyrzuca niejasny błąd. Dobra wiadomość? Naprawa wymaga zaledwie kilku linii kodu i model będzie gotowy w kilka minut. + +W tym samouczku przejdziemy krok po kroku przez wszystko, co musisz wiedzieć: od importu odpowiednich klas, przez **ustawienie katalogu modelu**, po **sposób pobrania modelu**, a na końcu weryfikację ścieżki. Po zakończeniu będziesz mógł uruchomić OCR na dowolnym obrazie jednym wywołaniem funkcji oraz zrozumiesz opcje **konfiguracji ścieżki modelu**, które utrzymają Twój projekt w porządku. Bez zbędnych wstępów, tylko praktyczny, gotowy do uruchomienia przykład dla użytkowników **aspose ocr python**. + +## Co się nauczysz + +- Jak poprawnie zaimportować klasy Aspose OCR Cloud. +- Dokładne kroki, aby **pobrać model OCR** automatycznie. +- Sposoby **ustawienia katalogu modelu** i **konfiguracji ścieżki modelu** dla powtarzalnych buildów. +- Jak zweryfikować, że model został zainicjowany i gdzie znajduje się na dysku. +- Typowe pułapki (uprawnienia, brakujące katalogi) oraz szybkie rozwiązania. + +### Wymagania wstępne + +- Python 3.8+ zainstalowany na Twoim komputerze. +- Pakiet `asposeocrcloud` (`pip install asposeocrcloud`). +- Uprawnienia zapisu do folderu, w którym chcesz przechowywać model (np. `C:\models` lub `~/ocr_models`). + +--- + +## Krok 1: Importowanie klas Aspose OCR Cloud + +Pierwszą rzeczą, której potrzebujesz, jest właściwe polecenie importu. Dzięki niemu zostaną wczytane klasy zarządzające konfiguracją modelu i operacjami OCR. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Dlaczego to ważne:* `AsposeAI` jest silnikiem, który wykona OCR, natomiast `AsposeAIModelConfig` informuje silnik, **gdzie** szukać modelu i **czy** ma go pobrać automatycznie. Pominięcie tego kroku lub import niewłaściwego modułu spowoduje `ModuleNotFoundError` jeszcze przed rozpoczęciem pobierania. + +--- + +## Krok 2: Definicja konfiguracji modelu (Ustaw katalog modelu i skonfiguruj ścieżkę modelu) + +Teraz mówimy Aspose, gdzie mają być przechowywane pliki modelu. To właśnie miejsce, w którym **ustawiasz katalog modelu** i **konfigurujesz ścieżkę modelu**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Wskazówki i pułapki** + +- **Ścieżki bezwzględne** zapobiegają nieporozumieniom, gdy skrypt uruchamiany jest z innego katalogu roboczego. +- Na Linux/macOS możesz używać `"/home/you/ocr_models"`; na Windowsie poprzedź ścieżkę `r`, aby traktować odwrotne ukośniki dosłownie. +- Ustawienie `allow_auto_download="true"` jest kluczem do **sposobu pobrania modelu** bez dodatkowego kodu. + +--- + +## Krok 3: Utworzenie instancji AsposeAI przy użyciu konfiguracji + +Gdy konfiguracja jest gotowa, tworzysz silnik OCR. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Dlaczego to ważne:* Obiekt `ocr_ai` teraz zawiera konfigurację, którą właśnie zdefiniowaliśmy. Jeśli model nie jest dostępny, kolejne wywołanie automatycznie uruchomi pobranie — to sedno **sposobu pobrania modelu** w trybie „hands‑off”. + +--- + +## Krok 4: Wywołanie pobrania modelu (jeśli jest potrzebne) + +Zanim będziesz mógł uruchomić OCR, musisz upewnić się, że model znajduje się na dysku. Metoda `is_initialized()` zarówno sprawdza, jak i wymusza inicjalizację. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**Co się dzieje pod maską?** + +- Pierwsze wywołanie `is_initialized()` zwraca `False`, ponieważ katalog modelu jest pusty. +- `print` informuje użytkownika, że zaraz rozpocznie się pobranie. +- Drugie wywołanie wymusza pobranie modelu z repozytorium Hugging Face, które podałeś wcześniej. +- Po pobraniu metoda zwraca `True` przy kolejnych sprawdzeniach. + +**Przypadek brzegowy:** Jeśli Twoja sieć blokuje Hugging Face, pojawi się wyjątek. W takim wypadku pobierz ręcznie plik zip modelu, rozpakuj go w `directory_model_path` i uruchom skrypt ponownie. + +--- + +## Krok 5: Raportowanie lokalnej ścieżki, w której model jest dostępny + +Po zakończeniu pobierania prawdopodobnie będziesz chciał wiedzieć, gdzie trafiły pliki. To pomaga w debugowaniu oraz przy konfigurowaniu pipeline’ów CI. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Typowy wynik wygląda tak: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Teraz udało Ci się **pobrać model OCR**, ustawić katalog i potwierdzić ścieżkę. + +--- + +## Przegląd wizualny + +Poniżej prosty diagram ilustrujący przepływ od konfiguracji do gotowego do użycia modelu. + +![diagram przepływu pobierania modelu OCR pokazujący konfigurację, automatyczne pobranie i lokalną ścieżkę](/images/download-ocr-model-flow.png) + +*Tekst alternatywny zawiera główne słowo kluczowe dla SEO.* + +--- + +## Typowe warianty i jak sobie z nimi radzić + +### 1. Użycie innego repozytorium modelu + +Jeśli potrzebujesz modelu innego niż `openai/gpt2`, po prostu zamień wartość `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Upewnij się, że repozytorium jest publiczne lub że masz ustawiony niezbędny token w środowisku. + +### 2. Wyłączenie automatycznego pobierania + +Czasami chcesz kontrolować pobieranie samodzielnie (np. w środowiskach odciętych od sieci). Ustaw `allow_auto_download` na `"false"` i wywołaj własny skrypt pobierający przed inicjalizacją: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Zmiana katalogu modelu w czasie działania + +Możesz zmienić ścieżkę bez tworzenia nowego obiektu `AsposeAI`: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Profesjonalne wskazówki dla środowisk produkcyjnych + +- **Cache'owanie modelu**: Trzymaj katalog na współdzielonym dysku sieciowym, jeśli wiele usług korzysta z tego samego modelu. Dzięki temu unikniesz zbędnych pobrań. +- **Zablokowanie wersji**: Repozytorium Hugging Face może się aktualizować. Aby zablokować konkretną wersję, dopisz `@v1.0.0` do ID repozytorium (`"openai/gpt2@v1.0.0"`). +- **Uprawnienia**: Upewnij się, że użytkownik uruchamiający skrypt ma prawa odczytu/zapisu w `directory_model_path`. Na Linuxie zazwyczaj wystarczy `chmod 755`. +- **Logowanie**: Zastąp proste instrukcje `print` modułem `logging` Pythona, aby uzyskać lepszą obserwowalność w większych aplikacjach. + +--- + +## Pełny działający przykład (gotowy do kopiowania) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Oczekiwany wynik** (pierwsze uruchomienie pobierze model, kolejne pominą pobieranie): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Uruchom skrypt ponownie; zobaczysz tylko linię ze ścieżką, ponieważ model jest już w pamięci podręcznej. + +--- + +## Zakończenie + +Omówiliśmy kompletny proces **pobierania modelu OCR** przy użyciu Aspose OCR w Pythonie, pokazaliśmy, jak **ustawić katalog modelu**, oraz wyjaśniliśmy niuanse **konfiguracji ścieżki modelu**. Kilka linijek kodu pozwala zautomatyzować pobranie, uniknąć ręcznych kroków i utrzymać pipeline OCR w stanie reprodukowalnym. + +Następnie możesz zbadać rzeczywiste wywołanie OCR (`ocr_ai.recognize_image(...)`) lub wypróbować inny model Hugging Face, aby zwiększyć dokładność. Niezależnie od wyboru, fundament, który zbudowałeś — jasna konfiguracja, automatyczne pobranie i weryfikacja ścieżki — ułatwi każdą przyszłą integrację. + +Masz pytania dotyczące przypadków brzegowych lub chcesz podzielić się, jak dostosowałeś katalog modelu w chmurze? zostaw komentarz poniżej i powodzenia w kodowaniu! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/polish/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..b58196109 --- /dev/null +++ b/ocr/polish/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-04-26 +description: Jak przetwarzać wyniki OCR i wyodrębniać tekst z współrzędnymi. Poznaj + rozwiązanie krok po kroku, wykorzystujące strukturalny wynik i korektę AI. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: pl +og_description: Jak przetwarzać wyniki OCR i wyodrębniać tekst z współrzędnymi. Skorzystaj + z tego kompleksowego poradnika, aby uzyskać niezawodny przepływ pracy. +og_title: Jak przetwarzać wyniki OCR – Kompletny przewodnik +tags: +- OCR +- Python +- AI +- Text Extraction +title: Jak przetwarzać wyniki OCR – wyodrębnić tekst z współrzędnymi w Pythonie +url: /pl/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak przetwarzać wyniki OCR – wyodrębnić tekst z współrzędnymi w Pythonie + +Czy kiedykolwiek potrzebowałeś **jak przetwarzać OCR** wyniki, ponieważ surowe wyjście było zaszumione lub nie wyrównane? Nie jesteś jedyny. W wielu rzeczywistych projektach — skanowanie faktur, digitalizacja paragonów czy nawet wzbogacanie doświadczeń AR — silnik OCR zwraca surowe słowa, ale nadal musisz je oczyścić i śledzić, gdzie każde słowo znajduje się na stronie. To właśnie tryb strukturalnego wyjścia połączony z napędzanym AI post‑procesorem błyszczy. + +> **Wskazówka:** Jeśli używasz innej biblioteki OCR, poszukaj trybu „structured” lub „layout”; koncepcje pozostają takie same. + +--- + +## Wymagania wstępne + +| Wymaganie | Dlaczego jest ważne | +|-------------|----------------| +| Python 3.9+ | Nowoczesna składnia i wskazówki typów | +| `ocr` library that supports `OutputMode.STRUCTURED` (e.g., a fictional `myocr`) | Wymagana do danych bounding‑box | +| An AI post‑processing module (could be OpenAI, HuggingFace, or a custom model) | Poprawia dokładność po OCR | +| An image file (`input.png`) in your working directory | Źródło, które odczytamy | + +Jeśli któreś z nich jest nieznane, po prostu zainstaluj pakiety zastępcze za pomocą `pip install myocr ai‑postproc`. Poniższy kod zawiera również awaryjne stuby, abyś mógł przetestować przepływ bez rzeczywistych bibliotek. + +--- + +## Krok 1: Włącz tryb strukturalnego wyjścia dla silnika OCR + +Pierwszą rzeczą, którą robimy, jest poinstruowanie silnika OCR, aby zwrócił nam więcej niż zwykły tekst. Strukturalne wyjście zwraca każde słowo wraz z jego ramką ograniczającą i wynikiem pewności, co jest niezbędne do **wyodrębniania tekstu z współrzędnymi** później. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Dlaczego to ważne:* Bez trybu strukturalnego otrzymałbyś tylko długi ciąg znaków i straciłbyś informacje przestrzenne potrzebne do nakładania tekstu na obrazy lub przekazywania do dalszej analizy układu. + +--- + +## Krok 2: Rozpoznaj obraz i przechwyć słowa, ramki i pewność + +Teraz wprowadzamy obraz do silnika. Wynikiem jest obiekt zawierający listę obiektów słów, z których każdy udostępnia `text`, `x`, `y`, `width`, `height` oraz `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Przypadek brzegowy:* Jeśli obraz jest pusty lub nieczytelny, `structured_result.words` będzie pustą listą. Dobrą praktyką jest sprawdzenie tego i obsłużenie tego w sposób elegancki. + +--- + +## Krok 3: Uruchom post‑procesing oparty na AI, zachowując pozycje + +Nawet najlepsze silniki OCR popełniają błędy — pomyśl o „O” vs. „0” lub brakujących diakrytykach. Model AI wytrenowany na tekście specyficznym dla domeny może skorygować te błędy. Co najważniejsze, zachowujemy oryginalne współrzędne, aby układ przestrzenny pozostał nienaruszony. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Dlaczego zachowujemy współrzędne:* Wiele zadań dalszych (np. generowanie PDF, etykietowanie AR) zależy od dokładnego rozmieszczenia. AI modyfikuje tylko pole `text`, pozostawiając `x`, `y`, `width`, `height` niezmienione. + +--- + +## Krok 4: Iteruj po poprawionych słowach i wyświetl ich tekst z współrzędnymi + +Na koniec iterujemy po poprawionych słowach i drukujemy każde słowo wraz z jego lewym górnym rogiem `(x, y)`. Spełnia to cel **wyodrębniania tekstu z współrzędnymi**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Oczekiwany wynik (przykład):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Każda linia pokazuje poprawione słowo i jego dokładną lokalizację na oryginalnym obrazie. + +--- + +## Pełny działający przykład + +Poniżej znajduje się pojedynczy skrypt, który łączy wszystko razem. Możesz go skopiować‑wkleić, dostosować instrukcje importu do swoich rzeczywistych bibliotek i uruchomić bezpośrednio. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Uruchamianie skryptu** + +```bash +python ocr_postprocess_demo.py +``` + +Jeśli masz zainstalowane rzeczywiste biblioteki, skrypt przetworzy twój `input.png`. W przeciwnym razie implementacja stub pozwoli zobaczyć oczekiwany przepływ i wynik bez żadnych zewnętrznych zależności. + +--- + +## Najczęściej zadawane pytania (FAQ) + +| Pytanie | Odpowiedź | +|----------|--------| +| *Czy to działa z Tesseract?* | Sam Tesseract nie udostępnia trybu strukturalnego od razu, ale wrappery takie jak `pytesseract.image_to_data` zwracają ramki ograniczające, które możesz przekazać do tego samego post‑procesora AI. | +| *Co jeśli potrzebuję prawego dolnego rogu zamiast lewego górnego?* | Każdy obiekt słowa udostępnia również `width` i `height`. Oblicz `x2 = x + width` i `y2 = y + height`, aby uzyskać przeciwległy róg. | +| *Czy mogę przetwarzać wiele obrazów wsadowo?* | Oczywiście. Owiń kroki w pętli `for image_path in Path("folder").glob("*.png"):` i zbieraj wyniki dla każdego pliku. | +| *Jak wybrać model AI do korekcji?* | Do ogólnego tekstu działa mały GPT‑2 dostrojony na błędy OCR. Do danych specyficznych dla domeny (np. recept medycznych) wytrenuj model sekwencja‑do‑sekwencji na sparowanych danych zaszumionych‑czystych. | +| *Czy wynik pewności jest przydatny po korekcji AI?* | Możesz nadal zachować oryginalną pewność do debugowania, ale AI może zwrócić własny wynik pewności, jeśli model to obsługuje. | + +## Przypadki brzegowe i najlepsze praktyki + +1. **Puste lub uszkodzone obrazy** – zawsze weryfikuj, że `structured_result.words` nie jest pusty przed kontynuacją. +2. **Skrypty niełacińskie** – upewnij się, że silnik OCR jest skonfigurowany na docelowy język; post‑procesor AI musi być wytrenowany na tym samym skrypcie. +3. **Wydajność** – korekcja AI może być kosztowna. Buforuj wyniki, jeśli będziesz ponownie używać tego samego obrazu, lub uruchom krok AI asynchronicznie. +4. **System współrzędnych** – biblioteki OCR mogą używać różnych początków (lewy górny vs. lewy dolny). Dostosuj odpowiednio przy nakładaniu na PDF‑y lub płótna. + +## Podsumowanie + +Masz teraz solidny, kompleksowy przepis na **jak przetwarzać OCR** i niezawodne **wyodrębnianie tekstu z współrzędnymi**. Dzięki włączeniu strukturalnego wyjścia, przekazaniu wyniku przez warstwę korekcji AI i zachowaniu oryginalnych ramek ograniczających, możesz przekształcić zaszumione skany OCR w czysty, świadomy przestrzennie tekst gotowy do dalszych zadań, takich jak generowanie PDF, automatyzacja wprowadzania danych czy nakładki rzeczywistości rozszerzonej. + +Gotowy na kolejny krok? Spróbuj zamienić stub AI na wywołanie OpenAI `gpt‑4o‑mini`, lub zintegrować pipeline z FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/polish/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..a0296f650 --- /dev/null +++ b/ocr/polish/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-04-26 +description: Jak szybko rozpoznawać obrazy w Pythonie. Poznaj pipeline rozpoznawania + obrazów, przetwarzanie wsadowe i automatyzuj rozpoznawanie obrazów przy użyciu sztucznej + inteligencji. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: pl +og_description: Jak szybko rozpoznawać obrazy w Pythonie. Ten przewodnik przeprowadza + przez pipeline rozpoznawania obrazów, batchowanie i automatyzację przy użyciu AI. +og_title: Jak rozpoznawać obrazy – Zautomatyzuj pipeline rozpoznawania obrazów +tags: +- image-processing +- python +- ai +title: Jak rozpoznawać obrazy – Zautomatyzuj pipeline rozpoznawania obrazów +url: /pl/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak rozpoznawać obrazy – Automatyzacja potoku rozpoznawania obrazów + +Zastanawiałeś się kiedyś **jak rozpoznawać obrazy** bez pisania tysięcy linii kodu? Nie jesteś sam — wielu programistów napotyka ten sam problem, gdy po raz pierwszy muszą przetworzyć dziesiątki lub setki zdjęć. Dobra wiadomość? Dzięki kilku prostym krokom możesz uruchomić w pełni funkcjonalny potok rozpoznawania obrazów, który grupuje, uruchamia i sprząta wszystko samodzielnie. + +W tym samouczku przeprowadzimy Cię przez kompletny, gotowy do uruchomienia przykład, który pokazuje **jak grupować obrazy**, podawać każdy z nich do silnika AI, przetwarzać wyniki i ostatecznie zwalniać zasoby. Po zakończeniu będziesz mieć samodzielny skrypt, który możesz wkleić do dowolnego projektu, niezależnie od tego, czy tworzysz tagger zdjęć, system kontroli jakości, czy generator zbioru danych badawczych. + +## Co się nauczysz + +- **Jak rozpoznawać obrazy** przy użyciu symulowanego silnika AI (wzorzec jest identyczny dla rzeczywistych usług takich jak TensorFlow, PyTorch czy API w chmurze). +- Jak zbudować **potok rozpoznawania obrazów**, który efektywnie obsługuje partie. +- Najlepszy sposób na **automatyzację rozpoznawania obrazów**, aby nie musieć ręcznie iterować po plikach za każdym razem. +- Wskazówki dotyczące skalowania potoku i bezpiecznego zwalniania zasobów. + +> **Wymagania wstępne:** Python 3.8+, podstawowa znajomość funkcji i pętli oraz kilka plików obrazów (lub ścieżek), które chcesz przetworzyć. Do podstawowego przykładu nie są potrzebne zewnętrzne biblioteki, ale wspomnimy, gdzie można podłączyć prawdziwe SDK AI. + +![Diagram jak rozpoznawać obrazy w potoku przetwarzania wsadowego](pipeline.png "Diagram rozpoznawania obrazów") + +## Krok 1: Grupowanie obrazów – Jak efektywnie grupować obrazy + +Zanim AI zacznie wykonywać ciężką pracę, potrzebujesz zbioru obrazów, które możesz mu podać. Pomyśl o tym jak o liście zakupów; silnik później pobierze każdy element z listy po kolei. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Dlaczego grupować?** +Grupowanie zmniejsza ilość kodu szablonowego, który musisz napisać, i ułatwia późniejsze dodanie równoległości. Jeśli kiedykolwiek będziesz musiał przetworzyć 10 000 zdjęć, zmienisz tylko źródło `image_batch` — reszta potoku pozostanie niezmieniona. + +## Krok 2: Uruchomienie potoku rozpoznawania obrazów (Rozpoznawanie obrazów przy użyciu AI) + +Teraz podłączamy grupę do rzeczywistego rozpoznawacza. W rzeczywistym scenariuszu możesz wywołać `torchvision.models` lub endpoint w chmurze; tutaj symulujemy zachowanie, aby samouczek pozostał samodzielny. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Wyjaśnienie:** +- `engine.recognize_image` jest sercem **potoku rozpoznawania obrazów**; może to być wywołanie modelu deep‑learningowego lub API REST. +- `postprocessor.run` demonstruje **automatyzację rozpoznawania obrazów** poprzez normalizację surowych prognoz do czystego słownika, który możesz zapisać lub przesłać. +- Zbieramy każdy słownik `corrected` w `recognized_results`, aby dalsze kroki (np. wstawianie do bazy danych) były proste. + +## Krok 3: Post‑procesowanie i przechowywanie – Automatyzacja wyników rozpoznawania obrazów + +Po uzyskaniu uporządkowanej listy prognoz zazwyczaj chcesz je zachować. Poniższy przykład zapisuje plik CSV; możesz swobodnie zamienić go na bazę danych lub kolejkę komunikatów. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Dlaczego CSV?** +CSV jest uniwersalnie czytelny — Excel, pandas, a nawet edytory tekstu mogą go otworzyć. Jeśli później będziesz musiał **automatyzować rozpoznawanie obrazów** na dużą skalę, zamień blok zapisu na masowy insert do Twojego jeziora danych. + +## Krok 4: Sprzątanie – Bezpieczne zwalnianie zasobów AI + +Wiele SDK AI przydziela pamięć GPU lub uruchamia wątki robocze. Zapomnienie o ich zwolnieniu może prowadzić do wycieków pamięci i poważnych awarii. Mimo że nasze obiekty symulacyjne nie wymagają tego, pokażemy właściwy wzorzec. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +Uruchomienie skryptu wypisuje przyjazne potwierdzenie, informując, że potok zakończył się pomyślnie. + +## Pełny działający skrypt + +Łącząc wszystko razem, oto kompletny, gotowy do skopiowania i wklejenia program: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Oczekiwany wynik + +Gdy uruchomisz skrypt (zakładając, że trzy przykładowe ścieżki istnieją), zobaczysz coś podobnego do: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +A wygenerowany plik `recognition_results.csv` będzie zawierał: + +| obraz | etykieta | pewność | +|---------------------|----------|----------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Podsumowanie + +Masz teraz solidny, kompleksowy przykład **jak rozpoznawać obrazy** w Pythonie, wraz z **potokiem rozpoznawania obrazów**, obsługą partii i automatycznym post‑procesowaniem. Wzorzec skaluje się: zamień klasy symulacyjne na prawdziwy model, podaj większą `image_batch` i masz rozwiązanie gotowe do produkcji. + +Chcesz iść dalej? Wypróbuj następujące kroki: + +- Zastąp `MockEngine` modelem TensorFlow lub PyTorch, aby uzyskać rzeczywiste prognozy. +- Zrównoleglij pętlę przy użyciu `concurrent.futures.ThreadPoolExecutor`, aby przyspieszyć duże partie. +- Podłącz zapis CSV do koszyka w chmurze, aby **automatyzować rozpoznawanie obrazów** w rozproszonych węzłach. + +Śmiało eksperymentuj, psuj rzeczy i potem je naprawiaj — tak naprawdę opanujesz potoki rozpoznawania obrazów. Jeśli napotkasz problemy lub masz pomysły na ulepszenia, zostaw komentarz poniżej. Szczęśliwego kodowania! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/polish/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..d62687cce --- /dev/null +++ b/ocr/polish/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-26 +description: Szybko maskuj numery kart kredytowych przy użyciu post‑procesingu OCR + AsposeAI. Poznaj zgodność z PCI, maskowanie przy użyciu wyrażeń regularnych oraz + sanitację danych w samouczku krok po kroku. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: pl +og_description: Maskuj numery kart kredytowych w wynikach OCR za pomocą AsposeAI. + Ten samouczek obejmuje zgodność z PCI, maskowanie wyrażeniami regularnymi i sanitację + danych. +og_title: Maskowanie numerów kart kredytowych – Kompletny przewodnik po post‑procesingu + OCR w Pythonie +tags: +- OCR +- Python +- security +title: Maskowanie numerów kart kredytowych w wynikach OCR – Kompletny przewodnik Pythona +url: /pl/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maskowanie numerów kart kredytowych – Kompletny przewodnik w Pythonie + +Czy kiedykolwiek musiałeś **maskować numery kart kredytowych** w tekście pochodzącym bezpośrednio z silnika OCR? Nie jesteś jedyny. W regulowanych branżach ujawnienie pełnego PAN (Primary Account Number) może wprowadzić Cię w kłopoty z audytorami zgodności PCI. Dobra wiadomość? Kilka linii Pythona i hak post‑processingowy AsposeAI pozwalają automatycznie ukryć środkowe osiem cyfr i pozostać po bezpiecznej stronie. + +W tym tutorialu przejdziemy przez realistyczny scenariusz: uruchomienie OCR na obrazie paragonu, a następnie zastosowanie niestandardowej funkcji **OCR post‑processing**, która sanitizuje wszelkie dane PCI. Po zakończeniu będziesz mieć wielokrotnego użytku fragment kodu, który możesz wstawić do dowolnego przepływu pracy AsposeAI, oraz kilka praktycznych wskazówek dotyczących obsługi przypadków brzegowych i skalowania rozwiązania. + +## Czego się nauczysz + +- Jak zarejestrować niestandardowy post‑processor w **AsposeAI**. +- Dlaczego podejście **maskowania wyrażeniami regularnymi** jest szybkie i niezawodne. +- Podstawy **zgodności PCI** związanej z sanitacją danych. +- Sposoby rozszerzenia wzorca dla wielu formatów kart lub numerów międzynarodowych. +- Oczekiwany wynik i jak zweryfikować, że maskowanie zadziałało. + +> **Prerequisites** – Powinieneś mieć działające środowisko Python 3, zainstalowany pakiet Aspose.AI for OCR (`pip install aspose-ocr`) oraz przykładowy obraz (np. `receipt.png`) zawierający numer karty kredytowej. Nie są wymagane żadne inne usługi zewnętrzne. + +--- + +## Krok 1: Zdefiniuj post‑processor, który maskuje numery kart kredytowych + +Serce rozwiązania tkwi w małej funkcji, która otrzymuje wynik OCR, wykonuje **regular expression masking** i zwraca zsanityzowany tekst. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Dlaczego to działa:** +- Wyrażenie regularne `(\d{4})\d{8}(\d{4})` dopasowuje dokładnie 16 kolejnych cyfr, typowy format dla Visa, MasterCard i wielu innych. +- Poprzez przechwycenie pierwszych i ostatnich czterech cyfr (`\1` i `\2`) zachowujemy wystarczające informacje do debugowania, jednocześnie spełniając zasady **PCI compliance**, które zakazują przechowywania pełnego PAN. +- Podstawienie `\1****\2` ukrywa wrażliwe środkowe osiem cyfr, zamieniając `1234567812345678` na `1234****5678`. + +> **Pro tip:** Jeśli potrzebujesz obsługiwać 15‑cyfrowe numery American Express, dodaj drugi wzorzec, np. `r'(\d{4})\d{6}(\d{5})'` i wykonaj oba zastąpienia kolejno. + +--- + +## Krok 2: Zainicjalizuj silnik AsposeAI + +Zanim będziemy mogli podłączyć nasz post‑processor, potrzebujemy instancji silnika OCR. AsposeAI zawiera model OCR oraz prostą API do przetwarzania niestandardowego. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Dlaczego inicjalizować tutaj?** +Utworzenie obiektu `AsposeAI` raz i ponowne użycie go przy wielu obrazach zmniejsza narzut. Silnik dodatkowo buforuje modele językowe, co przyspiesza kolejne wywołania — przydatne przy skanowaniu partii paragonów. + +--- + +## Krok 3: Zarejestruj niestandardową funkcję maskującą + +AsposeAI udostępnia metodę `set_post_processor`, która pozwala podłączyć dowolny callable. Przekazujemy naszą funkcję `mask_pci` wraz z opcjonalnym słownikiem ustawień (na razie pustym). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**Co się dzieje w tle?** +Gdy później wywołasz `run_postprocessor`, AsposeAI przekaże surowy wynik OCR do `mask_pci`. Funkcja otrzymuje lekki obiekt (`data`) zawierający rozpoznany tekst i zwraca nowy ciąg znaków. Ten projekt pozostawia podstawowy OCR nietknięty, a jednocześnie pozwala wymusić polityki **data sanitization** w jednym miejscu. + +--- + +## Krok 4: Uruchom OCR na obrazie paragonu + +Teraz, gdy silnik wie, jak oczyścić wyjście, podajemy mu obraz. Dla potrzeb tego tutorialu zakładamy, że masz już skonfigurowany obiekt `engine` z odpowiednimi ustawieniami języka i rozdzielczości. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Tip:** Jeśli nie masz wstępnie skonfigurowanego obiektu, możesz go utworzyć tak: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +Wywołanie `recognize_image` zwraca obiekt, którego atrybut `text` zawiera surowy, niezamaskowany ciąg. + +--- + +## Krok 5: Zastosuj zarejestrowany post‑processor + +Mając surowe dane OCR w ręku, przekazujemy je instancji AI. Silnik automatycznie uruchamia funkcję `mask_pci`, którą zarejestrowaliśmy wcześniej. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Dlaczego używać `run_postprocessor` zamiast wywoływać funkcję ręcznie?** +Pozwala to zachować spójny przepływ pracy, szczególnie gdy masz wiele post‑processorów (np. sprawdzanie pisowni, wykrywanie języka). AsposeAI kolejkowuje je w kolejności rejestracji, gwarantując deterministyczny wynik. + +--- + +## Krok 6: Zweryfikuj zsanityzowany wynik + +Na koniec wydrukujmy zsanityzowany tekst i potwierdźmy, że wszystkie numery kart kredytowych zostały prawidłowo zamaskowane. + +```python +print(final_result.text) +``` + +**Oczekiwany wynik** (fragment): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Jeśli paragon nie zawierał numeru karty, tekst pozostaje niezmieniony — nic do maskowania, nic do martwienia się. + +--- + +## Obsługa przypadków brzegowych i typowych wariacji + +### Multiple Card Numbers in One Document +Jeśli paragon zawiera więcej niż jeden PAN (np. kartę lojalnościową i kartę płatniczą), wyrażenie regularne działa globalnie, maskując wszystkie dopasowania automatycznie. Nie wymaga dodatkowego kodu. + +### Non‑Standard Formatting +Czasami OCR wstawia spacje lub myślniki (`1234 5678 1234 5678` lub `1234-5678-1234-5678`). Rozszerz wzorzec, aby ignorował te znaki: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +Dodane `[ -]?` toleruje opcjonalne spacje lub myślniki między blokami cyfr. + +### International Cards +Dla 19‑cyfrowych PAN używanych w niektórych regionach możesz poszerzyć wzorzec: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Pamiętaj, że **PCI compliance** nadal wymaga maskowania środkowych cyfr, niezależnie od długości. + +### Logging Masked Values (Optional) +Jeśli potrzebujesz ścieżek audytowych, przekaż flagę przez `custom_settings` i dostosuj funkcję: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Następnie zarejestruj tak: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Full Working Example (Copy‑Paste Ready) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Uruchomienie tego skryptu na paragonie zawierającym `4111111111111111` spowoduje: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +To cały pipeline — od surowego OCR po **data sanitization** — zamknięty w kilku czystych linijkach Pythona. + +--- + +## Conclusion + +Właśnie pokazaliśmy, jak **maskować numery kart kredytowych** w wynikach OCR przy użyciu hooka post‑processingowego AsposeAI, krótkiej procedury wyrażeń regularnych i kilku wskazówek dotyczących **PCI compliance**. Rozwiązanie jest w pełni samodzielne, działa z dowolnym obrazem, który silnik OCR potrafi odczytać, i może być rozszerzone o bardziej złożone formaty kart lub wymagania logowania. + +Gotowy na kolejny krok? Spróbuj połączyć tę maskę z **rutiną wstawiania do bazy danych**, która przechowuje tylko ostatnie cztery cyfry w celach referencyjnych, lub zintegrować **procesor wsadowy**, który skanuje cały folder paragonów przez noc. Możesz także zbadać inne zadania **OCR post‑processing**, takie jak standaryzacja adresów czy wykrywanie języka — każde z nich podąża tym samym schematem, którego użyliśmy tutaj. + +Masz pytania dotyczące przypadków brzegowych, wydajności lub adaptacji kodu do innej biblioteki OCR? Zostaw komentarz poniżej i kontynuujmy dyskusję. Szczęśliwego kodowania i bądź bezpieczny! + + + +![Diagram ilustrujący, jak maskowanie numerów kart kredytowych działa w potoku OCR](https://example.com/images/ocr-mask-flow.png "Diagram przepływu maskowania w post‑processing OCR") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/polish/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..378c6aed7 --- /dev/null +++ b/ocr/polish/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-04-26 +description: Dowiedz się, jak zmierzyć czas inferencji w Pythonie, załadować model + GGUF z Hugging Face i zoptymalizować wykorzystanie GPU, aby uzyskać szybsze wyniki. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: pl +og_description: Mierz czas inferencji w Pythonie, ładując model GGUF z Hugging Face + i dostosowując warstwy GPU w celu uzyskania optymalnej wydajności. +og_title: Mierzenie czasu inferencji – załaduj model GGUF i zoptymalizuj GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Mierzenie czasu inferencji – Załaduj model GGUF i zoptymalizuj GPU +url: /pl/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mierzenie czasu inferencji – Ładowanie modelu GGUF i optymalizacja GPU + +Kiedykolwiek potrzebowałeś **zmierzyć czas inferencji** dla dużego modelu językowego, ale nie wiedziałeś od czego zacząć? Nie jesteś sam — wielu programistów napotyka ten sam problem, gdy po raz pierwszy pobierają plik GGUF z Hugging Face i próbują uruchomić go w konfiguracji mieszanej CPU/GPU. + +W tym przewodniku przejdziemy przez **to, jak załadować model GGUF**, skonfigurujemy go dla Hugging Face i **zmierzymy czas inferencji** przy użyciu czystego fragmentu Pythona. Po drodze pokażemy także, jak **optymalizować użycie GPU przy inferencji**, aby Twoje uruchomienia były tak szybkie, jak to możliwe. Bez zbędnych wstępów, po prostu praktyczne, kompleksowe rozwiązanie, które możesz skopiować i wkleić już dziś. + +## Czego się nauczysz + +- Jak **skonfigurować model HuggingFace** przy użyciu `AsposeAIModelConfig`. +- Dokładne kroki **ładowania modelu GGUF** (`fp16` quantization) z hubu Hugging Face. +- Wzorzec wielokrotnego użytku do **mierzenia czasu kodu Python** wokół wywołania inferencji. +- Wskazówki, jak **optymalizować inferencję na GPU** poprzez dostosowanie `gpu_layers`. +- Oczekiwany wynik i jak zweryfikować, że pomiar ma sens. + +### Prerequisites + +| Wymaganie | Dlaczego ma znaczenie | +|-----------|-----------------------| +| Python 3.9+ | Nowoczesna składnia i wskazówki typów. | +| `asposeai` package (or the equivalent SDK) | Dostarcza `AsposeAI` i `AsposeAIModelConfig`. | +| Access to the Hugging Face repo `bartowski/Qwen2.5-3B-Instruct-GGUF` | Model GGUF, który załadujemy. | +| A GPU with at least 8 GB VRAM (optional but recommended) | Umożliwia krok **optimize inference GPU**. | + +If you haven’t installed the SDK yet, run: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![measure inference time diagram](https://example.com/measure-inference-time.png){alt="measure inference time diagram"} + +## Krok 1: Ładowanie modelu GGUF – Konfiguracja modelu HuggingFace + +Pierwszą rzeczą, której potrzebujesz, jest odpowiedni obiekt konfiguracji, który mówi Aspose AI, skąd pobrać model i jak go traktować. To tutaj **ładujemy model GGUF** i **konfigurujemy parametry modelu huggingface**. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Dlaczego to ważne:** +- `hugging_face_repo_id` wskazuje dokładny plik GGUF w Hubie. +- `fp16` zmniejsza przepustowość pamięci, zachowując większość wierności modelu. +- `gpu_layers` to parametr, który regulujesz, gdy chcesz **optimize inference GPU**; więcej warstw na GPU zazwyczaj oznacza niższą latencję, pod warunkiem, że masz wystarczającą ilość VRAM. + +## Krok 2: Utworzenie instancji Aspose AI + +Teraz, gdy model jest opisany, tworzymy obiekt `AsposeAI`. Ten krok jest prosty, ale to tutaj SDK faktycznie pobiera plik GGUF (jeśli nie jest w pamięci podręcznej) i przygotowuje środowisko uruchomieniowe. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Pro tip:** Pierwsze uruchomienie potrwa kilka sekund dłużej, ponieważ model jest pobierany i kompilowany pod GPU. Kolejne uruchomienia są błyskawiczne. + +## Krok 3: Uruchomienie inferencji i **mierzenie czasu inferencji** + +Oto serce tutorialu: otoczenie wywołania inferencji funkcją `time.time()`, aby **zmierzyć czas inferencji**. Dodatkowo podajemy mały wynik OCR, aby przykład był samodzielny. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Co powinieneś zobaczyć:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Jeśli liczba wydaje się wysoka, prawdopodobnie większość warstw działa na CPU. To prowadzi nas do kolejnego kroku. + +## Krok 4: **optimize inference GPU** – Dostosowanie `gpu_layers` + +Czasami domyślne `gpu_layers=40` jest albo zbyt agresywne (powoduje OOM), albo zbyt zachowawcze (pozostawia wydajność na stole). Oto szybka pętla, którą możesz użyć, aby znaleźć optymalny punkt: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Dlaczego to działa:** +- Każde wywołanie przebudowuje środowisko uruchomieniowe z inną alokacją GPU, pozwalając natychmiast zobaczyć kompromis latencji. +- Pętla także demonstruje **time python code** w sposób wielokrotnego użytku, który możesz dostosować do innych testów wydajności. + +Typowy wynik na 16 GB RTX 3080 może wyglądać tak: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +Na tej podstawie wybierzesz `gpu_layers=40` jako optymalny punkt dla tego sprzętu. + +## Pełny działający przykład + +Łącząc wszystko razem, oto pojedynczy skrypt, który możesz umieścić w pliku (`measure_inference.py`) i uruchomić: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Uruchom go za pomocą: + +```bash +python measure_inference.py +``` + +Powinieneś zobaczyć opóźnienie poniżej sekundy na przyzwoitym GPU, potwierdzając, że pomyślnie **measure inference time** i **optimize inference GPU**. + +--- + +## Najczęściej zadawane pytania (FAQ) + +**Q: Czy to działa z innymi formatami kwantyzacji?** +A: Absolutnie. Zamień `hugging_face_quantization="int8"` (lub `q4_0`, itp.) w konfiguracji i ponownie uruchom benchmark. Oczekuj kompromisu: mniejsze zużycie pamięci vs. niewielki spadek dokładności. + +**Q: Co jeśli nie mam GPU?** +A: Ustaw `gpu_layers=0`. Kod przełączy się całkowicie na CPU i nadal będziesz mógł **measure inference time** — po prostu spodziewaj się wyższych liczb. + +**Q: Czy mogę zmierzyć tylko przejście modelu do przodu, pomijając post‑processing?** +A: Tak. Wywołaj bezpośrednio `ai_engine.run_model(...)` (lub równoważną metodę) i otocz to wywołanie `time.time()`. Wzorzec dla **time python code** pozostaje taki sam. + +## Podsumowanie + +Masz teraz kompletną, gotową do skopiowania i wklejenia metodę **measure inference time** dla modelu GGUF, **load gguf model** z Hugging Face oraz dopasowanie ustawień **optimize inference GPU**. Poprzez regulację `gpu_layers` i eksperymentowanie z kwantyzacją, możesz wycisnąć każdy milisekundowy przyrost wydajności. + +Następne kroki, które możesz rozważyć: + +- Zintegruj tę logikę pomiaru czasu z pipeline CI, aby wykrywać regresje. +- Zbadaj inferencję wsadową, aby jeszcze bardziej zwiększyć przepustowość. +- Połącz model z rzeczywistym pipeline OCR zamiast używanego tutaj przykładowego tekstu. + +Szczęśliwego kodowania i niech Twoje czasy latencji zawsze będą niskie! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/polish/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..fc6fcc7bb --- /dev/null +++ b/ocr/polish/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-26 +description: Rozpoznawaj odręczny tekst za pomocą silnika OCR w Pythonie. Dowiedz + się, jak wyodrębnić tekst z obrazu, włączyć tryb odręczny i szybko odczytywać notatki + odręczne. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: pl +og_description: Rozpoznawaj odręczny tekst przy użyciu Pythona. Ten tutorial pokazuje, + jak wyodrębnić tekst z obrazu, włączyć tryb odręczny i odczytać odręczne notatki + przy użyciu prostego silnika OCR. +og_title: Rozpoznawanie odręcznego tekstu w Pythonie – Kompletny przewodnik OCR +tags: +- OCR +- Python +- Handwriting Recognition +title: Rozpoznawanie odręcznego tekstu w Pythonie – samouczek silnika OCR +url: /pl/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# rozpoznawanie odręcznego tekstu w Pythonie – samouczek silnika OCR + +Czy kiedykolwiek potrzebowałeś **rozpoznawać odręczny tekst**, ale utknąłeś na pytaniu „od czego zacząć?”? Nie jesteś jedyny. Niezależnie od tego, czy digitalizujesz notatki ze spotkań, czy wyciągasz dane ze zeskanowanego formularza, uzyskanie wiarygodnego wyniku OCR może przypominać gonienie jednorożca. + +Dobre wieści: wystarczy kilka linijek Pythona, aby **wyodrębnić tekst z obrazu**, **włączyć tryb odręczny** i w końcu **czytać odręczne notatki** bez poszukiwania niejasnych bibliotek. W tym przewodniku przeprowadzimy Cię przez cały proces, od konfiguracji w stylu **create OCR engine python** po wyświetlenie wyniku na ekranie. + +## Czego się nauczysz + +- Jak utworzyć instancję **create OCR engine python** przy użyciu pakietu `ocr`. +- Które ustawienie języka zapewnia wbudowane wsparcie dla odręcznego pisma. +- Dokładne wywołanie **turn on handwritten mode**, aby silnik wiedział, że masz do czynienia z pismem odręcznym. +- Jak podać zdjęcie notatki i **recognize handwritten text** z niego. +- Wskazówki dotyczące obsługi różnych formatów obrazów, rozwiązywania typowych problemów i rozbudowy rozwiązania. + +Bez zbędnego gadania, bez „zobacz dokumentację” – po prostu kompletny, działający skrypt, który możesz skopiować, wkleić i przetestować już dziś. + +## Wymagania wstępne + +Zanim zaczniemy, upewnij się, że masz: + +1. Python 3.8+ zainstalowany (kod używa f‑stringów). +2. Hipotetyczną bibliotekę `ocr` (`pip install ocr‑engine` – zamień na rzeczywistą nazwę pakietu, którego używasz). +3. Jasny plik obrazu odręcznej notatki (działają JPEG, PNG lub TIFF). +4. Umiarkowaną dawkę ciekawości — wszystko inne jest opisane poniżej. + +> **Pro tip:** Jeśli Twój obraz jest zaszumiony, wykonaj szybki krok wstępnego przetwarzania przy użyciu Pillow (np. `Image.open(...).convert('L')`) przed wysłaniem go do silnika OCR. Często zwiększa to dokładność. + +## Jak rozpoznawać odręczny tekst w Pythonie + +Poniżej znajduje się pełny skrypt, który **creates OCR engine python** obiekty, konfiguruje je do odręcznego pisma i wypisuje wyodrębniony ciąg znaków. Zapisz go jako `handwriting_ocr.py` i uruchom w terminalu. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Oczekiwany wynik + +Gdy skrypt uruchomi się pomyślnie, zobaczysz coś podobnego do: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Jeśli silnik OCR nie wykryje żadnych znaków, pole `text` będzie pustym ciągiem. W takim przypadku sprawdź ponownie jakość obrazu lub spróbuj skanu o wyższej rozdzielczości. + +## Szczegółowe wyjaśnienie krok po kroku + +### Krok 1 – instancja **create OCR engine python** + +Klasa `OcrEngine` jest punktem wejścia. Pomyśl o niej jak o czystym notesie — nic się nie dzieje, dopóki nie określisz, jakiego języka się spodziewać i czy masz do czynienia z odręcznym pismem. + +### Krok 2 – Wybierz język wspierający odręczne pismo + +`ocr.Language.EXTENDED_LATIN` to nie tylko „angielski”. Zawiera zestaw skryptów opartych na alfabecie łacińskim i, co kluczowe, modele wytrenowane na próbkach pisma odręcznego. Pominięcie tego kroku często prowadzi do zniekształconego wyniku, ponieważ silnik domyślnie używa modelu tekstu drukowanego. + +### Krok 3 – **turn on handwritten mode** + +Wywołanie `enable_handwritten_mode(True)` przełącza wewnętrzny znacznik. Silnik przełącza się wtedy na swoją sieć neuronową dostosowaną do nieregularnych odstępów i zmiennych szerokości pociągnięć, które występują w rzeczywistych notatkach. Zapomnienie tej linii to częsty błąd; silnik potraktuje Twoje bazgroły jako szum. + +### Krok 4 – Przekaż obraz i **recognize handwritten text** + +`recognize_image` wykonuje najcięższą pracę: przetwarza bitmapę, uruchamia ją przez model odręcznego pisma i zwraca obiekt z atrybutem `text`. Możesz także sprawdzić `handwritten_result.confidence`, jeśli potrzebujesz miary jakości. + +### Krok 5 – Wypisz wynik i **read handwritten notes** + +`print(handwritten_result.text)` to najprostszy sposób, aby zweryfikować, że udało Ci się **extract text from image**. W produkcji prawdopodobnie zapiszesz ciąg w bazie danych lub przekażesz go do innej usługi. + +## Obsługa przypadków brzegowych i typowych wariacji + +| Sytuacja | Co zrobić | +|-----------|------------| +| **Obraz jest obrócony** | Użyj Pillow, aby obrócić (`Image.rotate(angle)`) przed wywołaniem `recognize_image`. | +| **Niski kontrast** | Konwertuj na skalę szarości i zastosuj adaptacyjne progowanie (`Image.point(lambda p: p > 128 and 255)`). | +| **Wiele stron** | Iteruj po liście ścieżek plików i łącz wyniki. | +| **Skrypty niełacińskie** | Zastąp `EXTENDED_LATIN` przez `ocr.Language.CHINESE` (lub odpowiedni) i zachowaj `enable_handwritten_mode(True)`. | +| **Problemy z wydajnością** | Ponownie używaj tej samej instancji `ocr_engine` dla wielu obrazów; inicjalizacja przy każdym wywołaniu zwiększa narzut. | + +### Pro tip dotyczący użycia pamięci + +Jeśli przetwarzasz setki notatek w partii, wywołaj `ocr_engine.dispose()` po zakończeniu. Zwalnia to natywne zasoby, które może utrzymywać wrapper Pythona. + +## Szybkie podsumowanie wizualne + +![przykład rozpoznawania odręcznego tekstu](https://example.com/handwritten-note.png "przykład rozpoznawania odręcznego tekstu") + +*Powyższy obraz pokazuje typową odręczną notatkę, którą nasz skrypt może przekształcić w zwykły tekst.* + +## Pełny działający przykład (skrypt jednoplikowy) + +Dla tych, którzy kochają prostotę kopiuj‑wklej, oto cały kod ponownie, bez komentarzy wyjaśniających: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Uruchom go za pomocą: + +```bash +python handwriting_ocr.py +``` + +Powinieneś teraz zobaczyć wynik **recognize handwritten text** w konsoli. + +## Zakończenie + +Właśnie omówiliśmy wszystko, co potrzebne, aby **recognize handwritten text** w Pythonie — od nowego wywołania **create OCR engine python**, przez wybór odpowiedniego języka, **turn on handwritten mode**, aż po **extract text from image** i **read handwritten notes**. + +W jednym, samodzielnym skrypcie możesz przejść od rozmytego zdjęcia szkicu ze spotkania do czystego, przeszukiwalnego tekstu. Następnie rozważ przekazanie wyniku do potoku przetwarzania języka naturalnego, zapisanie go w indeksie przeszukiwalnym lub nawet zwrócenie go do usługi transkrypcji w celu generowania lektora. + +### Gdzie dalej? + +- **Batch processing:** Owiń skrypt w pętlę, aby obsługiwać folder ze skanami. +- **Confidence filtering:** Użyj `result.confidence`, aby odrzucać odczyty niskiej jakości. +- **Alternative libraries:** Jeśli `ocr` nie jest idealnym rozwiązaniem, wypróbuj `pytesseract` z `--psm 13` dla trybu odręcznego. +- **UI integration:** Połącz z Flask lub FastAPI, aby udostępnić usługę przesyłania plików przez internet. + +Masz pytania dotyczące konkretnego formatu obrazu lub potrzebujesz pomocy w dostrojeniu modelu? zostaw komentarz poniżej i powodzenia w kodowaniu! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/portuguese/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..a960b31e0 --- /dev/null +++ b/ocr/portuguese/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,192 @@ +--- +category: general +date: 2026-04-26 +description: Aprenda como baixar o modelo HuggingFace em Python e extrair texto de + imagens em Python, enquanto melhora a precisão do OCR em Python com o Aspose OCR + Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: pt +og_description: baixe o modelo huggingface python e impulsione seu pipeline de OCR. + Siga este guia para extrair texto de imagem python e melhorar a precisão do OCR + python. +og_title: baixar modelo huggingface python – tutorial completo de aprimoramento de + OCR +tags: +- OCR +- HuggingFace +- Python +- AI +title: baixar modelo huggingface python – Guia passo a passo para melhorar OCR +url: /pt/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – Tutorial Completo de Aprimoramento de OCR + +Já tentou **download HuggingFace model python** e se sentiu um pouco perdido? Você não está sozinho. Em muitos projetos, o maior gargalo é colocar um bom modelo na sua máquina e então tornar os resultados de OCR realmente úteis. + +Neste guia, vamos percorrer um exemplo prático que mostra exatamente como **download HuggingFace model python**, extrair texto de uma imagem com **extract text from image python**, e então **improve OCR accuracy python** usando o pós‑processador de IA da Aspose. Ao final, você terá um script pronto para executar que transforma uma imagem de nota fiscal ruidosa em texto limpo e legível — sem mágica, apenas passos claros. + +## O que você vai precisar + +- Python 3.9+ (o código também funciona em 3.11) +- Uma conexão à internet para o download único do modelo +- O pacote `asposeocrcloud` (`pip install asposeocrcloud`) +- Uma imagem de exemplo (por exemplo, `sample_invoice.png`) colocada em uma pasta que você controla + +É só isso — sem frameworks pesados, sem drivers específicos de GPU, a menos que você queira acelerar as coisas. + +Agora, vamos mergulhar na implementação real. + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## Etapa 1: Configurar o Motor de OCR e Escolher um Idioma +*(É aqui que começamos a **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Por que isso importa:** +O motor de OCR é a primeira linha de defesa; escolher o pacote de idioma correto reduz erros de reconhecimento de caracteres imediatamente, o que é uma parte central de **improve OCR accuracy python**. + +## Etapa 2: Configurar o Modelo AsposeAI – Download do HuggingFace +*(Aqui realmente **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**O que está acontecendo nos bastidores?** +Quando `allow_auto_download` está verdadeiro, o SDK acessa o HuggingFace, busca o modelo `Qwen2.5‑3B‑Instruct‑GGUF` e o armazena na pasta que você especificou. Isso é o núcleo de **download huggingface model python** — o SDK cuida do trabalho pesado, então você não precisa escrever nenhum comando `git clone` ou `wget`. + +*Dica profissional:* Mantenha `directory_model_path` em um SSD para tempos de carregamento mais rápidos; o modelo tem ~3 GB mesmo na forma `int8`. + +## Etapa 3: Vincular o Motor de IA ao Motor de OCR +*(Ligando as duas partes para que possamos **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Por que vinculá‑los?** +O motor de OCR nos fornece texto bruto, que pode conter erros de ortografia, linhas quebradas ou pontuação incorreta. O motor de IA atua como um editor inteligente, limpando esses problemas — exatamente o que você precisa para **improve OCR accuracy python**. + +## Etapa 4: Executar OCR na sua Imagem +*(O momento em que finalmente **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` agora contém um atributo `text` com os caracteres brutos que o motor viu. Na prática, você notará alguns tropeços — talvez “Invoice” tenha se tornado “Inv0ice” ou haja uma quebra de linha no meio de uma frase. + +## Etapa 5: Limpar com o Pós‑Processador de IA +*(Esta etapa **improve OCR accuracy python** diretamente.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +O modelo de IA reescreve o texto, aplicando correções sensíveis ao idioma. Como usamos um modelo ajustado por instruções do HuggingFace, a saída costuma ser fluente e pronta para processamento posterior. + +## Etapa 6: Mostrar Antes e Depois +*(Uma rápida verificação para ver quão bem **extract text from image python** e **improve OCR accuracy python**.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Saída Esperada + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Observe como a IA corrigiu “Inv0ice” para “Invoice” e suavizou quebras de linha indesejadas. Esse é o resultado tangível de **improve OCR accuracy python** usando um modelo HuggingFace baixado. + +## Perguntas Frequentes (FAQ) + +### Preciso de uma GPU para executar o modelo? +Não. A configuração `gpu_layers=20` indica ao SDK que use até 20 camadas de GPU se houver uma GPU compatível; caso contrário, ele recorre à CPU. Em um laptop moderno, o caminho CPU ainda processa algumas centenas de tokens por segundo — perfeito para parsing ocasional de notas fiscais. + +### E se o modelo falhar ao baixar? +Certifique‑se de que seu ambiente pode alcançar `https://huggingface.co`. Se você estiver atrás de um proxy corporativo, defina as variáveis de ambiente `HTTP_PROXY` e `HTTPS_PROXY`. O SDK tentará novamente automaticamente, mas você também pode fazer manualmente `git lfs pull` do repositório para `directory_model_path`. + +### Posso trocar o modelo por um menor? +Com certeza. Basta substituir `hugging_face_repo_id` por outro repositório (por exemplo, `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) e ajustar `hugging_face_quantization` adequadamente. Modelos menores baixam mais rápido e consomem menos RAM, embora você possa perder um pouco da qualidade de correção. + +### Como isso me ajuda a **extract text from image python** em outros domínios? +O mesmo pipeline funciona para recibos, passaportes ou notas manuscritas. A única mudança é o pacote de idioma (`ocr.Language.FRENCH`, etc.) e possivelmente um modelo afinado para o domínio específico do HuggingFace. + +## Bônus: Automatizando Vários Arquivos + +Se você tem uma pasta cheia de imagens, envolva a chamada de OCR em um loop simples: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +Essa pequena adição permite que você **download huggingface model python** uma vez, e então processe em lote dezenas de arquivos — ótimo para escalar seu pipeline de automação de documentos. + +## Conclusão + +Acabamos de percorrer um exemplo completo, de ponta a ponta, que mostra como **download HuggingFace model python**, **extract text from image python**, e **improve OCR accuracy python** usando o OCR Cloud da Aspose e um pós‑processador de IA. O script está pronto para ser executado, os conceitos foram explicados, e você viu a saída antes e depois para saber que funciona. + +Qual o próximo passo? Experimente trocar por outro modelo HuggingFace, teste outros pacotes de idioma, ou alimente o texto limpo em um pipeline NLP posterior (por exemplo, extração de entidades para itens de nota fiscal). O céu é o limite, e a base que você acabou de construir é sólida. + +Tem dúvidas ou uma imagem complicada que ainda engana o OCR? Deixe um comentário abaixo, e vamos solucionar juntos. Feliz codificação! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/portuguese/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..6aa74f6ed --- /dev/null +++ b/ocr/portuguese/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-04-26 +description: Baixe o modelo OCR rapidamente usando Aspose OCR Python. Aprenda como + definir o diretório do modelo, configurar o caminho do modelo e como baixar o modelo + em poucas linhas. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: pt +og_description: Baixe o modelo OCR em segundos com Aspose OCR Python. Este guia mostra + como definir o diretório do modelo, configurar o caminho do modelo e como baixar + o modelo com segurança. +og_title: baixar modelo OCR – Tutorial completo de OCR Aspose em Python +tags: +- OCR +- Python +- Aspose +title: Baixar modelo OCR com Aspose OCR Python – Guia passo a passo +url: /pt/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – Tutorial Completo de Aspose OCR Python + +Já se perguntou como **download ocr model** usando Aspose OCR em Python sem vasculhar documentos intermináveis? Você não está sozinho. Muitos desenvolvedores esbarram em um obstáculo quando o modelo não está presente localmente e o SDK lança um erro enigmático. A boa notícia? A solução são algumas linhas de código, e você terá o modelo pronto em minutos. + +Neste tutorial vamos percorrer tudo o que você precisa saber: desde a importação das classes corretas, até **set model directory**, passando por **how to download model**, e finalmente verificando o caminho. Ao final, você será capaz de executar OCR em qualquer imagem com uma única chamada de função, e entenderá as opções de **configure model path** que mantêm seu projeto organizado. Sem enrolação, apenas um exemplo prático e executável para usuários de **aspose ocr python**. + +## O que você aprenderá + +- Como importar as classes Aspose OCR Cloud corretamente. +- Os passos exatos para **download ocr model** automaticamente. +- Formas de **set model directory** e **configure model path** para builds reproduzíveis. +- Como verificar se o modelo está inicializado e onde ele está no disco. +- Armadilhas comuns (permissões, diretórios ausentes) e correções rápidas. + +### Pré-requisitos + +- Python 3.8+ instalado na sua máquina. +- `asposeocrcloud` package (`pip install asposeocrcloud`). +- Permissão de escrita em uma pasta onde você deseja armazenar o modelo (por exemplo, `C:\models` ou `~/ocr_models`). + +--- + +## Etapa 1: Importar as Classes Aspose OCR Cloud + +A primeira coisa que você precisa é a declaração de import correta. Ela traz as classes que gerenciam a configuração do modelo e as operações de OCR. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Por que isso importa:* `AsposeAI` é o motor que executará o OCR, enquanto `AsposeAIModelConfig` informa ao motor **onde** procurar o modelo e **se** ele deve buscá‑lo automaticamente. Pular esta etapa ou importar o módulo errado causará um `ModuleNotFoundError` antes mesmo de chegar à parte de download. + +--- + +## Etapa 2: Definir a Configuração do Modelo (Set Model Directory & Configure Model Path) + +Agora informamos à Aspose onde armazenar os arquivos do modelo. É aqui que você **set model directory** e **configure model path**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Dicas & Armadilhas** + +- **Caminhos absolutos** evitam confusão quando o script é executado a partir de um diretório de trabalho diferente. +- No Linux/macOS você pode usar `"/home/you/ocr_models"`; no Windows, prefixe com `r` para tratar as barras invertidas literalmente. +- Definir `allow_auto_download="true"` é a chave para **how to download model** sem escrever código extra. + +--- + +## Etapa 3: Criar a Instância AsposeAI Usando a Configuração + +Com a configuração pronta, instancie o motor de OCR. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Por que isso importa:* O objeto `ocr_ai` agora contém a configuração que acabamos de definir. Se o modelo não estiver presente, a próxima chamada acionará o download automaticamente — este é o cerne de **how to download model** de forma automática. + +--- + +## Etapa 4: Acionar o Download do Modelo (Se Necessário) + +Antes de poder executar OCR, você precisa garantir que o modelo esteja realmente no disco. O método `is_initialized()` verifica e força a inicialização. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**O que acontece nos bastidores?** + +- A primeira chamada `is_initialized()` retorna `False` porque a pasta do modelo está vazia. +- O `print` informa ao usuário que o download está prestes a começar. +- A segunda chamada força o Aspose a buscar o modelo do repositório Hugging Face que você especificou anteriormente. +- Uma vez baixado, o método retorna `True` nas verificações subsequentes. + +**Caso extremo:** Se sua rede bloquear o Hugging Face, você verá uma exceção. Nesse caso, faça o download manual do zip do modelo, extraia‑o em `directory_model_path` e execute o script novamente. + +--- + +## Etapa 5: Relatar o Caminho Local Onde o Modelo Está Agora Disponível + +Depois que o download terminar, provavelmente você quer saber onde os arquivos foram salvos. Isso ajuda na depuração e na configuração de pipelines CI. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +A saída típica se parece com: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Agora você baixou com sucesso **download ocr model**, definiu o diretório e confirmou o caminho. + +--- + +## Visão Geral Visual + +Abaixo está um diagrama simples que mostra o fluxo da configuração até um modelo pronto‑para‑uso. + +![diagrama do fluxo de download do modelo ocr mostrando configuração, download automático e caminho local](/images/download-ocr-model-flow.png) + +*O texto alternativo inclui a palavra‑chave principal para SEO.* + +--- + +## Variações Comuns & Como Lidar com Elas + +### 1. Usando um Repositório de Modelo Diferente + +Se você precisar de um modelo diferente de `openai/gpt2`, basta substituir o valor `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Certifique‑se de que o repositório seja público ou que você tenha o token necessário configurado no seu ambiente. + +### 2. Desativando o Download Automático + +Às vezes você quer controlar o download manualmente (por exemplo, em ambientes isolados). Defina `allow_auto_download` para `"false"` e chame um script de download personalizado antes de inicializar: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Alterando o Diretório do Modelo em Tempo de Execução + +Você pode reconfigurar o caminho sem recriar o objeto `AsposeAI`: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Dicas Profissionais para Uso em Produção + +- **Cache o modelo**: Mantenha o diretório em uma unidade de rede compartilhada se vários serviços precisarem do mesmo modelo. Isso evita downloads redundantes. +- **Fixação de versão**: O repositório Hugging Face pode ser atualizado. Para travar em uma versão específica, adicione `@v1.0.0` ao ID do repositório (`"openai/gpt2@v1.0.0"`). +- **Permissões**: Garanta que o usuário que executa o script tenha direitos de leitura/escrita em `directory_model_path`. No Linux, `chmod 755` geralmente basta. +- **Logging**: Substitua as simples instruções `print` pelo módulo `logging` do Python para melhor observabilidade em aplicações maiores. + +--- + +## Exemplo Completo Funcional (Pronto para Copiar‑Colar) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Saída esperada** (a primeira execução fará o download, execuções subsequentes pularão o download): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Execute o script novamente; você verá apenas a linha do caminho porque o modelo já está em cache. + +--- + +## Conclusão + +Acabamos de cobrir o processo completo para **download ocr model** usando Aspose OCR Python, mostramos como **set model directory** e explicamos as nuances de **configure model path**. Com apenas algumas linhas de código você pode automatizar o download, evitar etapas manuais e manter seu pipeline de OCR reproduzível. + +Em seguida, você pode explorar a chamada real de OCR (`ocr_ai.recognize_image(...)`) ou experimentar um modelo Hugging Face diferente para melhorar a precisão. De qualquer forma, a base que você construiu aqui — configuração clara, download automático e verificação de caminho — tornará qualquer integração futura muito mais fácil. + +Tem dúvidas sobre casos extremos, ou quer compartilhar como ajustou o diretório do modelo para implantações em nuvem? Deixe um comentário abaixo, e feliz codificação! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/portuguese/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..c3d32ba78 --- /dev/null +++ b/ocr/portuguese/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-26 +description: Como pós‑processar resultados de OCR e extrair texto com coordenadas. + Aprenda uma solução passo a passo usando saída estruturada e correção por IA. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: pt +og_description: Como pós‑processar resultados de OCR e extrair texto com coordenadas. + Siga este tutorial abrangente para um fluxo de trabalho confiável. +og_title: Como Pós‑Processar OCR – Guia Completo +tags: +- OCR +- Python +- AI +- Text Extraction +title: Como pós-processar OCR – Extrair texto com coordenadas em Python +url: /pt/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como Pós‑Processar OCR – Extrair Texto com Coordenadas em Python + +Já precisou **pós‑processar OCR** porque a saída bruta estava ruidosa ou desalinhada? Você não está sozinho. Em muitos projetos reais — digitalização de faturas, digitalização de recibos ou até mesmo aprimoramento de experiências de AR — o motor de OCR fornece palavras brutas, mas ainda é necessário limpá‑las e acompanhar onde cada palavra está na página. É aí que um modo de saída estruturada combinado com um pós‑processador orientado por IA se destaca. + +Neste tutorial vamos percorrer um pipeline Python completo e executável que **extrai texto com coordenadas** de uma imagem, executa uma etapa de correção baseada em IA e imprime cada palavra junto com sua posição (x, y). Sem importações ausentes, sem atalhos vagos “veja a documentação” — apenas uma solução autocontida que você pode inserir no seu projeto hoje. + +> **Dica de especialista:** Se você estiver usando outra biblioteca de OCR, procure um modo “structured” ou “layout”; os conceitos permanecem os mesmos. + +--- + +## Pré‑requisitos + +Antes de mergulharmos, certifique‑se de que você tem: + +| Requisito | Por que é importante | +|-----------|----------------------| +| Python 3.9+ | Sintaxe moderna e dicas de tipo | +| Biblioteca `ocr` que suporte `OutputMode.STRUCTURED` (por exemplo, um fictício `myocr`) | Necessária para dados de caixa delimitadora | +| Módulo de pós‑processamento de IA (pode ser OpenAI, HuggingFace ou um modelo customizado) | Melhora a precisão após o OCR | +| Um arquivo de imagem (`input.png`) no seu diretório de trabalho | A fonte que leremos | + +Se algum desses itens lhe for desconhecido, basta instalar os pacotes fictícios com `pip install myocr ai‑postproc`. O código abaixo também inclui stubs de fallback para que você possa testar o fluxo sem as bibliotecas reais. + +--- + +## Etapa 1: Habilitar o Modo de Saída Estruturada para o Motor de OCR + +A primeira coisa que fazemos é dizer ao motor de OCR para nos dar mais do que apenas texto simples. A saída estruturada retorna cada palavra junto com sua caixa delimitadora e pontuação de confiança, o que é essencial para **extrair texto com coordenadas** mais adiante. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Por que isso importa:* Sem o modo estruturado você receberia apenas uma longa string e perderia as informações espaciais necessárias para sobrepor texto em imagens ou alimentar análises de layout posteriores. + +--- + +## Etapa 2: Reconhecer a Imagem e Capturar Palavras, Caixas e Confiança + +Agora alimentamos a imagem no motor. O resultado é um objeto que contém uma lista de objetos de palavra, cada um expondo `text`, `x`, `y`, `width`, `height` e `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Caso extremo:* Se a imagem estiver vazia ou ilegível, `structured_result.words` será uma lista vazia. É uma boa prática verificar isso e tratá‑lo de forma elegante. + +--- + +## Etapa 3: Executar Pós‑Processamento Baseado em IA Preservando as Posições + +Mesmo os melhores motores de OCR cometem erros — pense em “O” vs. “0” ou diacríticos ausentes. Um modelo de IA treinado em texto específico de domínio pode corrigir esses erros. Crucialmente, mantemos as coordenadas originais para que o layout espacial permaneça intacto. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Por que preservamos as coordenadas:* Muitas tarefas posteriores (por exemplo, geração de PDF, rotulagem em AR) dependem da colocação exata. A IA altera apenas o campo `text`, deixando `x`, `y`, `width`, `height` inalterados. + +--- + +## Etapa 4: Iterar Sobre as Palavras Corrigidas e Exibir Seu Texto com Coordenadas + +Por fim, percorremos as palavras corrigidas e imprimimos cada palavra junto com seu canto superior esquerdo `(x, y)`. Isso cumpre o objetivo de **extrair texto com coordenadas**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Saída esperada (exemplo):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Cada linha mostra a palavra corrigida e sua localização exata na imagem original. + +--- + +## Exemplo Completo Funcional + +A seguir está um script único que une tudo. Você pode copiar‑colar, ajustar as instruções de importação para corresponder às suas bibliotecas reais e executá‑lo diretamente. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Executando o script** + +```bash +python ocr_postprocess_demo.py +``` + +Se você tiver as bibliotecas reais instaladas, o script processará seu `input.png`. Caso contrário, a implementação stub permite que você veja o fluxo e a saída esperados sem dependências externas. + +--- + +## Perguntas Frequentes (FAQ) + +| Pergunta | Resposta | +|----------|----------| +| *Isso funciona com Tesseract?* | O Tesseract por si só não expõe um modo estruturado, mas wrappers como `pytesseract.image_to_data` retornam caixas delimitadoras que podem ser alimentadas no mesmo pós‑processador de IA. | +| *E se eu precisar do canto inferior direito em vez do superior esquerdo?* | Cada objeto de palavra também fornece `width` e `height`. Calcule `x2 = x + width` e `y2 = y + height` para obter o canto oposto. | +| *Posso processar várias imagens em lote?* | Absolutamente. Envolva as etapas em um loop `for image_path in Path("folder").glob("*.png"):` e colete os resultados por arquivo. | +| *Como escolho um modelo de IA para correção?* | Para texto genérico, um pequeno GPT‑2 afinado em erros de OCR funciona. Para dados específicos de domínio (por exemplo, prescrições médicas), treine um modelo seq2seq em pares de dados ruidoso‑limpo. | +| *A pontuação de confiança ainda é útil após a correção da IA?* | Você ainda pode manter a confiança original para depuração, mas a IA pode gerar sua própria pontuação de confiança se o modelo a suportar. | + +--- + +## Casos Limite & Melhores Práticas + +1. **Imagens vazias ou corrompidas** – sempre verifique se `structured_result.words` não está vazio antes de prosseguir. +2. **Scripts não latinos** – assegure que seu motor de OCR esteja configurado para o idioma alvo; o pós‑processador de IA deve ser treinado no mesmo script. +3. **Desempenho** – a correção por IA pode ser custosa. Cache os resultados se você reutilizar a mesma imagem, ou execute a etapa de IA de forma assíncrona. +4. **Sistema de coordenadas** – bibliotecas de OCR podem usar origens diferentes (canto superior esquerdo vs. canto inferior esquerdo). Ajuste conforme necessário ao sobrepor em PDFs ou canvases. + +--- + +## Conclusão + +Agora você tem uma receita sólida, de ponta a ponta, para **pós‑processar OCR** e **extrair texto com coordenadas** de forma confiável. Ao habilitar a saída estruturada, alimentar o resultado por uma camada de correção baseada em IA e preservar as caixas delimitadoras originais, você transforma digitalizações OCR ruidosas em texto limpo e espacialmente consciente, pronto para tarefas posteriores como geração de PDF, automação de entrada de dados ou sobreposições de realidade aumentada. + +Pronto para o próximo passo? Experimente substituir a IA stub por uma chamada ao OpenAI `gpt‑4o‑mini`, ou integre o pipeline em um FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/portuguese/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..326da9879 --- /dev/null +++ b/ocr/portuguese/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-26 +description: Como reconhecer imagens rapidamente com Python. Aprenda um pipeline de + reconhecimento de imagens, processamento em lote e automatize o reconhecimento de + imagens usando IA. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: pt +og_description: Como reconhecer imagens rapidamente com Python. Este guia percorre + um pipeline de reconhecimento de imagens, processamento em lote e automação usando + IA. +og_title: Como Reconhecer Imagens – Automatize um Pipeline de Reconhecimento de Imagens +tags: +- image-processing +- python +- ai +title: Como Reconhecer Imagens – Automatize um Pipeline de Reconhecimento de Imagens +url: /pt/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como Reconhecer Imagens – Automatize um Pipeline de Reconhecimento de Imagens + +Já se perguntou **como reconhecer imagens** sem escrever milhares de linhas de código? Você não está sozinho — muitos desenvolvedores batem na mesma parede quando precisam processar dezenas ou centenas de fotos pela primeira vez. A boa notícia? Com alguns passos simples você pode montar um pipeline completo de reconhecimento de imagens que agrupa, executa e limpa tudo automaticamente. + +Neste tutorial vamos percorrer um exemplo completo e executável que mostra **como agrupar imagens**, enviá‑las a um motor de IA, pós‑processar os resultados e, por fim, liberar os recursos. Ao final, você terá um script autônomo que pode ser inserido em qualquer projeto, seja para criar um etiquetador de fotos, um sistema de controle de qualidade ou um gerador de conjuntos de dados para pesquisa. + +## O Que Você Vai Aprender + +- **Como reconhecer imagens** usando um motor de IA simulado (o padrão é idêntico para serviços reais como TensorFlow, PyTorch ou APIs de nuvem). +- Como construir um **pipeline de reconhecimento de imagens** que lida com lotes de forma eficiente. +- A melhor maneira de **automatizar o reconhecimento de imagens** para que você não precise percorrer manualmente os arquivos a cada execução. +- Dicas para escalar o pipeline e liberar recursos de forma segura. + +> **Pré‑requisitos:** Python 3.8+, familiaridade básica com funções e loops, e alguns arquivos de imagem (ou caminhos) que você deseja processar. Nenhuma biblioteca externa é necessária para o exemplo principal, mas mencionaremos onde você poderia integrar SDKs de IA reais. + +![Diagrama de como reconhecer imagens em um pipeline de processamento em lote](pipeline.png "How to recognize images diagram") + +## Etapa 1: Agrupe Suas Imagens – Como Agrupar Imagens de Forma Eficiente + +Antes que a IA faça qualquer trabalho pesado, você precisa de uma coleção de imagens para alimentá‑la. Pense nisso como sua lista de compras; o motor pegará cada item da lista um por um. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Por que agrupar?** +O agrupamento reduz a quantidade de código repetitivo que você escreve e torna trivial a adição de paralelismo posteriormente. Se você precisar processar 10 000 fotos, basta mudar a origem de `image_batch` — o restante do pipeline permanece intacto. + +## Etapa 2: Execute o Pipeline de Reconhecimento de Imagens (Reconheça Imagens com IA) + +Agora conectamos o lote ao reconhecedor propriamente dito. Em um cenário real você poderia chamar `torchvision.models` ou um endpoint de nuvem; aqui simulamos o comportamento para que o tutorial seja autônomo. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Explicação:** +- `engine.recognize_image` é o coração do **pipeline de reconhecimento de imagens**; pode ser uma chamada a um modelo de deep learning ou a uma API REST. +- `postprocessor.run` demonstra **automatizar o reconhecimento de imagens** ao normalizar previsões brutas em um dicionário limpo que você pode armazenar ou transmitir. +- Coletamos cada dicionário `corrected` em `recognized_results` para que as etapas subsequentes (por exemplo, inserção em banco de dados) sejam simples. + +## Etapa 3: Pós‑processar e Armazenar – Automatize os Resultados do Reconhecimento de Imagens + +Depois de obter uma lista organizada de previsões, normalmente você quer persistir esses dados. O exemplo abaixo grava um arquivo CSV; sinta‑se à vontade para substituir por um banco de dados ou fila de mensagens. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Por que um CSV?** +CSV é universalmente legível — Excel, pandas, até editores de texto simples podem abri‑lo. Se mais tarde você precisar **automatizar o reconhecimento de imagens** em escala, substitua o bloco de escrita por uma inserção em lote no seu data lake. + +## Etapa 4: Limpeza – Libere os Recursos de IA com Segurança + +Muitos SDKs de IA alocam memória de GPU ou criam threads de trabalho. Esquecer de liberá‑los pode causar vazamentos de memória e falhas desagradáveis. Embora nossos objetos simulados não precisem disso, vamos mostrar o padrão correto. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +Executar o script imprime uma confirmação amigável, indicando que o pipeline terminou corretamente. + +## Script Completo + +Juntando tudo, aqui está o programa completo, pronto para copiar e colar: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Saída Esperada + +Ao executar o script (supondo que os três caminhos de exemplo existam), você verá algo como: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +E o `recognition_results.csv` gerado conterá: + +| image | label | confidence | +|---------------------|-------|------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Conclusão + +Agora você tem um exemplo sólido, de ponta a ponta, de **como reconhecer imagens** em Python, completo com um **pipeline de reconhecimento de imagens**, tratamento de lotes e pós‑processamento automatizado. O padrão escala: troque as classes simuladas por um modelo real, alimente um `image_batch` maior e você terá uma solução pronta para produção. + +Quer avançar mais? Experimente os próximos passos: + +- Substitua `MockEngine` por um modelo TensorFlow ou PyTorch para previsões reais. +- Paralelize o loop com `concurrent.futures.ThreadPoolExecutor` para acelerar lotes grandes. +- Conecte o gravador de CSV a um bucket de armazenamento na nuvem para **automatizar o reconhecimento de imagens** entre workers distribuídos. + +Sinta‑se à vontade para experimentar, quebrar coisas e depois consertá‑las — é assim que se domina realmente pipelines de reconhecimento de imagens. Se encontrar algum obstáculo ou tiver ideias de melhoria, deixe um comentário abaixo. Boa codificação! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/portuguese/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..0afa1a39f --- /dev/null +++ b/ocr/portuguese/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-04-26 +description: Mascarar números de cartão de crédito rapidamente usando o pós‑processamento + OCR do AsposeAI. Aprenda conformidade PCI, mascaramento com expressões regulares + e sanitização de dados em um tutorial passo a passo. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: pt +og_description: Mascarar números de cartão de crédito nos resultados de OCR com AsposeAI. + Este tutorial aborda conformidade PCI, mascaramento com expressões regulares e sanitização + de dados. +og_title: Mascarar Números de Cartão de Crédito – Guia Completo de Pós‑Processamento + OCR em Python +tags: +- OCR +- Python +- security +title: Mascarar números de cartão de crédito na saída de OCR – Guia completo de Python +url: /pt/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mascarar Números de Cartão de Crédito – Guia Completo em Python + +Já precisou **mascarar números de cartão de crédito** em texto que vem direto de um motor OCR? Você não está sozinho. Em indústrias regulamentadas, expor um PAN completo (Primary Account Number) pode causar problemas com auditores de conformidade PCI. A boa notícia? Com algumas linhas de Python e o hook de pós‑processamento da AsposeAI, você pode ocultar automaticamente os oito dígitos centrais e ficar seguro. + +Neste tutorial vamos percorrer um cenário real: executar OCR em uma imagem de recibo e, em seguida, aplicar uma função personalizada de **pós‑processamento OCR** que sanitiza quaisquer dados PCI. Ao final, você terá um trecho reutilizável que pode inserir em qualquer fluxo de trabalho AsposeAI, além de algumas dicas práticas para lidar com casos extremos e escalar a solução. + +## O que você aprenderá + +- Como registrar um pós‑processador personalizado com **AsposeAI**. +- Por que uma abordagem de **mascaramento com expressão regular** é rápida e confiável. +- O básico da **conformidade PCI** relacionado à sanitização de dados. +- Como estender o padrão para múltiplos formatos de cartão ou números internacionais. +- Saída esperada e como verificar se o mascaramento funcionou. + +> **Pré‑requisitos** – Você deve ter um ambiente Python 3 funcionando, o pacote Aspose.AI for OCR instalado (`pip install aspose-ocr`), e uma imagem de exemplo (por exemplo, `receipt.png`) que contenha um número de cartão de crédito. Nenhum outro serviço externo é necessário. + +--- + +## Etapa 1: Definir um Pós‑Processador que Mascarar Números de Cartão de Crédito + +O coração da solução está em uma pequena função que recebe o resultado do OCR, executa uma rotina de **mascaramento com expressão regular** e devolve o texto sanitizado. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Por que isso funciona:** +- A regex `(\d{4})\d{8}(\d{4})` corresponde exatamente a 16 dígitos consecutivos, o formato comum para Visa, MasterCard e muitos outros. +- Ao capturar os quatro primeiros e os quatro últimos dígitos (`\1` e `\2`) preservamos informação suficiente para depuração, ao mesmo tempo que cumprimos as regras de **conformidade PCI** que proíbem armazenar o PAN completo. +- A substituição `\1****\2` oculta os oito dígitos centrais sensíveis, transformando `1234567812345678` em `1234****5678`. + +> **Dica profissional:** Se precisar dar suporte a números American Express de 15 dígitos, adicione um segundo padrão como `r'(\d{4})\d{6}(\d{5})'` e execute ambas as substituições sequencialmente. + +--- + +## Etapa 2: Inicializar o Motor AsposeAI + +Antes de podermos anexar nosso pós‑processador, precisamos de uma instância do motor OCR. A AsposeAI inclui o modelo OCR e uma API simples para processamento customizado. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Por que inicializar aqui?** +Criar o objeto `AsposeAI` uma única vez e reutilizá‑lo em várias imagens reduz a sobrecarga. O motor também faz cache dos modelos de idioma, o que acelera chamadas subsequentes — útil quando você está escaneando lotes de recibos. + +## Etapa 3: Registrar a Função de Mascaramento Personalizada + +A AsposeAI expõe o método `set_post_processor` que permite conectar qualquer callable. Passamos nossa função `mask_pci` junto com um dicionário de configurações opcional (vazio por enquanto). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**O que está acontecendo nos bastidores?** +Quando você invocar `run_postprocessor` mais tarde, a AsposeAI entregará o resultado bruto do OCR à `mask_pci`. A função recebe um objeto leve (`data`) que contém o texto reconhecido, e você devolve uma nova string. Esse design mantém o OCR central intacto enquanto permite impor políticas de **sanitização de dados** em um único ponto. + +## Etapa 4: Executar OCR na Imagem do Recibo + +Agora que o motor sabe como limpar a saída, alimentamos uma imagem. Para fins deste tutorial, assumimos que você já possui um objeto `engine` configurado com o idioma e as definições de resolução corretas. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Dica:** Se você ainda não tem um objeto pré‑configurado, pode criá‑lo com: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +A chamada `recognize_image` devolve um objeto cujo atributo `text` contém a string bruta, sem mascaramento. + +## Etapa 5: Aplicar o Pós‑Processador Registrado + +Com os dados OCR brutos em mãos, os entregamos à instância de IA. O motor executa automaticamente a função `mask_pci` que registramos anteriormente. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Por que usar `run_postprocessor` em vez de chamar a função manualmente?** +Isso mantém o fluxo de trabalho consistente, especialmente quando há múltiplos pós‑processadores (por exemplo, correção ortográfica, detecção de idioma). A AsposeAI os enfileira na ordem em que são registrados, garantindo saída determinística. + +## Etapa 6: Verificar a Saída Sanitizada + +Por fim, vamos imprimir o texto sanitizado e confirmar que quaisquer números de cartão de crédito foram corretamente mascarados. + +```python +print(final_result.text) +``` + +**Saída esperada** (trecho): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Se o recibo não continha número de cartão, o texto permanece inalterado — nada a mascarar, nada a se preocupar. + +## Lidando com Casos Extremos e Variações Comuns + +### Vários Números de Cartão em um Mesmo Documento +Se um recibo inclui mais de um PAN (por exemplo, um cartão de fidelidade mais um cartão de pagamento), a regex roda globalmente, mascarando todas as ocorrências automaticamente. Não é necessário código extra. + +### Formatação Não‑Padrão +Às vezes o OCR insere espaços ou hífens (`1234 5678 1234 5678` ou `1234-5678-1234-5678`). Amplie o padrão para ignorar esses caracteres: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +O `[ -]?` adicionado tolera espaços ou hífens opcionais entre blocos de dígitos. + +### Cartões Internacionais +Para PANs de 19 dígitos usados em algumas regiões, você pode ampliar o padrão: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Lembre‑se apenas de que **conformidade PCI** ainda exige mascarar os dígitos centrais, independentemente do comprimento. + +### Registro de Valores Mascarados (Opcional) +Se precisar de trilhas de auditoria, passe uma bandeira via `custom_settings` e ajuste a função: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Em seguida registre com: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +## Exemplo Completo Funcional (Pronto para Copiar‑Colar) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Executar este script em um recibo que contenha `4111111111111111` produzirá: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +Esse é todo o pipeline — do OCR bruto à **sanitização de dados** — encapsulado em algumas linhas limpas de Python. + +## Conclusão + +Acabamos de mostrar como **mascarar números de cartão de crédito** em resultados de OCR usando o hook de pós‑processamento da AsposeAI, uma rotina concisa de expressão regular e algumas dicas de boas práticas para **conformidade PCI**. A solução é totalmente autônoma, funciona com qualquer imagem que o motor OCR consiga ler e pode ser estendida para cobrir formatos de cartão mais complexos ou requisitos de registro. + +Pronto para o próximo passo? Experimente combinar esse mascaramento com uma rotina de **inserção em banco de dados** que armazene apenas os quatro últimos dígitos para referência, ou integre um **processador em lote** que escaneie uma pasta inteira de recibos durante a noite. Você também pode explorar outras tarefas de **pós‑processamento OCR**, como padronização de endereços ou detecção de idioma — todas seguem o mesmo padrão que usamos aqui. + +Tem dúvidas sobre casos extremos, desempenho ou como adaptar o código para outra biblioteca OCR? Deixe um comentário abaixo e vamos continuar a conversa. Feliz codificação e mantenha‑se seguro! + +![Diagram illustrating how mask credit card numbers works in an OCR pipeline](https://example.com/images/ocr-mask-flow.png "Diagram of OCR post‑processing masking flow") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/portuguese/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..ac40795d1 --- /dev/null +++ b/ocr/portuguese/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-04-26 +description: Aprenda a medir o tempo de inferência em Python, carregar um modelo GGUF + do Hugging Face e otimizar o uso da GPU para resultados mais rápidos. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: pt +og_description: Meça o tempo de inferência em Python carregando um modelo GGUF do + Hugging Face e ajustando as camadas da GPU para desempenho ideal. +og_title: Medir o Tempo de Inferência – Carregar Modelo GGUF e Otimizar GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Medir o Tempo de Inferência – Carregar Modelo GGUF e Otimizar GPU +url: /pt/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Medir o Tempo de Inferência – Carregar Modelo GGUF & Otimizar GPU + +Já precisou **medir o tempo de inferência** de um modelo de linguagem grande, mas não sabia por onde começar? Você não está sozinho—muitos desenvolvedores esbarram na mesma dificuldade ao baixar um arquivo GGUF do Hugging Face e tentar executá‑lo em um ambiente misto CPU/GPU. + +Neste guia vamos percorrer **como carregar um modelo GGUF**, configurá‑lo para Hugging Face e **medir o tempo de inferência** com um snippet Python limpo. Ao longo do caminho também mostraremos como **otimizar a inferência na GPU** para que suas execuções sejam o mais rápidas possível. Sem enrolação, apenas uma solução prática de ponta a ponta que você pode copiar‑colar hoje. + +## O que você vai aprender + +- Como **configurar um modelo HuggingFace** com `AsposeAIModelConfig`. +- Os passos exatos para **carregar um modelo GGUF** (quantização `fp16`) a partir do hub Hugging Face. +- Um padrão reutilizável para **cronometrar código Python** ao redor de uma chamada de inferência. +- Dicas para **otimizar a inferência na GPU** ajustando `gpu_layers`. +- Saída esperada e como verificar se a sua medição faz sentido. + +### Pré‑requisitos + +| Requisito | Por que importa | +|-----------|-----------------| +| Python 3.9+ | Sintaxe moderna e type hints. | +| pacote `asposeai` (ou o SDK equivalente) | Fornece `AsposeAI` e `AsposeAIModelConfig`. | +| Acesso ao repositório Hugging Face `bartowski/Qwen2.5-3B-Instruct-GGUF` | O modelo GGUF que vamos carregar. | +| Uma GPU com pelo menos 8 GB de VRAM (opcional, mas recomendado) | Permite a etapa de **otimizar a inferência na GPU**. | + +Se ainda não instalou o SDK, execute: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![diagrama de medição de tempo de inferência](https://example.com/measure-inference-time.png){alt="diagrama de medição de tempo de inferência"} + +## Etapa 1: Carregar o Modelo GGUF – Configurar Modelo HuggingFace + +A primeira coisa que você precisa é um objeto de configuração adequado que indique ao Aspose AI onde buscar o modelo e como tratá‑lo. É aqui que **carregamos um modelo GGUF** e **configuramos os parâmetros do modelo huggingface**. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Por que isso importa:** +- `hugging_face_repo_id` aponta para o arquivo GGUF exato no Hub. +- `fp16` reduz a largura de banda de memória enquanto mantém a maior parte da fidelidade do modelo. +- `gpu_layers` é o ajuste que você modifica quando deseja **otimizar a inferência na GPU**; mais camadas na GPU geralmente significam latência menor, desde que haja VRAM suficiente. + +## Etapa 2: Criar a Instância Aspose AI + +Agora que o modelo está descrito, instanciamos um objeto `AsposeAI`. Esta etapa é direta, mas é onde o SDK realmente baixa o arquivo GGUF (se ainda não estiver em cache) e prepara o runtime. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Dica de especialista:** A primeira execução levará alguns segundos a mais porque o modelo está sendo baixado e compilado para a GPU. Execuções subsequentes são extremamente rápidas. + +## Etapa 3: Executar a Inferência e **Medir o Tempo de Inferência** + +Aqui está o coração do tutorial: envolver a chamada de inferência com `time.time()` para **medir o tempo de inferência**. Também fornecemos um pequeno resultado de OCR apenas para manter o exemplo autocontido. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**O que você deve ver:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Se o número parecer alto, provavelmente a maioria das camadas está sendo executada na CPU. Isso nos leva à próxima etapa. + +## Etapa 4: **Otimizar a Inferência na GPU** – Ajustar `gpu_layers` + +Às vezes o padrão `gpu_layers=40` é agressivo demais (causando OOM) ou conservador demais (deixando desempenho na mesa). Aqui está um loop rápido que você pode usar para encontrar o ponto ideal: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Por que isso funciona:** +- Cada chamada reconstrói o runtime com uma alocação de GPU diferente, permitindo ver a troca de latência instantaneamente. +- O loop também demonstra **time python code** de forma reutilizável, que você pode adaptar para outros testes de desempenho. + +Saída típica em uma RTX 3080 de 16 GB pode ser semelhante a: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +A partir disso, você escolheria `gpu_layers=40` como o ponto ótimo para esse hardware. + +## Exemplo Completo Funcionando + +Juntando tudo, aqui está um script único que você pode salvar em um arquivo (`measure_inference.py`) e executar: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Execute com: + +```bash +python measure_inference.py +``` + +Você deverá observar latência inferior a um segundo em uma GPU decente, confirmando que você **mediu o tempo de inferência** e **otimizou a inferência na GPU** com sucesso. + +--- + +## Perguntas Frequentes (FAQs) + +**Q: Isso funciona com outros formatos de quantização?** +A: Absolutamente. Troque `hugging_face_quantization="int8"` (ou `q4_0`, etc.) na configuração e reexecute o benchmark. Espere um trade‑off: menor uso de memória vs. leve queda de precisão. + +**Q: E se eu não tiver uma GPU?** +A: Defina `gpu_layers=0`. O código recairá totalmente na CPU, e você ainda poderá **medir o tempo de inferência**—apenas espere números mais altos. + +**Q: Posso cronometrar apenas a passagem forward do modelo, excluindo o pós‑processamento?** +A: Sim. Chame `ai_engine.run_model(...)` (ou o método equivalente) diretamente e envolva essa chamada com `time.time()`. O padrão para **time python code** permanece o mesmo. + +--- + +## Conclusão + +Agora você tem uma solução completa, pronta para copiar‑colar, para **medir o tempo de inferência** de um modelo GGUF, **carregar modelo gguf** do Hugging Face e ajustar as configurações de **otimizar a inferência na GPU**. Ajustando `gpu_layers` e experimentando quantizações, você pode extrair cada milissegundo de desempenho. + +Próximos passos sugeridos: + +- Integrar essa lógica de medição em um pipeline CI para detectar regressões. +- Explorar inferência em lote para melhorar ainda mais o throughput. +- Combinar o modelo com um pipeline OCR real ao invés do texto fictício usado aqui. + +Bom código, e que seus números de latência permaneçam sempre baixos! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/portuguese/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..a6267291a --- /dev/null +++ b/ocr/portuguese/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,205 @@ +--- +category: general +date: 2026-04-26 +description: reconheça texto manuscrito usando o motor OCR do Python. aprenda como + extrair texto de uma imagem, ativar o modo manuscrito e ler notas manuscritas rapidamente. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: pt +og_description: reconheça texto manuscrito com Python. Este tutorial mostra como extrair + texto de uma imagem, ativar o modo manuscrito e ler anotações manuscritas usando + um motor OCR simples. +og_title: reconheça texto manuscrito em Python – Guia completo de OCR +tags: +- OCR +- Python +- Handwriting Recognition +title: reconhecer texto manuscrito em Python – Tutorial do motor OCR +url: /pt/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# reconhecer texto manuscrito em Python – OCR Engine Tutorial + +Já precisou **recognize handwritten text** mas ficou preso no “por onde começar?”? Você não está sozinho. Seja digitalizando rabiscos de reunião ou extraindo dados de um formulário escaneado, obter um resultado confiável de OCR pode parecer caçar um unicórnio. + +Boa notícia: com apenas algumas linhas de Python você pode **extract text from image** files, **turn on handwritten mode**, e finalmente **read handwritten notes** sem precisar caçar bibliotecas obscuras. Neste guia percorreremos todo o processo, desde a configuração no estilo **create OCR engine python** até imprimir o resultado na tela. + +## O que você aprenderá + +- Como criar uma instância **create OCR engine python** usando o pacote `ocr`. +- Qual configuração de idioma fornece suporte nativo a manuscritos. +- A chamada exata para **turn on handwritten mode** para que o motor saiba que você está lidando com caligrafia. +- Como alimentar uma foto de uma nota e **recognize handwritten text** a partir dela. +- Dicas para lidar com diferentes formatos de imagem, solucionar problemas comuns e expandir a solução. + +Sem enrolação, sem “veja a documentação” sem saída—apenas um script completo e executável que você pode copiar‑colar e testar hoje. + +## Pré-requisitos + +Antes de mergulharmos, certifique-se de que você tem: + +1. Python 3.8+ instalado (o código usa f‑strings). +2. A biblioteca hipotética `ocr` (`pip install ocr‑engine` – substitua pelo nome real do pacote que você está usando). +3. Um arquivo de imagem nítido de uma nota manuscrita (JPEG, PNG ou TIFF funciona). +4. Uma dose modesta de curiosidade—todo o resto está coberto abaixo. + +> **Dica profissional:** Se sua imagem estiver ruidosa, execute uma etapa rápida de pré‑processamento com Pillow (por exemplo, `Image.open(...).convert('L')`) antes de enviá‑la ao motor OCR. Isso costuma melhorar a precisão. + +## Como reconhecer texto manuscrito com Python + +Abaixo está o script completo que **creates OCR engine python** objetos, os configura para manuscritos e imprime a string extraída. Salve como `handwriting_ocr.py` e execute no seu terminal. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Saída esperada + +Quando o script for executado com sucesso, você verá algo como: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Se o motor OCR não conseguir detectar nenhum caractere, o campo `text` será uma string vazia. Nesse caso, verifique novamente a qualidade da imagem ou tente uma digitalização de resolução mais alta. + +## Explicação passo a passo + +### Etapa 1 – Instância **create OCR engine python** + +A classe `OcrEngine` é o ponto de entrada. Pense nela como um caderno em branco—nada acontece até que você indique qual idioma esperar e se está lidando com manuscrito. + +### Etapa 2 – Escolha um idioma que suporte manuscritos + +`ocr.Language.EXTENDED_LATIN` não é apenas “English”. Ele agrupa um conjunto de scripts baseados em latim e, crucialmente, inclui modelos treinados em amostras cursivas. Pular esta etapa costuma gerar saída confusa porque o motor padrão usa um modelo de texto impresso. + +### Etapa 3 – **turn on handwritten mode** + +Chamar `enable_handwritten_mode(True)` altera uma bandeira interna. O motor então muda para sua rede neural ajustada ao espaçamento irregular e larguras de traço variáveis que você vê em notas reais. Esquecer esta linha é um erro comum; o motor tratará seus rabiscos como ruído. + +### Etapa 4 – Alimente a imagem e **recognize handwritten text** + +`recognize_image` faz o trabalho pesado: pré‑processa o bitmap, executa‑o através do modelo de manuscrito e retorna um objeto com o atributo `text`. Você também pode inspecionar `handwritten_result.confidence` se precisar de uma métrica de qualidade. + +### Etapa 5 – Imprima o resultado e **read handwritten notes** + +`print(handwritten_result.text)` é a maneira mais simples de verificar que você **extract text from image** com sucesso. Em produção, você provavelmente armazenaria a string em um banco de dados ou a enviaria para outro serviço. + +## Lidando com casos de borda e variações comuns + +| Situação | O que fazer | +|-----------|------------| +| **Imagem está rotacionada** | Use Pillow para rotacionar (`Image.rotate(angle)`) antes de chamar `recognize_image`. | +| **Baixo contraste** | Converta para escala de cinza e aplique limiarização adaptativa (`Image.point(lambda p: p > 128 and 255)`). | +| **Múltiplas páginas** | Itere sobre uma lista de caminhos de arquivos e concatene os resultados. | +| **Scripts não latinos** | Substitua `EXTENDED_LATIN` por `ocr.Language.CHINESE` (ou apropriado) e mantenha `enable_handwritten_mode(True)`. | +| **Preocupações de desempenho** | Reutilize a mesma instância `ocr_engine` em muitas imagens; inicializá‑la a cada vez adiciona sobrecarga. | + +### Dica profissional sobre uso de memória + +Se você estiver processando centenas de notas em lote, chame `ocr_engine.dispose()` após terminar. Isso libera recursos nativos que o wrapper Python pode estar mantendo. + +## Recapitulação visual rápida + +![recognize handwritten text example](https://example.com/handwritten-note.png "recognize handwritten text example") + +*A imagem acima mostra uma nota manuscrita típica que nosso script pode transformar em texto simples.* + +## Exemplo completo em funcionamento (script de um arquivo) + +Para quem adora a simplicidade de copiar‑colar, aqui está tudo novamente sem os comentários explicativos: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Execute com: + +```bash +python handwriting_ocr.py +``` + +Agora você deve ver a saída **recognize handwritten text** no seu console. + +## Conclusão + +Acabamos de cobrir tudo que você precisa para **recognize handwritten text** em Python—começando de uma chamada fresca **create OCR engine python**, selecionando o idioma correto, **turn on handwritten mode**, e finalmente **extract text from image** para **read handwritten notes**. + +Em um único script autônomo, você pode passar de uma foto borrada de um rabisco de reunião para texto limpo e pesquisável. Em seguida, considere alimentar a saída em um pipeline de linguagem natural, armazená‑la em um índice pesquisável ou até mesmo enviá‑la de volta para um serviço de transcrição para geração de narração. + +### Para onde ir a partir daqui? + +- **Processamento em lote:** Envolva o script em um loop para lidar com uma pasta de digitalizações. +- **Filtragem por confiança:** Use `result.confidence` para descartar leituras de baixa qualidade. +- **Bibliotecas alternativas:** Se `ocr` não for um ajuste perfeito, explore `pytesseract` com `--psm 13` para modo manuscrito. +- **Integração de UI:** Combine com Flask ou FastAPI para oferecer um serviço de upload baseado na web. + +Tem perguntas sobre um formato de imagem específico ou precisa de ajuda para ajustar o modelo? Deixe um comentário abaixo, e feliz codificação! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/russian/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..0cee1c59d --- /dev/null +++ b/ocr/russian/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-04-26 +description: Узнайте, как скачать модель HuggingFace на Python и извлечь текст из + изображения на Python, улучшая точность OCR на Python с помощью Aspose OCR Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: ru +og_description: Скачайте модель HuggingFace для Python и ускорьте ваш OCR‑конвейер. + Следуйте этому руководству, чтобы извлекать текст из изображения с помощью Python + и повышать точность OCR в Python. +og_title: скачать модель huggingface python – Полный учебник по улучшению OCR +tags: +- OCR +- HuggingFace +- Python +- AI +title: Скачать модель HuggingFace на Python – пошаговое руководство по ускорению OCR. +url: /ru/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – Полный учебник по улучшению OCR + +Когда‑нибудь пытались **download HuggingFace model python** и чувствовали себя немного потерянными? Вы не одиноки. Во многих проектах главным узким местом является загрузка хорошей модели на ваш компьютер и последующее превращение результатов OCR в действительно полезные. + +В этом руководстве мы пройдём через практический пример, который покажет, как именно **download HuggingFace model python**, извлекать текст из изображения с помощью **extract text from image python**, а затем **improve OCR accuracy python** с использованием AI‑постпроцессора Aspose. К концу вы получите готовый к запуску скрипт, превращающий шумное изображение счёта в чистый, читаемый текст — без магии, только чёткие шаги. + +## Что вам понадобится + +- Python 3.9+ (код работает и на 3.11) +- Подключение к интернету для однократной загрузки модели +- Пакет `asposeocrcloud` (`pip install asposeocrcloud`) +- Пример изображения (например, `sample_invoice.png`), размещённый в папке, которой вы управляете + +Вот и всё — без тяжёлых фреймворков, без драйверов, специфичных для GPU, если только вы не хотите ускорить процесс. + +А теперь давайте погрузимся в реальную реализацию. + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## Шаг 1: Настройте OCR‑движок и выберите язык +*(Здесь мы начинаем **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Почему это важно:** +OCR‑движок — первая линия защиты; выбор правильного языкового пакета сразу уменьшает ошибки распознавания символов, что является ключевой частью **improve OCR accuracy python**. + +## Шаг 2: Настройте модель AsposeAI – загрузка с HuggingFace +*(Здесь мы действительно **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**Что происходит «под капотом»?** +Когда `allow_auto_download` установлен в true, SDK обращается к HuggingFace, загружает модель `Qwen2.5‑3B‑Instruct‑GGUF` и сохраняет её в указанную папку. Это и есть ядро **download huggingface model python** — SDK берёт на себя всю тяжёлую работу, так что вам не придётся писать `git clone` или `wget`. + +*Совет:* Держите `directory_model_path` на SSD для более быстрых загрузок; модель занимает около 3 ГБ даже в виде `int8`. + +## Шаг 3: Привяжите AI‑движок к OCR‑движку +*(Связываем два компонента, чтобы **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Зачем их связывать?** +OCR‑движок выдаёт «сырой» текст, в котором могут быть опечатки, разорванные строки или неправильная пунктуация. AI‑движок выступает в роли умного редактора, исправляя эти проблемы — именно то, что нужно для **improve OCR accuracy python**. + +## Шаг 4: Запустите OCR на вашем изображении +*(Наконец‑то мы **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` теперь содержит атрибут `text` с необработанными символами, которые увидел движок. На практике вы заметите небольшие глюки — например, «Invoice» может превратиться в «Inv0ice» или появиться разрыв строки посередине предложения. + +## Шаг 5: Очистка с помощью AI‑постпроцессора +*(Этот шаг непосредственно **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +AI‑модель переписывает текст, применяя исправления, учитывающие язык. Поскольку мы используем instruction‑tuned модель из HuggingFace, вывод обычно звучит естественно и готов к дальнейшей обработке. + +## Шаг 6: Показать «до» и «после» +*(Быстрая проверка, насколько хорошо мы **extract text from image python** и **improve OCR accuracy python**.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Ожидаемый вывод + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Обратите внимание, как AI исправил «Inv0ice» на «Invoice» и убрал лишние разрывы строк. Это осязаемый результат **improve OCR accuracy python** с использованием загруженной модели HuggingFace. + +## Часто задаваемые вопросы (FAQ) + +### Нужно ли мне GPU для запуска модели? +Нет. Параметр `gpu_layers=20` сообщает SDK использовать до 20 слоёв GPU, если совместимый GPU присутствует; в противном случае происходит откат на CPU. На современном ноутбуке путь через CPU всё равно обрабатывает несколько сотен токенов в секунду — идеально для редкой обработки счетов. + +### Что делать, если модель не загружается? +Убедитесь, что ваша среда может достичь `https://huggingface.co`. Если вы за корпоративным прокси, задайте переменные окружения `HTTP_PROXY` и `HTTPS_PROXY`. SDK будет автоматически повторять попытки, но вы также можете вручную выполнить `git lfs pull` репозитория в `directory_model_path`. + +### Можно ли заменить модель на более маленькую? +Конечно. Просто замените `hugging_face_repo_id` на другой репозиторий (например, `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) и скорректируйте `hugging_face_quantization` соответственно. Меньшие модели скачиваются быстрее и требуют меньше RAM, хотя качество исправлений может немного пострадать. + +### Как это помогает мне **extract text from image python** в других областях? +Тот же конвейер работает с чеками, паспортами или рукописными заметками. Единственное, что меняется, — языковой пакет (`ocr.Language.FRENCH` и т.д.) и, возможно, специализированная дообученная модель из HuggingFace. + +## Бонус: Автоматизация обработки нескольких файлов + +Если у вас есть папка, полная изображений, оберните вызов OCR в простой цикл: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +Это небольшое дополнение позволяет **download huggingface model python** один раз, а затем пакетно обрабатывать десятки файлов — отлично подходит для масштабирования вашего конвейера автоматизации документов. + +## Заключение + +Мы только что прошли полный сквозной пример, показывающий, как **download HuggingFace model python**, **extract text from image python** и **improve OCR accuracy python** с помощью Aspose OCR Cloud и AI‑постпроцессора. Скрипт готов к запуску, концепции объяснены, и вы увидели вывод «до‑и‑после», так что знаете, что всё работает. + +Что дальше? Попробуйте заменить модель HuggingFace, поэкспериментируйте с другими языковыми пакетами или передайте очищенный текст в downstream‑NLP конвейер (например, извлечение сущностей из строк счёта). Возможности безграничны, а фундамент, который вы только что построили, надёжен. + +Есть вопросы или «проблемное» изображение, которое всё ещё сбивает OCR? Оставьте комментарий ниже, и давайте разбираться вместе. Счастливого кодинга! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/russian/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..377e29c30 --- /dev/null +++ b/ocr/russian/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-04-26 +description: Быстро скачайте OCR‑модель с помощью Aspose OCR Python. Узнайте, как + задать каталог модели, настроить путь к модели и как загрузить модель в несколько + строк. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: ru +og_description: Скачайте OCR‑модель за секунды с Aspose OCR Python. Это руководство + показывает, как установить каталог модели, настроить путь к модели и как безопасно + загрузить модель. +og_title: скачать OCR‑модель — Полный учебник Aspose OCR на Python +tags: +- OCR +- Python +- Aspose +title: Скачивание OCR‑модели с Aspose OCR Python – пошаговое руководство +url: /ru/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# загрузить ocr модель – Полный учебник Aspose OCR для Python + +Когда‑то задумывались, как **загрузить ocr модель** с помощью Aspose OCR в Python, не копаясь в бесконечных документах? Вы не одиноки. Многие разработчики сталкиваются с проблемой, когда модель отсутствует локально, а SDK выдаёт непонятную ошибку. Хорошая новость? Решение состоит из нескольких строк кода, и модель будет готова к использованию за считанные минуты. + +В этом учебнике мы пройдём всё, что нужно знать: от импорта нужных классов, до **установки каталога модели**, до самого **как загрузить модель**, и, наконец, проверки пути. К концу вы сможете выполнять OCR на любом изображении одним вызовом функции и поймёте варианты **настройки пути к модели**, которые помогут поддерживать ваш проект в порядке. Без лишних слов, только практический, готовый к запуску пример для пользователей **aspose ocr python**. + +## Что вы узнаете + +- Как правильно импортировать классы Aspose OCR Cloud. +- Точные шаги для **загрузки ocr модели** автоматически. +- Способы **установки каталога модели** и **настройки пути к модели** для воспроизводимых сборок. +- Как проверить, что модель инициализирована и где она находится на диске. +- Распространённые подводные камни (разрешения, отсутствие каталогов) и быстрые решения. + +### Предварительные требования + +- Python 3.8+ установленный на вашем компьютере. +- Пакет `asposeocrcloud` (`pip install asposeocrcloud`). +- Права записи в папку, где вы хотите хранить модель (например, `C:\models` или `~/ocr_models`). + +--- + +## Шаг 1: Импортировать классы Aspose OCR Cloud + +Первое, что вам нужно — правильное объявление импорта. Оно подтягивает классы, управляющие конфигурацией модели и операциями OCR. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Почему это важно:* `AsposeAI` — движок, который будет выполнять OCR, а `AsposeAIModelConfig` указывает движку **где** искать модель и **нужно** ли её автоматически загружать. Пропуск этого шага или импорт неправильного модуля вызовет `ModuleNotFoundError` ещё до того, как вы дойдёте до части загрузки. + +--- + +## Шаг 2: Определить конфигурацию модели (Установить каталог модели & Настроить путь к модели) + +Теперь мы говорим Aspose, где хранить файлы модели. Здесь вы **устанавливаете каталог модели** и **настраиваете путь к модели**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Советы и подводные камни** + +- **Абсолютные пути** избавляют от путаницы, когда скрипт запускается из другой рабочей директории. +- На Linux/macOS можно использовать `"/home/you/ocr_models"`; на Windows добавьте префикс `r`, чтобы обратные слеши воспринимались буквально. +- Установка `allow_auto_download="true"` — ключ к **как загрузить модель** без написания дополнительного кода. + +--- + +## Шаг 3: Создать экземпляр AsposeAI с использованием конфигурации + +Когда конфигурация готова, создаём объект OCR‑движка. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Почему это важно:* Объект `ocr_ai` теперь содержит только что определённую конфигурацию. Если модель отсутствует, следующий вызов автоматически инициирует её загрузку — это суть **как загрузить модель** без вмешательства пользователя. + +--- + +## Шаг 4: Инициировать загрузку модели (при необходимости) + +Прежде чем запускать OCR, нужно убедиться, что модель действительно находится на диске. Метод `is_initialized()` одновременно проверяет и принудительно инициализирует её. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**Что происходит «под капотом»?** + +- Первый вызов `is_initialized()` возвращает `False`, потому что папка модели пуста. +- `print` информирует пользователя, что загрузка скоро начнётся. +- Второй вызов заставляет Aspose загрузить модель из репозитория Hugging Face, указанный ранее. +- После загрузки метод возвращает `True` при последующих проверках. + +**Особый случай:** Если ваша сеть блокирует Hugging Face, вы увидите исключение. В этом случае вручную скачайте zip‑архив модели, распакуйте его в `directory_model_path` и запустите скрипт снова. + +--- + +## Шаг 5: Вывести локальный путь, где модель теперь доступна + +После завершения загрузки, вероятно, захотите знать, куда попали файлы. Это полезно для отладки и настройки CI‑конвейеров. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Обычный вывод выглядит так: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Теперь вы успешно **загрузили ocr модель**, задали каталог и подтвердили путь. + +--- + +## Визуальный обзор + +Ниже простая диаграмма, показывающая поток от конфигурации до готовой к использованию модели. + +![диаграмма процесса загрузки ocr модели, показывающая конфигурацию, автоматическую загрузку и локальный путь](/images/download-ocr-model-flow.png) + +*Alt‑текст включает основной ключевой запрос для SEO.* + +--- + +## Распространённые варианты и как с ними работать + +### 1. Использование другого репозитория модели + +Если нужна модель, отличная от `openai/gpt2`, просто замените значение `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Убедитесь, что репозиторий публичный или у вас установлен необходимый токен в переменных окружения. + +### 2. Отключение автоматической загрузки + +Иногда требуется контролировать загрузку вручную (например, в изолированных средах). Установите `allow_auto_download` в `"false"` и вызовите собственный скрипт загрузки перед инициализацией: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Изменение каталога модели во время выполнения + +Можно переустановить путь без создания нового объекта `AsposeAI`: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Профессиональные советы для продакшн‑использования + +- **Кешировать модель**: Разместите каталог на общем сетевом диске, если несколько сервисов используют одну и ту же модель. Это избавит от повторных загрузок. +- **Фиксация версии**: Репозиторий Hugging Face может обновляться. Чтобы зафиксировать конкретную версию, добавьте `@v1.0.0` к ID репозитория (`"openai/gpt2@v1.0.0"`). +- **Разрешения**: Убедитесь, что пользователь, запускающий скрипт, имеет права чтения/записи в `directory_model_path`. На Linux обычно достаточно `chmod 755`. +- **Логирование**: Замените простые `print` на модуль `logging` Python для лучшей наблюдаемости в крупных приложениях. + +--- + +## Полный рабочий пример (готовый к копированию) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Ожидаемый вывод** (при первом запуске будет загрузка, при последующих — пропуск загрузки): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Запустите скрипт ещё раз; вы увидите только строку с путём, потому что модель уже закеширована. + +--- + +## Заключение + +Мы рассмотрели полный процесс **загрузки ocr модели** с помощью Aspose OCR Python, показали, как **установить каталог модели**, и объяснили нюансы **настройки пути к модели**. Всего несколькими строками кода вы можете автоматизировать загрузку, избавиться от ручных шагов и сделать ваш OCR‑конвейер воспроизводимым. + +Дальше вы можете исследовать сам вызов OCR (`ocr_ai.recognize_image(...)`) или поэкспериментировать с другой моделью Hugging Face для повышения точности. В любом случае, построенная здесь база — чёткая конфигурация, автоматическая загрузка и проверка пути — упростит любые будущие интеграции. + +Есть вопросы о крайних случаях или хотите поделиться, как вы настроили каталог модели для облачных развертываний? Оставляйте комментарий ниже, и счастливого кодинга! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/russian/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..d1ab659ca --- /dev/null +++ b/ocr/russian/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-26 +description: Как постобрабатывать результаты OCR и извлекать текст с координатами. + Узнайте пошаговое решение с использованием структурированного вывода и AI‑коррекции. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: ru +og_description: Как постобрабатывать результаты OCR и извлекать текст с координатами. + Следуйте этому подробному руководству для надёжного рабочего процесса. +og_title: Как постобработать OCR – Полное руководство +tags: +- OCR +- Python +- AI +- Text Extraction +title: Как постобработать OCR – извлечь текст с координатами в Python +url: /ru/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как пост‑обработать OCR – извлечь текст с координатами в Python + +Когда‑нибудь вам приходилось **пост‑обрабатывать OCR**‑результаты, потому что сырой вывод был шумным или смещённым? Вы не одиноки. Во многих реальных проектах — сканирование счетов, оцифровка чеков или даже дополнение AR‑опыта — OCR‑движок выдаёт сырые слова, но их всё равно нужно очистить и отследить, где каждое слово находится на странице. Здесь в игру вступает режим структурированного вывода в сочетании с AI‑управляемой пост‑обработкой. + +В этом руководстве мы пройдём полный, готовый к запуску Python‑конвейер, который **извлекает текст с координатами** из изображения, запускает шаг коррекции на основе AI и выводит каждое слово вместе с его позицией (x, y). Никаких недостающих импортов, никаких расплывчатых «см. документацию»‑шорткатов — просто автономное решение, которое вы можете сразу внедрить в свой проект. + +> **Совет:** Если вы используете другую библиотеку OCR, ищите режим «structured» или «layout»; концепции остаются теми же. + +--- + +## Требования + +Прежде чем погрузиться, убедитесь, что у вас есть: + +| Требование | Почему это важно | +|-------------|-------------------| +| Python 3.9+ | Современный синтаксис и подсказки типов | +| `ocr` library that supports `OutputMode.STRUCTURED` (e.g., a fictional `myocr`) | Необходима для данных ограничивающих рамок | +| An AI post‑processing module (could be OpenAI, HuggingFace, or a custom model) | Повышает точность после OCR | +| An image file (`input.png`) in your working directory | Исходный файл, который будем читать | + +Если что‑то из этого вам незнакомо, просто установите заглушечные пакеты командой `pip install myocr ai‑postproc`. Ниже представленный код также включает fallback‑заглушки, чтобы вы могли протестировать поток без реальных библиотек. + +--- + +## Шаг 1: Включить режим структурированного вывода для OCR‑движка + +Первое, что мы делаем, — просим OCR‑движок выдавать не просто простой текст. Структурированный вывод возвращает каждое слово вместе с ограничивающим прямоугольником и оценкой уверенности, что необходимо для **извлечения текста с координатами** позже. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Почему это важно:* Без структурированного режима вы получите лишь длинную строку и потеряете пространственную информацию, необходимую для наложения текста на изображения или дальнейшего анализа макета. + +--- + +## Шаг 2: Распознать изображение и получить слова, рамки и уверенность + +Теперь мы передаём изображение в движок. Результат — объект, содержащий список объектов‑слов, каждый из которых раскрывает `text`, `x`, `y`, `width`, `height` и `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Особый случай:* Если изображение пустое или нечитаемое, `structured_result.words` будет пустым списком. Хорошая практика — проверять это и корректно обрабатывать ситуацию. + +--- + +## Шаг 3: Запустить AI‑основанную пост‑обработку, сохраняя позиции + +Даже лучшие OCR‑движки делают ошибки — например, «O» vs. «0» или отсутствие диакритических знаков. AI‑модель, обученная на доменно‑специфичном тексте, может исправить эти ошибки. При этом мы сохраняем оригинальные координаты, чтобы пространственная раскладка оставалась неизменной. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Почему мы сохраняем координаты:* Многие последующие задачи (например, генерация PDF, маркировка AR) зависят от точного размещения. AI меняет только поле `text`, оставляя `x`, `y`, `width`, `height` без изменений. + +--- + +## Шаг 4: Пройтись по исправленным словам и вывести их текст с координатами + +Наконец, мы перебираем исправленные слова и печатаем каждое слово вместе с его левым верхним углом `(x, y)`. Это полностью удовлетворяет задачу **извлечения текста с координатами**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Ожидаемый вывод (пример):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Каждая строка показывает исправленное слово и его точное расположение на оригинальном изображении. + +--- + +## Полный рабочий пример + +Ниже один скрипт, который связывает всё вместе. Скопируйте‑вставьте его, при необходимости поправьте импорт‑операторы под свои библиотеки и запустите напрямую. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Запуск скрипта** + +```bash +python ocr_postprocess_demo.py +``` + +Если у вас установлены реальные библиотеки, скрипт обработает ваш `input.png`. В противном случае заглушечная реализация позволит увидеть ожидаемый поток и вывод без внешних зависимостей. + +--- + +## Часто задаваемые вопросы (FAQ) + +| Вопрос | Ответ | +|----------|--------| +| *Это работает с Tesseract?* | Сам Tesseract не предоставляет структурированный режим «из коробки», но обёртки вроде `pytesseract.image_to_data` возвращают ограничивающие рамки, которые можно передать в тот же AI‑пост‑процессор. | +| *Что если мне нужен правый нижний угол вместо левого верхнего?* | Каждый объект‑слово также предоставляет `width` и `height`. Вычислите `x2 = x + width` и `y2 = y + height`, чтобы получить противоположный угол. | +| *Можно ли пакетно обрабатывать несколько изображений?* | Конечно. Оберните шаги в цикл `for image_path in Path("folder").glob("*.png"):` и собирайте результаты по файлам. | +| *Как выбрать AI‑модель для коррекции?* | Для общего текста подойдёт небольшая GPT‑2, дообученная на OCR‑ошибках. Для специализированных данных (например, медицинских рецептов) обучите seq2seq‑модель на парных «шум‑чистый» данных. | +| *Полезен ли показатель уверенности после AI‑коррекции?* | Вы можете оставить оригинальную уверенность для отладки, но AI может выдавать собственный показатель, если модель его поддерживает. | + +--- + +## Особые случаи и лучшие практики + +1. **Пустые или повреждённые изображения** — всегда проверяйте, что `structured_result.words` не пустой, прежде чем продолжать. +2. **Нелатинские скрипты** — убедитесь, что ваш OCR‑движок настроен под целевой язык; AI‑пост‑процессор должен быть обучен на том же скрипте. +3. **Производительность** — AI‑коррекция может быть ресурсоёмкой. Кешируйте результаты, если будете повторно использовать одно и то же изображение, или запускайте AI‑шаг асинхронно. +4. **Система координат** — OCR‑библиотеки могут использовать разные начала (левый‑верхний vs. левый‑нижний). При наложении на PDF или канвас корректируйте их соответственно. + +--- + +## Заключение + +Теперь у вас есть надёжный сквозной рецепт для **пост‑обработки OCR** и надёжного **извлечения текста с координатами**. Включив структурированный вывод, пропустив результат через слой AI‑коррекции и сохранив оригинальные ограничивающие рамки, вы превращаете шумные OCR‑сканы в чистый, пространственно‑осведомлённый текст, готовый к дальнейшим задачам вроде генерации PDF, автоматизации ввода данных или наложения дополненной реальности. + +Готовы к следующему шагу? Попробуйте заменить заглушку AI на вызов OpenAI `gpt‑4o‑mini`, либо интегрировать конвейер в FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/russian/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..071dedb4d --- /dev/null +++ b/ocr/russian/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-04-26 +description: Как быстро распознавать изображения с помощью Python. Изучите конвейер + распознавания изображений, пакетную обработку и автоматизацию распознавания изображений + с использованием ИИ. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: ru +og_description: Как быстро распознавать изображения с помощью Python. Это руководство + проходит через конвейер распознавания изображений, пакетную обработку и автоматизацию + с использованием ИИ. +og_title: Как распознавать изображения — автоматизировать конвейер распознавания изображений +tags: +- image-processing +- python +- ai +title: Как распознавать изображения — автоматизировать конвейер распознавания изображений +url: /ru/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как распознавать изображения – автоматизация конвейера распознавания изображений + +Когда‑нибудь задавались вопросом **как распознавать изображения** без написания тысячи строк кода? Вы не одиноки — многие разработчики сталкиваются с тем же самым, когда им впервые нужно обработать десятки или сотни фотографий. Хорошая новость? С несколькими простыми шагами вы можете создать полноценный конвейер распознавания изображений, который будет пакетировать, выполнять и очищать всё автоматически. + +В этом руководстве мы пройдем через полностью готовый к запуску пример, показывающий **как пакетировать изображения**, передавать каждое в AI‑движок, пост‑обрабатывать результаты и, наконец, освобождать ресурсы. К концу вы получите автономный скрипт, который можно добавить в любой проект, будь то фототеггер, система контроля качества или генератор исследовательского набора данных. + +## Что вы узнаете + +- **Как распознавать изображения** с помощью имитационного AI‑движка (паттерн идентичен реальным сервисам вроде TensorFlow, PyTorch или облачным API). +- Как построить **конвейер распознавания изображений**, эффективно работающий с пакетами. +- Лучший способ **автоматизировать распознавание изображений**, чтобы не писать ручные циклы по файлам каждый раз. +- Советы по масштабированию конвейера и безопасному освобождению ресурсов. + +> **Требования:** Python 3.8+, базовое знакомство с функциями и циклами, а также несколько файлов изображений (или их путей), которые вы хотите обработать. Для ядра примера внешние библиотеки не требуются, но мы укажем, где можно подключить реальные AI‑SDK. + +![Диаграмма того, как распознавать изображения в конвейере пакетной обработки](pipeline.png "Диаграмма распознавания изображений") + +## Шаг 1: Пакетировать изображения – Как эффективно пакетировать изображения + +Прежде чем AI начнёт выполнять тяжёлую работу, вам нужна коллекция изображений для подачи в него. Представьте это как список покупок; позже движок будет поочерёдно брать каждый пункт из списка. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Почему пакетировать?** +Пакетирование уменьшает количество шаблонного кода, который вам приходится писать, и делает тривиальным добавление параллелизма позже. Если когда‑нибудь понадобится обработать 10 000 фотографий, вам достаточно будет изменить источник `image_batch` — остальная часть конвейера останется без изменений. + +## Шаг 2: Запустить конвейер распознавания изображений (Распознавание изображений с помощью ИИ) + +Теперь мы подключаем пакет к реальному распознавателю. В реальном сценарии вы могли бы вызвать `torchvision.models` или облачную точку доступа; здесь мы имитируем поведение, чтобы руководство оставалось автономным. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Explanation:** +- `engine.recognize_image` — сердце **конвейера распознавания изображений**; это может быть вызов модели глубокого обучения или REST‑API. +- `postprocessor.run` демонстрирует **автоматизацию распознавания изображений**, нормализуя сырые предсказания в чистый словарь, который можно сохранять или передавать дальше. +- Мы собираем каждый словарь `corrected` в `recognized_results`, чтобы последующие шаги (например, вставка в базу данных) были простыми. + +## Шаг 3: Пост‑обработка и хранение – Автоматизация результатов распознавания изображений + +После того как у вас появился аккуратный список предсказаний, обычно хочется сохранить их. В примере ниже записывается CSV‑файл; при желании замените его на базу данных или очередь сообщений. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Почему CSV?** +CSV универсально читаем — его открывают Excel, pandas и даже простые текстовые редакторы. Если позже понадобится **автоматизировать распознавание изображений** в масштабе, замените блок записи на массовую вставку в ваш озеро данных. + +## Шаг 4: Очистка – Безопасное освобождение ресурсов ИИ + +Многие AI‑SDK выделяют память GPU или создают рабочие потоки. Забвение об их освобождении может привести к утечкам памяти и неприятным сбоям. Хотя наши имитационные объекты этого не требуют, мы покажем правильный шаблон. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +Запуск скрипта выводит дружелюбное подтверждение, информируя, что конвейер завершён корректно. + +## Полный рабочий скрипт + +Объединив всё вместе, получаем полностью готовую к копированию и вставке программу: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Ожидаемый вывод + +При запуске скрипта (при условии, что три указанных пути существуют) вы увидите примерно следующее: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +А сгенерированный `recognition_results.csv` будет содержать: + +| изображение | метка | уверенность | +|----------------------|-------|-------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Заключение + +Теперь у вас есть надёжный сквозной пример **как распознавать изображения** на Python, включающий **конвейер распознавания изображений**, работу с пакетами и автоматизированную пост‑обработку. Паттерн масштабируется: замените имитационные классы на реальную модель, подайте более крупный `image_batch`, и вы получите готовое к продакшну решение. + +Хотите пойти дальше? Попробуйте следующие шаги: + +- Замените `MockEngine` на модель TensorFlow или PyTorch для реальных предсказаний. +- Параллелизуйте цикл с помощью `concurrent.futures.ThreadPoolExecutor` для ускорения больших пакетов. +- Подключите запись CSV к облачному хранилищу, чтобы **автоматизировать распознавание изображений** на распределённых воркерах. + +Экспериментируйте, ломайте, а затем исправляйте — так вы действительно освоите конвейеры распознавания изображений. Если столкнётесь с проблемами или у вас есть идеи по улучшению, оставляйте комментарий ниже. Счастливого кодинга! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/russian/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..87beb7325 --- /dev/null +++ b/ocr/russian/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-26 +description: Быстро маскируйте номера кредитных карт с помощью постобработки OCR AsposeAI. + Узнайте о соблюдении требований PCI, маскировании с помощью регулярных выражений + и очистке данных в пошаговом руководстве. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: ru +og_description: Маскируйте номера кредитных карт в результатах OCR с помощью AsposeAI. + В этом руководстве рассматриваются соответствие требованиям PCI, маскирование с + помощью регулярных выражений и очистка данных. +og_title: Маскирование номеров кредитных карт – Полное руководство по постобработке + OCR на Python +tags: +- OCR +- Python +- security +title: Маскирование номеров кредитных карт в выводе OCR – Полное руководство по Python +url: /ru/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Маскирование номеров кредитных карт – Полное руководство по Python + +Когда‑нибудь вам нужно было **маскировать номера кредитных карт** в тексте, полученном напрямую от OCR‑движка? Вы не одиноки. В регулируемых отраслях раскрытие полного PAN (Primary Account Number) может привести к проблемам с аудиторами по PCI‑compliance. Хорошая новость? С помощью нескольких строк кода на Python и post‑processing‑hook от AsposeAI вы можете автоматически скрыть средние восемь цифр и оставаться в безопасности. + +В этом руководстве мы пройдем реальный сценарий: запуск OCR на изображении чека, а затем применение пользовательской функции **OCR post‑processing**, которая очищает любые PCI‑данные. К концу вы получите переиспользуемый фрагмент, который можно вставить в любой workflow AsposeAI, а также несколько практических советов по обработке граничных случаев и масштабированию решения. + +## Что вы узнаете + +- Как зарегистрировать пользовательский post‑processor в **AsposeAI**. +- Почему подход **regular expression masking** быстрый и надёжный. +- Основы **PCI compliance**, связанные с очисткой данных. +- Способы расширения шаблона для нескольких форматов карт или международных номеров. +- Ожидаемый вывод и как проверить, что маскирование сработало. + +> **Prerequisites** – Вы должны иметь рабочую среду Python 3, установленный пакет Aspose.AI for OCR (`pip install aspose-ocr`) и пример изображения (например, `receipt.png`), содержащий номер кредитной карты. Другие внешние сервисы не требуются. + +--- + +## Шаг 1: Определите post‑processor, который маскирует номера кредитных карт + +Сердце решения находится в небольшой функции, которая получает результат OCR, запускает **regular expression masking**‑процедуру и возвращает очищенный текст. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Почему это работает:** +- Регулярное выражение `(\d{4})\d{8}(\d{4})` точно совпадает с 16 последовательными цифрами, типичным форматом для Visa, MasterCard и многих других. +- Сохраняя первые и последние четыре цифры (`\1` и `\2`), мы оставляем достаточно информации для отладки, одновременно соблюдая правила **PCI compliance**, запрещающие хранить полный PAN. +- Подстановка `\1****\2` скрывает чувствительные средние восемь цифр, превращая `1234567812345678` в `1234****5678`. + +> **Pro tip:** Если нужно поддерживать 15‑значные номера American Express, добавьте второй шаблон, например `r'(\d{4})\d{6}(\d{5})'`, и выполните оба замещения последовательно. + +--- + +## Шаг 2: Инициализируйте движок AsposeAI + +Прежде чем привязать наш post‑processor, нам нужен экземпляр OCR‑движка. AsposeAI включает модель OCR и простой API для пользовательской обработки. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Почему инициализировать здесь?** +Создание объекта `AsposeAI` один раз и его повторное использование для нескольких изображений уменьшает нагрузку. Движок также кэширует языковые модели, что ускоряет последующие вызовы — удобно при сканировании пакетов чеков. + +--- + +## Шаг 3: Зарегистрируйте пользовательскую функцию маскирования + +AsposeAI предоставляет метод `set_post_processor`, позволяющий подключить любой вызываемый объект. Мы передаём нашу функцию `mask_pci` вместе с необязательным словарём настроек (пока пустым). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**Что происходит за кулисами?** +Когда позже вызывается `run_postprocessor`, AsposeAI передаёт необработанный результат OCR функции `mask_pci`. Функция получает лёгкий объект (`data`), содержащий распознанный текст, и возвращает новую строку. Такой дизайн оставляет ядро OCR нетронутым, позволяя централизованно применять политики **data sanitization**. + +--- + +## Шаг 4: Запустите OCR на изображении чека + +Теперь, когда движок знает, как очистить вывод, мы передаём ему изображение. Для целей этого руководства предполагается, что у вас уже есть объект `engine`, сконфигурированный с нужными языком и настройками разрешения. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Tip:** Если у вас нет предварительно сконфигурированного объекта, его можно создать так: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +Вызов `recognize_image` возвращает объект, чей атрибут `text` содержит необработанную, немаскированную строку. + +--- + +## Шаг 5: Примените зарегистрированный post‑processor + +Получив необработанные OCR‑данные, передаём их экземпляру AI. Движок автоматически запускает функцию `mask_pci`, которую мы зарегистрировали ранее. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Почему использовать `run_postprocessor`, а не вызывать функцию вручную?** +Это сохраняет согласованность рабочего процесса, особенно когда задействовано несколько post‑processor‑ов (например, проверка орфографии, определение языка). AsposeAI ставит их в очередь в порядке регистрации, гарантируя детерминированный вывод. + +--- + +## Шаг 6: Проверьте очищенный вывод + +Наконец, выведем очищенный текст и убедимся, что все номера кредитных карт правильно замаскированы. + +```python +print(final_result.text) +``` + +**Ожидаемый вывод** (отрывок): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Если в чеке не было номера карты, текст останется без изменений — нечего маскировать, нечего беспокоиться. + +--- + +## Обработка граничных случаев и распространённых вариаций + +### Несколько номеров карт в одном документе +Если чек содержит более одного PAN (например, карта лояльности плюс платёжная карта), регулярное выражение работает глобально, автоматически маскируя все совпадения. Дополнительный код не требуется. + +### Нестандартное форматирование +Иногда OCR вставляет пробелы или дефисы (`1234 5678 1234 5678` или `1234-5678-1234-5678`). Расширьте шаблон, чтобы игнорировать эти символы: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +Добавление `[ -]?` допускает опциональные пробелы или дефисы между блоками цифр. + +### Международные карты +Для 19‑значных PAN, используемых в некоторых регионах, можно расширить шаблон: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Просто помните, что **PCI compliance** всё равно требует маскировать средние цифры, независимо от длины. + +### Логирование замаскированных значений (опционально) +Если нужны аудиторские следы, передайте флаг через `custom_settings` и скорректируйте функцию: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Затем зарегистрируйте её так: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Полный рабочий пример (готовый к копированию) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Запуск этого скрипта на чеке, содержащем `4111111111111111`, даст: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +Это весь конвейер — от необработанного OCR до **data sanitization** — упакованный в несколько чистых строк Python. + +--- + +## Заключение + +Мы только что показали, как **маскировать номера кредитных карт** в результатах OCR, используя post‑processing‑hook AsposeAI, лаконичную регулярную маску и несколько рекомендаций по **PCI compliance**. Решение полностью автономно, работает с любым изображением, которое способен прочитать OCR‑движок, и может быть расширено для более сложных форматов карт или требований к логированию. + +Готовы к следующему шагу? Попробуйте связать эту маску с процедурой **вставки в базу данных**, сохраняющей только последние четыре цифры для справки, или интегрировать **пакетный процессор**, сканирующий всю папку чеков за ночь. Вы также можете исследовать другие задачи **OCR post‑processing**, такие как стандартизация адресов или определение языка — каждая следует той же схеме, что и здесь. + +Есть вопросы о граничных случаях, производительности или о том, как адаптировать код под другую OCR‑библиотеку? Оставьте комментарий ниже, и давайте продолжим обсуждение. Приятного кодинга и будьте в безопасности! + + + +![Diagram illustrating how mask credit card numbers works in an OCR pipeline](https://example.com/images/ocr-mask-flow.png "Diagram of OCR post‑processing masking flow") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/russian/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..89d88da44 --- /dev/null +++ b/ocr/russian/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-04-26 +description: Узнайте, как измерять время вывода в Python, загрузить модель GGUF с + Hugging Face и оптимизировать использование GPU для более быстрых результатов. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: ru +og_description: Измерьте время инференса в Python, загрузив модель GGUF с Hugging + Face и настроив слои GPU для оптимальной производительности. +og_title: Измерение времени инференса – загрузка модели GGUF и оптимизация GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Измерение времени инференса – загрузка модели GGUF и оптимизация GPU +url: /ru/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Измерение времени вывода – загрузка модели GGUF и оптимизация GPU + +Когда‑нибудь вам нужно было **измерить время вывода** для большой языковой модели, но вы не знали, с чего начать? Вы не одиноки — многие разработчики сталкиваются с тем же, когда впервые скачивают файл GGUF с Hugging Face и пытаются запустить его на смешанной конфигурации CPU/GPU. + +В этом руководстве мы пройдемся по **загрузке модели GGUF**, её настройке для Hugging Face и **измерению времени вывода** с помощью чистого фрагмента кода на Python. По пути мы также покажем, как **оптимизировать использование GPU при выводе**, чтобы ваши запуски были максимально быстрыми. Без лишних слов, только практическое решение «от начала до конца», которое вы можете скопировать и вставить уже сегодня. + +## Что вы узнаете + +- Как **настроить модель HuggingFace** с помощью `AsposeAIModelConfig`. +- Точные шаги для **загрузки модели GGUF** (квантование `fp16`) из хаба Hugging Face. +- Переиспользуемый шаблон для **измерения времени Python‑кода** вокруг вызова вывода. +- Советы по **оптимизации вывода на GPU** путём изменения `gpu_layers`. +- Ожидаемый вывод и как проверить, что измерения имеют смысл. + +### Предварительные требования + +| Требование | Почему это важно | +|------------|------------------| +| Python 3.9+ | Современный синтаксис и подсказки типов. | +| `asposeai` package (or the equivalent SDK) | Предоставляет `AsposeAI` и `AsposeAIModelConfig`. | +| Access to the Hugging Face repo `bartowski/Qwen2.5-3B-Instruct-GGUF` | Модель GGUF, которую мы будем загружать. | +| A GPU with at least 8 GB VRAM (optional but recommended) | Позволяет выполнить шаг **optimize inference GPU**. | + +Если вы ещё не установили SDK, выполните: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![measure inference time diagram](https://example.com/measure-inference-time.png){alt="measure inference time diagram"} + +## Шаг 1: Загрузка модели GGUF – Настройка модели HuggingFace + +Первое, что вам нужно — это правильный объект конфигурации, который сообщает Aspose AI, где взять модель и как её обрабатывать. Здесь мы **загружаем модель GGUF** и **настраиваем параметры huggingface model**. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Почему это важно:** +- `hugging_face_repo_id` указывает на точный файл GGUF в хабе. +- `fp16` уменьшает пропускную способность памяти, сохраняя большую часть точности модели. +- `gpu_layers` — это параметр, который вы регулируете, когда хотите **оптимизировать вывод на GPU**; больше слоёв на GPU обычно означают меньшую задержку, при условии достаточного объёма VRAM. + +## Шаг 2: Создание экземпляра Aspose AI + +Теперь, когда модель описана, мы создаём объект `AsposeAI`. Этот шаг прост, но именно здесь SDK скачивает файл GGUF (если он не закеширован) и подготавливает среду выполнения. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Pro tip:** Первый запуск займёт несколько секунд дольше, потому что модель скачивается и компилируется для GPU. Последующие запуски будут молниеносными. + +## Шаг 3: Запуск вывода и **измерение времени вывода** + +Вот сердце руководства: обёртывание вызова вывода в `time.time()` для **измерения времени вывода**. Мы также подаём небольшой результат OCR, чтобы пример был самодостаточным. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Что вы должны увидеть:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Если полученное значение кажется высоким, скорее всего большинство слоёв работает на CPU. Переходим к следующему шагу. + +## Шаг 4: **Оптимизировать вывод на GPU** – Настройка `gpu_layers` + +Иногда значение по умолчанию `gpu_layers=40` либо слишком агрессивно (вызывает OOM), либо слишком консервативно (оставляет производительность неиспользованной). Ниже представлена быстрая петля, которую можно использовать для поиска оптимального баланса: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Почему это работает:** +- Каждый вызов перестраивает среду выполнения с другим распределением GPU, позволяя мгновенно увидеть компромисс задержки. +- Петля также демонстрирует **time python code** в переиспользуемом виде, который можно адаптировать для других тестов производительности. + +Типичный вывод на RTX 3080 с 16 GB VRAM может выглядеть так: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +Исходя из этого, вы бы выбрали `gpu_layers=40` как оптимальное значение для данного оборудования. + +## Полный рабочий пример + +Объединив всё вместе, получаем единый скрипт, который можно сохранить в файл (`measure_inference.py`) и запустить: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Запустите его так: + +```bash +python measure_inference.py +``` + +Вы должны увидеть субсекундную задержку на приличном GPU, подтверждая, что вы успешно **измерили время вывода** и **оптимизировали вывод на GPU**. + +--- + +## Часто задаваемые вопросы (FAQ) + +**Q: Работает ли это с другими форматами квантования?** +A: Абсолютно. Замените `hugging_face_quantization="int8"` (или `q4_0` и т.д.) в конфигурации и повторно запустите бенчмарк. Ожидайте компромисс: меньшее потребление памяти против небольшого снижения точности. + +**Q: Что делать, если нет GPU?** +A: Установите `gpu_layers=0`. Код полностью переключится на CPU, и вы всё равно сможете **измерить время вывода** — просто ожидайте более высокие цифры. + +**Q: Можно ли измерять только прямой проход модели, исключив пост‑обработку?** +A: Да. Вызовите `ai_engine.run_model(...)` (или аналогичный метод) напрямую и оберните этот вызов в `time.time()`. Шаблон для **time python code** остаётся тем же. + +## Заключение + +Теперь у вас есть полное решение «копировать‑и‑вставить» для **измерения времени вывода** GGUF‑модели, **загрузки gguf модели** с Hugging Face и тонкой настройки параметров **optimize inference GPU**. Регулируя `gpu_layers` и экспериментируя с квантованием, вы сможете выжать каждый миллисекунд производительности. + +Дальнейшие шаги могут включать: + +- Интеграцию этой логики измерения в CI‑конвейер для обнаружения регрессий. +- Исследование пакетного вывода для дальнейшего повышения пропускной способности. +- Комбинацию модели с реальным OCR‑конвейером вместо использованного здесь фиктивного текста. + +Счастливого кодинга, и пусть ваши показатели задержки всегда остаются низкими! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/russian/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..a3c63e384 --- /dev/null +++ b/ocr/russian/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-26 +description: распознавать рукописный текст с помощью OCR‑движка Python. Узнайте, как + извлекать текст из изображения, включать режим рукописного ввода и быстро читать + рукописные заметки. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: ru +og_description: распознавать рукописный текст с помощью Python. Этот учебник показывает, + как извлекать текст из изображения, включать режим рукописного ввода и читать рукописные + заметки с помощью простого OCR‑движка. +og_title: Распознавание рукописного текста в Python – Полное руководство по OCR +tags: +- OCR +- Python +- Handwriting Recognition +title: Распознавание рукописного текста в Python – учебник по OCR‑движку +url: /ru/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# распознавание рукописного текста в Python – OCR Engine Tutorial + +Когда‑то вам нужно было **распознать рукописный текст**, но вы застряли на вопросе «с чего начать?». Вы не одиноки. Будь то оцифровка заметок с совещаний или извлечение данных из отсканированной формы, получение надёжного результата OCR иногда кажется охотой за единорогом. + +Хорошие новости: всего несколькими строками Python вы можете **извлечь текст из изображения**, **включить режим рукописного ввода** и наконец **читать рукописные заметки** без поиска obscure‑библиотек. В этом руководстве мы пройдём весь процесс — от настройки в стиле **create OCR engine python** до вывода результата на экран. + +## Что вы узнаете + +- Как **создать OCR engine python**‑экземпляр с помощью пакета `ocr`. +- Какой параметр языка предоставляет встроенную поддержку рукописного ввода. +- Как точно вызвать **turn on handwritten mode**, чтобы движок понял, что вы работаете с курсивом. +- Как подать изображение заметки и **распознать рукописный текст**. +- Советы по работе с разными форматами изображений, устранению типичных проблем и расширению решения. + +Без лишних слов, без «см. документацию»‑тупиков — только полностью готовый к запуску скрипт, который можно скопировать‑вставить и протестировать уже сегодня. + +## Предварительные требования + +Прежде чем погрузиться в детали, убедитесь, что у вас есть: + +1. Установлен Python 3.8+ (код использует f‑строки). +2. Гипотетическая библиотека `ocr` (`pip install ocr‑engine` – замените на реальное название пакета, которым вы пользуетесь). +3. Чёткий файл изображения рукописной заметки (поддерживаются JPEG, PNG или TIFF). +4. Небольшая доля любопытства — всё остальное описано ниже. + +> **Pro tip:** Если ваше изображение шумное, выполните быструю предобработку с помощью Pillow (например, `Image.open(...).convert('L')`) перед передачей в OCR‑движок. Это часто повышает точность. + +## Как распознать рукописный текст с помощью Python + +Ниже представлен полный скрипт, который **создаёт OCR engine python**‑объекты, настраивает их для рукописного ввода и выводит извлечённую строку. Сохраните его как `handwriting_ocr.py` и запустите из терминала. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Ожидаемый вывод + +При успешном выполнении скрипта вы увидите примерно следующее: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Если движок OCR не обнаружит символов, поле `text` будет пустой строкой. В этом случае проверьте качество изображения или попробуйте сканировать с более высоким разрешением. + +## Пошаговое объяснение + +### Шаг 1 – **create OCR engine python**‑экземпляр + +Класс `OcrEngine` — точка входа. Представьте его как чистый блокнот — ничего не происходит, пока вы не укажете, какой язык ожидать и работаете ли вы с рукописным вводом. + +### Шаг 2 – Выберите язык, поддерживающий рукописный ввод + +`ocr.Language.EXTENDED_LATIN` — это не просто «английский». Он включает набор латинских скриптов и, что важнее, модели, обученные на образцах курсивного письма. Пропуск этого шага часто приводит к «мусорному» выводу, потому что движок по умолчанию использует модель для печатного текста. + +### Шаг 3 – **turn on handwritten mode** + +Вызов `enable_handwritten_mode(True)` переключает внутренний флаг. Движок тогда переходит к нейронной сети, настроенной под нерегулярные интервалы и переменную толщину штрихов, характерные для реальных заметок. Забыть эту строку — частая ошибка; в этом случае движок будет воспринимать ваши каракули как шум. + +### Шаг 4 – Передайте изображение и **распознайте рукописный текст** + +`recognize_image` делает всю тяжёлую работу: предобрабатывает битмап, прогоняет его через модель рукописного ввода и возвращает объект с атрибутом `text`. При необходимости можно также посмотреть `handwritten_result.confidence` для оценки качества. + +### Шаг 5 – Выведите результат и **читайте рукописные заметки** + +`print(handwritten_result.text)` — самый простой способ убедиться, что вы успешно **извлекли текст из изображения**. В продакшене, скорее всего, строку сохранят в базе данных или передадут в другой сервис. + +## Обработка граничных случаев и типичных вариаций + +| Ситуация | Что делать | +|-----------|------------| +| **Изображение повернуто** | Используйте Pillow для вращения (`Image.rotate(angle)`) перед вызовом `recognize_image`. | +| **Низкий контраст** | Переведите в градации серого и примените адаптивное пороговое преобразование (`Image.point(lambda p: p > 128 and 255)`). | +| **Несколько страниц** | Пройдитесь в цикле по списку путей к файлам и конкатенируйте результаты. | +| **Нелатинские скрипты** | Замените `EXTENDED_LATIN` на `ocr.Language.CHINESE` (или другой нужный) и оставьте `enable_handwritten_mode(True)`. | +| **Проблемы с производительностью** | Переиспользуйте один и тот же экземпляр `ocr_engine` для множества изображений; инициализация каждый раз добавляет накладные расходы. | + +### Pro tip по использованию памяти + +Если вы обрабатываете сотни заметок в пакете, вызовите `ocr_engine.dispose()` после завершения. Это освободит нативные ресурсы, которые может удерживать Python‑обёртка. + +## Краткий визуальный обзор + +![recognize handwritten text example](https://example.com/handwritten-note.png "recognize handwritten text example") + +*На изображении показана типичная рукописная заметка, которую наш скрипт может превратить в обычный текст.* + +## Полный рабочий пример (одностраничный скрипт) + +Для тех, кто любит простоту копировать‑вставить, вот весь код без пояснительных комментариев: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Запустите его так: + +```bash +python handwriting_ocr.py +``` + +Теперь вы должны увидеть вывод **recognize handwritten text** в консоли. + +## Заключение + +Мы только что прошли всё, что нужно, чтобы **распознать рукописный текст** в Python — от свежего вызова **create OCR engine python**, выбора правильного языка, **turn on handwritten mode**, до **извлечения текста из изображения** и **чтения рукописных заметок**. + +В одном самодостаточном скрипте вы можете превратить размытое фото заметки с совещания в чистый, индексируемый текст. Далее можно передать результат в конвейер обработки естественного языка, сохранить в поисковом индексе или даже использовать в сервисе транскрипции для генерации озвучки. + +### Куда двигаться дальше? + +- **Пакетная обработка:** Оберните скрипт в цикл для обработки папки сканов. +- **Фильтрация по уверенности:** Используйте `result.confidence` для отбрасывания низкокачественных распознаваний. +- **Альтернативные библиотеки:** Если `ocr` не полностью подходит, изучите `pytesseract` с параметром `--psm 13` для режима рукописного ввода. +- **Интеграция UI:** Скомбинируйте с Flask или FastAPI, чтобы предложить веб‑сервис загрузки. + +Есть вопросы о конкретном формате изображения или нужна помощь в настройке модели? Оставляйте комментарий ниже, и счастливого кодинга! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/spanish/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..ef191ce33 --- /dev/null +++ b/ocr/spanish/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-04-26 +description: Aprende cómo descargar el modelo HuggingFace en Python y extraer texto + de una imagen en Python mientras mejoras la precisión del OCR en Python con Aspose + OCR Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: es +og_description: Descarga el modelo HuggingFace para Python y potencia tu pipeline + OCR. Sigue esta guía para extraer texto de una imagen con Python y mejorar la precisión + del OCR con Python. +og_title: Descargar modelo HuggingFace Python – Tutorial completo de mejora de OCR +tags: +- OCR +- HuggingFace +- Python +- AI +title: descargar modelo huggingface python – Guía paso a paso para potenciar OCR +url: /es/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# descargar modelo huggingface python – Tutorial completo de mejora OCR + +¿Alguna vez intentaste **download HuggingFace model python** y te sentiste un poco perdido? No eres el único. En muchos proyectos el mayor cuello de botella es obtener un buen modelo en tu máquina y luego hacer que los resultados de OCR sean realmente útiles. + +En esta guía recorreremos un ejemplo práctico que te muestra exactamente cómo **download HuggingFace model python**, extraer texto de una imagen con **extract text from image python**, y luego **improve OCR accuracy python** usando el post‑procesador de IA de Aspose. Al final tendrás un script listo para ejecutar que convierte una imagen de factura ruidosa en texto limpio y legible—sin magia, solo pasos claros. + +## Lo que necesitarás + +- Python 3.9+ (el código también funciona en 3.11) +- Una conexión a internet para la descarga única del modelo +- El paquete `asposeocrcloud` (`pip install asposeocrcloud`) +- Una imagen de ejemplo (p.ej., `sample_invoice.png`) ubicada en una carpeta que controles + +Eso es todo—sin frameworks pesados, sin controladores específicos de GPU a menos que quieras acelerar las cosas. + +Ahora, sumerjámonos en la implementación real. + +![flujo de trabajo de descarga de modelo huggingface python](image.png "diagrama de descarga de modelo huggingface python") + +## Paso 1: Configura el motor OCR y elige un idioma +*(Este es el punto donde empezamos a **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Por qué esto es importante:** +El motor OCR es la primera línea de defensa; escoger el paquete de idioma correcto reduce los errores de reconocimiento de caracteres de inmediato, lo cual es una parte fundamental de **improve OCR accuracy python**. + +## Paso 2: Configura el modelo AsposeAI – Descargando desde HuggingFace +*(Aquí realmente **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**¿Qué está sucediendo bajo el capó?** +Cuando `allow_auto_download` es verdadero, el SDK se conecta a HuggingFace, descarga el modelo `Qwen2.5‑3B‑Instruct‑GGUF` y lo almacena en la carpeta que especificaste. Esto es el núcleo de **download huggingface model python**—el SDK se encarga del trabajo pesado, por lo que no tienes que escribir ningún comando `git clone` o `wget`. +*Consejo profesional:* Mantén `directory_model_path` en un SSD para tiempos de carga más rápidos; el modelo tiene ~3 GB incluso en forma `int8`. + +## Paso 3: Adjunta el motor de IA al motor OCR +*(Enlazando las dos piezas para que podamos **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**¿Por qué enlazarlos?** +El motor OCR nos brinda texto crudo, que puede contener errores ortográficos, líneas rotas o puntuación incorrecta. El motor de IA actúa como un editor inteligente, limpiando esos problemas—exactamente lo que necesitas para **improve OCR accuracy python**. + +## Paso 4: Ejecuta OCR en tu imagen +*(El momento en que finalmente **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` ahora contiene un atributo `text` con los caracteres crudos que el motor vio. En la práctica notarás algunos fallos—quizá “Invoice” se convierta en “Inv0ice” o haya un salto de línea en medio de una frase. + +## Paso 5: Limpia con el post‑procesador de IA +*(Este paso directamente **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +El modelo de IA reescribe el texto, aplicando correcciones conscientes del idioma. Como usamos un modelo afinado por instrucciones de HuggingFace, la salida suele ser fluida y lista para el procesamiento posterior. + +## Paso 6: Muestra el antes y después +*(Una rápida verificación para ver qué tan bien **extract text from image python** y **improve OCR accuracy python**.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Salida esperada + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Observa cómo la IA corrigió “Inv0ice” a “Invoice” y suavizó los saltos de línea errantes. Ese es el resultado tangible de **improve OCR accuracy python** usando un modelo HuggingFace descargado. + +## Preguntas frecuentes (FAQ) + +### ¿Necesito una GPU para ejecutar el modelo? +No. La configuración `gpu_layers=20` indica al SDK que use hasta 20 capas de GPU si hay una GPU compatible; de lo contrario recurre a la CPU. En un portátil moderno la ruta CPU aún procesa unos cientos de tokens por segundo—perfecto para el análisis ocasional de facturas. + +### ¿Qué pasa si el modelo no se descarga? +Asegúrate de que tu entorno pueda acceder a `https://huggingface.co`. Si estás detrás de un proxy corporativo, configura las variables de entorno `HTTP_PROXY` y `HTTPS_PROXY`. El SDK volverá a intentar automáticamente, pero también puedes ejecutar manualmente `git lfs pull` del repositorio en `directory_model_path`. + +### ¿Puedo cambiar el modelo por uno más pequeño? +Claro. Simplemente reemplaza `hugging_face_repo_id` por otro repositorio (p.ej., `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) y ajusta `hugging_face_quantization` en consecuencia. Los modelos más pequeños se descargan más rápido y consumen menos RAM, aunque podrías perder un poco de calidad en la corrección. + +### ¿Cómo me ayuda esto a **extract text from image python** en otros dominios? +La misma canalización funciona para recibos, pasaportes o notas manuscritas. El único cambio es el paquete de idioma (`ocr.Language.FRENCH`, etc.) y posiblemente un modelo afinado específicamente para el dominio de HuggingFace. + +## Bonus: Automatizando múltiples archivos + +Si tienes una carpeta llena de imágenes, envuelve la llamada OCR en un bucle simple: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +Esta pequeña adición te permite **download huggingface model python** una vez, y luego procesar por lotes docenas de archivos—ideal para escalar tu canalización de automatización de documentos. + +## Conclusión + +Acabamos de recorrer un ejemplo completo, de extremo a extremo, que te muestra cómo **download HuggingFace model python**, **extract text from image python**, y **improve OCR accuracy python** usando OCR Cloud de Aspose y un post‑procesador de IA. El script está listo para ejecutarse, los conceptos están explicados, y has visto la salida antes y después, así sabes que funciona. + +¿Qué sigue? Prueba cambiar a un modelo HuggingFace diferente, experimenta con otros paquetes de idioma, o alimenta el texto limpio a una canalización NLP posterior (p.ej., extracción de entidades para líneas de factura). El cielo es el límite, y la base que acabas de construir es sólida. + +¿Tienes preguntas o una imagen complicada que aún confunde al OCR? Deja un comentario abajo, y solucionemos juntos. ¡Feliz codificación! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/spanish/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..bc030392a --- /dev/null +++ b/ocr/spanish/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-04-26 +description: Descarga el modelo OCR rápidamente usando Aspose OCR Python. Aprende + cómo establecer el directorio del modelo, configurar la ruta del modelo y cómo descargar + el modelo en unas pocas líneas. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: es +og_description: Descarga el modelo OCR en segundos con Aspose OCR Python. Esta guía + muestra cómo establecer el directorio del modelo, configurar la ruta del modelo + y cómo descargar el modelo de forma segura. +og_title: descargar modelo OCR – Tutorial completo de Aspose OCR en Python +tags: +- OCR +- Python +- Aspose +title: Descargar modelo OCR con Aspose OCR Python – Guía paso a paso +url: /es/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# descargar modelo ocr – Tutorial completo de Aspose OCR Python + +¿Alguna vez te has preguntado cómo **download ocr model** usando Aspose OCR en Python sin tener que buscar en interminables documentos? No eres el único. Muchos desarrolladores se topan con un obstáculo cuando el modelo no está presente localmente y el SDK lanza un error críptico. ¿La buena noticia? La solución son unas cuantas líneas, y tendrás el modelo listo para usar en minutos. + +En este tutorial repasaremos todo lo que necesitas saber: desde importar las clases correctas, hasta **set model directory**, pasando por **how to download model**, y finalmente verificando la ruta. Al final podrás ejecutar OCR en cualquier imagen con una sola llamada a función, y comprenderás las opciones de **configure model path** que mantienen tu proyecto ordenado. Sin rodeos, solo un ejemplo práctico y ejecutable para usuarios de **aspose ocr python**. + +## Lo que aprenderás + +- Cómo importar correctamente las clases de Aspose OCR Cloud. +- Los pasos exactos para **download ocr model** automáticamente. +- Formas de **set model directory** y **configure model path** para compilaciones reproducibles. +- Cómo verificar que el modelo está inicializado y dónde se encuentra en disco. +- Trampas comunes (permisos, carpetas faltantes) y soluciones rápidas. + +### Requisitos previos + +- Python 3.8+ instalado en tu máquina. +- Paquete `asposeocrcloud` (`pip install asposeocrcloud`). +- Permiso de escritura en una carpeta donde quieras almacenar el modelo (p. ej., `C:\models` o `~/ocr_models`). + +--- + +## Paso 1: Importar clases de Aspose OCR Cloud + +Lo primero que necesitas es la declaración de importación correcta. Esto trae las clases que gestionan la configuración del modelo y las operaciones de OCR. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Por qué es importante:* `AsposeAI` es el motor que ejecutará OCR, mientras que `AsposeAIModelConfig` le indica al motor **dónde** buscar el modelo y **si** debe descargarlo automáticamente. Omitir este paso o importar el módulo incorrecto provocará un `ModuleNotFoundError` antes de llegar a la parte de descarga. + +--- + +## Paso 2: Definir la configuración del modelo (Set Model Directory & Configure Model Path) + +Ahora le decimos a Aspose dónde guardar los archivos del modelo. Aquí es donde **set model directory** y **configure model path** entran en juego. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Consejos y advertencias** + +- Las **rutas absolutas** evitan confusiones cuando el script se ejecuta desde un directorio de trabajo diferente. +- En Linux/macOS puedes usar `"/home/you/ocr_models"`; en Windows, antepone `r` para tratar las barras invertidas literalmente. +- Establecer `allow_auto_download="true"` es la clave para **how to download model** sin escribir código adicional. + +--- + +## Paso 3: Crear la instancia de AsposeAI usando la configuración + +Con la configuración lista, instancia el motor OCR. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Por qué es importante:* El objeto `ocr_ai` ahora contiene la configuración que acabamos de definir. Si el modelo no está presente, la siguiente llamada desencadenará la descarga automáticamente; este es el núcleo de **how to download model** de forma automática. + +--- + +## Paso 4: Activar la descarga del modelo (si es necesario) + +Antes de poder ejecutar OCR, debes asegurarte de que el modelo esté realmente en disco. El método `is_initialized()` verifica y fuerza la inicialización. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**¿Qué ocurre bajo el capó?** + +- La primera llamada a `is_initialized()` devuelve `False` porque la carpeta del modelo está vacía. +- El `print` informa al usuario que la descarga está a punto de comenzar. +- La segunda llamada obliga a Aspose a obtener el modelo del repositorio Hugging Face que especificaste antes. +- Una vez descargado, el método devuelve `True` en comprobaciones posteriores. + +**Caso extremo:** Si tu red bloquea Hugging Face, verás una excepción. En ese caso, descarga manualmente el zip del modelo, extráelo en `directory_model_path` y vuelve a ejecutar el script. + +--- + +## Paso 5: Informar la ruta local donde el modelo está disponible + +Después de que la descarga finalice, probablemente quieras saber dónde aterrizaron los archivos. Esto ayuda en depuración y al configurar pipelines de CI. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Una salida típica se ve así: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Ahora has **download ocr model** con éxito, establecido el directorio y confirmado la ruta. + +--- + +## Visión general visual + +A continuación se muestra un diagrama sencillo que ilustra el flujo desde la configuración hasta un modelo listo para usar. + +![download ocr model flow diagram showing configuration, automatic download, and local path](/images/download-ocr-model-flow.png) + +*El texto alternativo incluye la palabra clave principal para SEO.* + +--- + +## Variaciones comunes y cómo manejarlas + +### 1. Usar un repositorio de modelo diferente + +Si necesitas un modelo distinto a `openai/gpt2`, simplemente reemplaza el valor de `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Asegúrate de que el repositorio sea público o de que tengas el token necesario configurado en tu entorno. + +### 2. Desactivar la descarga automática + +A veces deseas controlar la descarga tú mismo (p. ej., en entornos aislados). Establece `allow_auto_download` a `"false"` y llama a un script de descarga personalizado antes de inicializar: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Cambiar el directorio del modelo en tiempo de ejecución + +Puedes reconfigurar la ruta sin recrear el objeto `AsposeAI`: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Consejos profesionales para uso en producción + +- **Cachear el modelo**: Mantén el directorio en una unidad de red compartida si varios servicios necesitan el mismo modelo. Así evitas descargas redundantes. +- **Fijar versiones**: El repositorio de Hugging Face puede actualizarse. Para bloquear una versión específica, añade `@v1.0.0` al ID del repo (`"openai/gpt2@v1.0.0"`). +- **Permisos**: Garantiza que el usuario que ejecuta el script tenga derechos de lectura/escritura en `directory_model_path`. En Linux, `chmod 755` suele ser suficiente. +- **Registro (logging)**: Sustituye los simples `print` por el módulo `logging` de Python para una mejor observabilidad en aplicaciones más grandes. + +--- + +## Ejemplo completo y listo para copiar‑pegar + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Salida esperada** (la primera ejecución descargará, las siguientes omitirán la descarga): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Ejecuta el script nuevamente; verás solo la línea de ruta porque el modelo ya está en caché. + +--- + +## Conclusión + +Acabamos de cubrir el proceso completo para **download ocr model** usando Aspose OCR Python, mostramos cómo **set model directory** y explicamos los matices de **configure model path**. Con solo unas pocas líneas de código puedes automatizar la descarga, evitar pasos manuales y mantener tu pipeline de OCR reproducible. + +A continuación, podrías explorar la llamada real de OCR (`ocr_ai.recognize_image(...)`) o probar con otro modelo de Hugging Face para mejorar la precisión. Sea cual sea el caso, la base que has construido aquí —configuración clara, descarga automática y verificación de ruta— hará que cualquier integración futura sea pan comido. + +¿Tienes preguntas sobre casos extremos, o quieres compartir cómo ajustaste el directorio del modelo para despliegues en la nube? ¡Deja un comentario abajo y feliz codificación! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/spanish/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..5ab5eb10c --- /dev/null +++ b/ocr/spanish/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-04-26 +description: Cómo post‑procesar resultados de OCR y extraer texto con coordenadas. + Aprende una solución paso a paso usando salida estructurada y corrección con IA. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: es +og_description: Cómo post‑procesar los resultados de OCR y extraer texto con coordenadas. + Sigue este tutorial completo para un flujo de trabajo fiable. +og_title: Cómo post‑procesar OCR – Guía completa +tags: +- OCR +- Python +- AI +- Text Extraction +title: Cómo post‑procesar OCR – Extraer texto con coordenadas en Python +url: /es/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo post‑procesar OCR – Extraer texto con coordenadas en Python + +¿Alguna vez necesitaste **post‑procesar OCR** resultados porque la salida cruda era ruidosa o desalineada? No eres el único. En muchos proyectos del mundo real—escaneo de facturas, digitalización de recibos, o incluso la mejora de experiencias de AR—el motor OCR te da palabras crudas, pero aún tienes que limpiarlas y mantener el seguimiento de dónde vive cada palabra en la página. Ahí es donde un modo de salida estructurada combinado con un post‑procesador impulsado por IA brilla. + +En este tutorial recorreremos una canalización completa y ejecutable en Python que **extrae texto con coordenadas** de una imagen, ejecuta un paso de corrección basado en IA y muestra cada palabra junto con su posición (x, y). Sin importaciones faltantes, sin atajos vagos de “ver la documentación”—solo una solución autónoma que puedes incorporar a tu proyecto hoy. + +> **Consejo profesional:** Si estás usando una biblioteca OCR diferente, busca un modo “structured” o “layout”; los conceptos siguen siendo los mismos. + +--- + +## Requisitos previos + +Antes de profundizar, asegúrate de tener: + +| Requisito | Por qué es importante | +|-------------|------------------------| +| Python 3.9+ | Sintaxis moderna y anotaciones de tipo | +| `ocr` library that supports `OutputMode.STRUCTURED` (e.g., a fictional `myocr`) | Biblioteca `ocr` que soporta `OutputMode.STRUCTURED` (p. ej., una ficticia `myocr`) | +| Needed for bounding‑box data | Necesario para datos de cajas delimitadoras | +| An AI post‑processing module (could be OpenAI, HuggingFace, or a custom model) | Un módulo de post‑procesamiento de IA (puede ser OpenAI, HuggingFace, o un modelo personalizado) | +| Improves accuracy after OCR | Mejora la precisión después del OCR | +| An image file (`input.png`) in your working directory | Un archivo de imagen (`input.png`) en tu directorio de trabajo | +| The source we’ll read | La fuente que leeremos | + +Si alguno de estos te suena desconocido, simplemente instala los paquetes de marcador con `pip install myocr ai‑postproc`. El código a continuación también incluye stubs de reserva para que puedas probar el flujo sin las bibliotecas reales. + +## Paso 1: Habilitar el modo de salida estructurada para el motor OCR + +Lo primero que hacemos es indicarle al motor OCR que nos dé más que solo texto plano. La salida estructurada devuelve cada palabra junto con su caja delimitadora y puntuación de confianza, lo cual es esencial para **extraer texto con coordenadas** más adelante. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Por qué es importante:* Sin el modo estructurado solo obtendrías una cadena larga, y perderías la información espacial que necesitas para superponer texto en imágenes o alimentar análisis de diseño posteriores. + +## Paso 2: Reconocer la imagen y capturar palabras, cajas y confianza + +Ahora alimentamos la imagen al motor. El resultado es un objeto que contiene una lista de objetos palabra, cada uno exponiendo `text`, `x`, `y`, `width`, `height` y `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Caso límite:* Si la imagen está vacía o no se puede leer, `structured_result.words` será una lista vacía. Es una buena práctica verificar eso y manejarlo de forma elegante. + +## Paso 3: Ejecutar post‑procesamiento basado en IA mientras se preservan las posiciones + +Incluso los mejores motores OCR cometen errores—piensa en “O” vs. “0” o diacríticos faltantes. Un modelo de IA entrenado en texto específico de dominio puede corregir esos errores. Crucialmente, mantenemos las coordenadas originales para que el diseño espacial permanezca intacto. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Por qué preservamos las coordenadas:* Muchas tareas posteriores (p. ej., generación de PDF, etiquetado AR) dependen de una colocación exacta. La IA solo modifica el campo `text`, dejando `x`, `y`, `width`, `height` sin tocar. + +## Paso 4: Iterar sobre las palabras corregidas y mostrar su texto con coordenadas + +Finalmente, iteramos sobre las palabras corregidas e imprimimos cada palabra junto con su esquina superior izquierda `(x, y)`. Esto satisface el objetivo de **extraer texto con coordenadas**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Salida esperada (ejemplo):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Cada línea muestra la palabra corregida y su ubicación exacta en la imagen original. + +## Ejemplo completo y funcional + +A continuación hay un único script que une todo. Puedes copiar‑pegarlo, ajustar las declaraciones de importación para que coincidan con tus bibliotecas reales y ejecutarlo directamente. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Ejecutando el script** + +```bash +python ocr_postprocess_demo.py +``` + +Si tienes las bibliotecas reales instaladas, el script procesará tu `input.png`. De lo contrario, la implementación de stubs te permite ver el flujo y salida esperados sin dependencias externas. + +## Preguntas frecuentes (FAQ) + +| Pregunta | Respuesta | +|----------|-----------| +| *¿Esto funciona con Tesseract?* | Tesseract en sí no expone un modo estructurado de forma nativa, pero envoltorios como `pytesseract.image_to_data` devuelven cajas delimitadoras que puedes alimentar al mismo post‑procesador de IA. | +| *¿Qué pasa si necesito la esquina inferior‑derecha en lugar de la superior‑izquierda?* | Cada objeto palabra también proporciona `width` y `height`. Calcula `x2 = x + width` y `y2 = y + height` para obtener la esquina opuesta. | +| *¿Puedo procesar por lotes múltiples imágenes?* | Absolutamente. Envuelve los pasos en un bucle `for image_path in Path("folder").glob("*.png"):` y recopila los resultados por archivo. | +| *¿Cómo elijo un modelo de IA para la corrección?* | Para texto genérico, funciona un pequeño GPT‑2 afinado en errores de OCR. Para datos específicos de dominio (p. ej., recetas médicas), entrena un modelo secuencia‑a‑secuencia con datos ruidosos‑limpios emparejados. | +| *¿Es útil la puntuación de confianza después de la corrección de IA?* | Puedes seguir conservando la confianza original para depuración, pero la IA puede generar su propia confianza si el modelo lo soporta. | + +## Casos límite y mejores prácticas + +1. **Imágenes vacías o corruptas** – siempre verifica que `structured_result.words` no esté vacío antes de continuar. +2. **Scripts no latinos** – asegura que tu motor OCR esté configurado para el idioma objetivo; el post‑procesador de IA debe estar entrenado en el mismo script. +3. **Rendimiento** – la corrección de IA puede ser costosa. Cachea los resultados si vas a reutilizar la misma imagen, o ejecuta el paso de IA de forma asíncrona. +4. **Sistema de coordenadas** – las bibliotecas OCR pueden usar orígenes diferentes (superior‑izquierda vs. inferior‑izquierda). Ajusta según sea necesario al superponer en PDFs o lienzos. + +## Conclusión + +Ahora tienes una receta sólida, de extremo a extremo, para **post‑procesar OCR** y **extraer texto con coordenadas** de forma fiable. Al habilitar la salida estructurada, pasar el resultado a través de una capa de corrección de IA y preservar las cajas delimitadoras originales, puedes convertir escaneos OCR ruidosos en texto limpio y consciente del espacio, listo para tareas posteriores como generación de PDF, automatización de entrada de datos o superposiciones de realidad aumentada. + +¿Listo para el siguiente paso? Prueba cambiar la IA de sustitución por una llamada a OpenAI `gpt‑4o‑mini`, o integra la canalización en un FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/spanish/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..84ca7cdb2 --- /dev/null +++ b/ocr/spanish/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,249 @@ +--- +category: general +date: 2026-04-26 +description: Cómo reconocer imágenes rápidamente con Python. Aprende una canalización + de reconocimiento de imágenes, procesamiento por lotes y automatiza el reconocimiento + de imágenes usando IA. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: es +og_description: Cómo reconocer imágenes rápidamente con Python. Esta guía recorre + una canalización de reconocimiento de imágenes, procesamiento por lotes y automatización + usando IA. +og_title: Cómo reconocer imágenes – Automatiza un flujo de trabajo de reconocimiento + de imágenes +tags: +- image-processing +- python +- ai +title: Cómo reconocer imágenes – Automatizar una canalización de reconocimiento de + imágenes +url: /es/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo reconocer imágenes – Automatiza una canalización de reconocimiento de imágenes + +¿Alguna vez te has preguntado **cómo reconocer imágenes** sin escribir miles de líneas de código? No estás solo: muchos desarrolladores se topan con el mismo obstáculo cuando, por primera vez, necesitan procesar decenas o cientos de fotos. ¿La buena noticia? Con unos pocos pasos ordenados puedes crear una canalización de reconocimiento de imágenes completa que agrupe, ejecute y limpie todo por sí sola. + +En este tutorial recorreremos un ejemplo completo y ejecutable que muestra **cómo agrupar imágenes**, alimentar cada una a un motor de IA, post‑procesar los resultados y, finalmente, liberar los recursos. Al terminar tendrás un script autónomo que podrás insertar en cualquier proyecto, ya sea que estés construyendo un etiquetador de fotos, un sistema de control de calidad o un generador de conjuntos de datos para investigación. + +## Lo que aprenderás + +- **Cómo reconocer imágenes** usando un motor de IA simulado (el patrón es idéntico para servicios reales como TensorFlow, PyTorch o APIs en la nube). +- Cómo construir una **canalización de reconocimiento de imágenes** que maneje lotes de forma eficiente. +- La mejor manera de **automatizar el reconocimiento de imágenes** para no tener que iterar manualmente sobre los archivos cada vez. +- Consejos para escalar la canalización y liberar recursos de forma segura. + +> **Requisitos previos:** Python 3.8+, familiaridad básica con funciones y bucles, y un puñado de archivos de imagen (o rutas) que quieras procesar. No se requieren bibliotecas externas para el ejemplo central, pero mencionaremos dónde podrías conectar SDKs de IA reales. + +![Diagrama de cómo reconocer imágenes en una canalización de procesamiento por lotes](pipeline.png "Diagrama de cómo reconocer imágenes") + +## Paso 1: Agrupa tus imágenes – Cómo agrupar imágenes eficientemente + +Antes de que la IA haga cualquier trabajo pesado, necesitas una colección de imágenes para alimentarla. Piensa en esto como tu lista de la compra; el motor luego tomará cada elemento de la lista uno por uno. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**¿Por qué agrupar?** +Agrupar reduce la cantidad de código repetitivo que escribes y hace trivial añadir paralelismo más adelante. Si alguna vez necesitas procesar 10 000 fotos, solo cambiarás la fuente de `image_batch`; el resto de la canalización permanecerá intacto. + +## Paso 2: Ejecuta la canalización de reconocimiento de imágenes (Reconocer imágenes con IA) + +Ahora conectamos el lote al reconocedor real. En un escenario del mundo real podrías llamar a `torchvision.models` o a un endpoint en la nube; aquí simulamos el comportamiento para que el tutorial sea autónomo. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Explicación:** +- `engine.recognize_image` es el corazón de la **canalización de reconocimiento de imágenes**; podría ser una llamada a un modelo de deep learning o a una API REST. +- `postprocessor.run` demuestra **automatizar el reconocimiento de imágenes** normalizando predicciones crudas en un diccionario limpio que puedes almacenar o transmitir. +- Recopilamos cada diccionario `corrected` en `recognized_results` para que los pasos posteriores (p. ej., inserción en base de datos) sean sencillos. + +## Paso 3: Post‑procesar y almacenar – Automatiza los resultados del reconocimiento de imágenes + +Una vez que tienes una lista ordenada de predicciones, normalmente querrás persistirlas. El ejemplo a continuación escribe un archivo CSV; si lo prefieres, puedes cambiarlo por una base de datos o una cola de mensajes. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**¿Por qué un CSV?** +CSV es universalmente legible—Excel, pandas, incluso editores de texto plano pueden abrirlo. Si más adelante necesitas **automatizar el reconocimiento de imágenes** a gran escala, reemplaza el bloque de escritura por una inserción masiva en tu lago de datos. + +## Paso 4: Limpieza – Libera los recursos de IA de forma segura + +Muchos SDK de IA asignan memoria GPU o crean hilos de trabajo. Olvidar liberarlos puede provocar fugas de memoria y fallos desagradables. Aunque nuestros objetos simulados no lo requieran, mostraremos el patrón correcto. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +Ejecutar el script muestra una confirmación amigable, indicando que la canalización ha finalizado correctamente. + +## Script completo y funcional + +Uniendo todo, aquí tienes el programa completo listo para copiar y pegar: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Salida esperada + +Al ejecutar el script (suponiendo que existan las tres rutas de ejemplo), verás algo como: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +Y el archivo `recognition_results.csv` generado contendrá: + +| image | label | confidence | +|---------------------|-------|------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Conclusión + +Ahora dispones de un ejemplo sólido, de extremo a extremo, de **cómo reconocer imágenes** en Python, completo con una **canalización de reconocimiento de imágenes**, manejo de lotes y post‑procesamiento automatizado. El patrón escala: sustituye las clases simuladas por un modelo real, alimenta un `image_batch` más grande y tendrás una solución lista para producción. + +¿Quieres ir más allá? Prueba los siguientes pasos: + +- Sustituye `MockEngine` por un modelo de TensorFlow o PyTorch para obtener predicciones reales. +- Paraleliza el bucle con `concurrent.futures.ThreadPoolExecutor` para acelerar lotes grandes. +- Conecta el escritor de CSV a un bucket de almacenamiento en la nube para **automatizar el reconocimiento de imágenes** entre trabajadores distribuidos. + +Siéntete libre de experimentar, romper cosas y luego arreglarlas—así es como realmente dominas las canalizaciones de reconocimiento de imágenes. Si encuentras algún obstáculo o tienes ideas de mejora, deja un comentario abajo. ¡Feliz codificación! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/spanish/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..d1bcd318c --- /dev/null +++ b/ocr/spanish/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-26 +description: Enmascara rápidamente los números de tarjetas de crédito usando el post‑procesamiento + OCR de AsposeAI. Aprende sobre cumplimiento PCI, enmascaramiento con expresiones + regulares y sanitización de datos en un tutorial paso a paso. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: es +og_description: Enmascara los números de tarjetas de crédito en los resultados de + OCR con AsposeAI. Este tutorial cubre el cumplimiento PCI, el enmascaramiento mediante + expresiones regulares y la sanitización de datos. +og_title: Enmascarar números de tarjetas de crédito – Guía completa de post‑procesamiento + OCR en Python +tags: +- OCR +- Python +- security +title: Enmascarar números de tarjetas de crédito en la salida OCR – Guía completa + de Python +url: /es/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Enmascarar números de tarjetas de crédito – Guía completa de Python + +¿Alguna vez necesitaste **enmascarar números de tarjetas de crédito** en texto que proviene directamente de un motor OCR? No eres el único. En industrias reguladas, exponer un PAN completo (Primary Account Number) puede meterte en problemas con los auditores de cumplimiento PCI. ¿La buena noticia? Con unas pocas líneas de Python y el hook de post‑procesamiento de AsposeAI, puedes ocultar automáticamente los ocho dígitos del medio y mantenerte en el lado seguro. + +En este tutorial recorreremos un escenario del mundo real: ejecutar OCR sobre una imagen de recibo y luego aplicar una función personalizada de **post‑processing OCR** que sanea cualquier dato PCI. Al final tendrás un fragmento reutilizable que puedes insertar en cualquier flujo de trabajo de AsposeAI, además de varios consejos prácticos para manejar casos límite y escalar la solución. + +## Lo que aprenderás + +- Cómo registrar un post‑processor personalizado con **AsposeAI**. +- Por qué un enfoque de **enmascaramiento con expresiones regulares** es rápido y fiable. +- Los conceptos básicos de **cumplimiento PCI** relacionados con la sanitización de datos. +- Formas de extender el patrón para múltiples formatos de tarjetas o números internacionales. +- Salida esperada y cómo verificar que el enmascaramiento funcionó. + +> **Requisitos previos** – Debes contar con un entorno Python 3 funcional, el paquete Aspose.AI for OCR instalado (`pip install aspose-ocr`), y una imagen de muestra (p. ej., `receipt.png`) que contenga un número de tarjeta de crédito. No se requieren otros servicios externos. + +--- + +## Paso 1: Definir un post‑processor que enmascare números de tarjetas de crédito + +El corazón de la solución vive en una pequeña función que recibe el resultado del OCR, ejecuta una rutina de **enmascaramiento con expresiones regulares** y devuelve el texto saneado. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Por qué funciona esto:** +- La expresión regular `(\d{4})\d{8}(\d{4})` coincide exactamente con 16 dígitos consecutivos, el formato común para Visa, MasterCard y muchas otras. +- Al capturar los primeros y últimos cuatro dígitos (`\1` y `\2`) conservamos suficiente información para depuración mientras cumplimos con las reglas de **cumplimiento PCI** que prohíben almacenar el PAN completo. +- La sustitución `\1****\2` oculta los ocho dígitos sensibles del medio, convirtiendo `1234567812345678` en `1234****5678`. + +> **Consejo profesional:** Si necesitas soportar números American Express de 15 dígitos, añade un segundo patrón como `r'(\d{4})\d{6}(\d{5})'` y ejecuta ambas sustituciones secuencialmente. + +--- + +## Paso 2: Inicializar el motor AsposeAI + +Antes de poder adjuntar nuestro post‑processor, necesitamos una instancia del motor OCR. AsposeAI incluye el modelo OCR y una API sencilla para procesamiento personalizado. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**¿Por qué inicializar aquí?** +Crear el objeto `AsposeAI` una sola vez y reutilizarlo en múltiples imágenes reduce la sobrecarga. El motor también almacena en caché los modelos de idioma, lo que acelera llamadas posteriores—útil cuando escaneas lotes de recibos. + +--- + +## Paso 3: Registrar la función de enmascaramiento personalizada + +AsposeAI expone un método `set_post_processor` que permite conectar cualquier callable. Pasamos nuestra función `mask_pci` junto con un diccionario de configuraciones opcional (vacío por ahora). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**¿Qué ocurre tras bambalinas?** +Cuando más adelante invoques `run_postprocessor`, AsposeAI entregará el resultado bruto del OCR a `mask_pci`. La función recibe un objeto ligero (`data`) que contiene el texto reconocido, y tú devuelves una nueva cadena. Este diseño mantiene el OCR central intacto mientras te permite aplicar políticas de **sanitización de datos** en un solo lugar. + +--- + +## Paso 4: Ejecutar OCR sobre la imagen del recibo + +Ahora que el motor sabe cómo limpiar la salida, le pasamos una imagen. Para este tutorial asumimos que ya dispones de un objeto `engine` configurado con el idioma y la resolución adecuados. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Consejo:** Si no tienes un objeto preconfigurado, puedes crear uno con: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +La llamada `recognize_image` devuelve un objeto cuyo atributo `text` contiene la cadena cruda, sin enmascarar. + +--- + +## Paso 5: Aplicar el post‑processor registrado + +Con los datos OCR sin procesar en mano, los entregamos a la instancia de IA. El motor ejecuta automáticamente la función `mask_pci` que registramos anteriormente. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**¿Por qué usar `run_postprocessor` en lugar de llamar a la función manualmente?** +Hacerlo mantiene el flujo de trabajo coherente, especialmente cuando tienes varios post‑processors (p. ej., corrección ortográfica, detección de idioma). AsposeAI los encola en el orden en que los registras, garantizando una salida determinista. + +--- + +## Paso 6: Verificar la salida saneada + +Finalmente, imprimamos el texto saneado y confirmemos que cualquier número de tarjeta de crédito está correctamente enmascarado. + +```python +print(final_result.text) +``` + +**Salida esperada** (extracto): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Si el recibo no contenía número de tarjeta, el texto permanece sin cambios—nada que enmascarar, nada de qué preocuparse. + +--- + +## Manejo de casos límite y variaciones comunes + +### Múltiples números de tarjeta en un mismo documento +Si un recibo incluye más de un PAN (p. ej., una tarjeta de fidelidad más una tarjeta de pago), la expresión regular se ejecuta globalmente, enmascarando todas las coincidencias automáticamente. No se necesita código adicional. + +### Formato no estándar +A veces el OCR inserta espacios o guiones (`1234 5678 1234 5678` o `1234-5678-1234-5678`). Amplía el patrón para ignorar esos caracteres: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +El añadido `[ -]?` tolera espacios o guiones opcionales entre bloques de dígitos. + +### Tarjetas internacionales +Para PAN de 19 dígitos usados en algunas regiones, puedes ampliar el patrón: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Solo recuerda que **cumplimiento PCI** sigue exigiendo enmascarar los dígitos del medio, sin importar la longitud. + +### Registro de valores enmascarados (opcional) +Si necesitas auditorías, pasa una bandera mediante `custom_settings` y ajusta la función: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Luego regístrala con: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Ejemplo completo listo para copiar y pegar + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Ejecutar este script sobre un recibo que contenga `4111111111111111` producirá: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +Ese es todo el pipeline—desde OCR crudo hasta **sanitización de datos**—envuelto en unas pocas líneas limpias de Python. + +--- + +## Conclusión + +Acabamos de mostrarte cómo **enmascarar números de tarjetas de crédito** en resultados OCR usando el hook de post‑processing de AsposeAI, una rutina concisa de expresiones regulares y varios consejos de mejores prácticas para **cumplimiento PCI**. La solución es totalmente autónoma, funciona con cualquier imagen que el motor OCR pueda leer y puede ampliarse para cubrir formatos de tarjeta más complejos o requisitos de registro. + +¿Listo para el siguiente paso? Prueba combinar este enmascarado con una rutina de **inserción en base de datos** que almacene solo los últimos cuatro dígitos como referencia, o integra un **procesador por lotes** que escanee una carpeta completa de recibos durante la noche. También podrías explorar otras tareas de **post‑processing OCR** como la estandarización de direcciones o la detección de idioma—cada una sigue el mismo patrón que usamos aquí. + +¿Tienes preguntas sobre casos límite, rendimiento o cómo adaptar el código a otra biblioteca OCR? Deja un comentario abajo y mantengamos la conversación. ¡Feliz codificación y mantente seguro! + +![Diagram illustrating how mask credit card numbers works in an OCR pipeline](https://example.com/images/ocr-mask-flow.png "Diagram of OCR post‑processing masking flow") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/spanish/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..a655b62c0 --- /dev/null +++ b/ocr/spanish/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-04-26 +description: Aprende a medir el tiempo de inferencia en Python, cargar un modelo GGUF + desde Hugging Face y optimizar el uso de la GPU para obtener resultados más rápidos. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: es +og_description: Mide el tiempo de inferencia en Python cargando un modelo GGUF de + Hugging Face y ajustando las capas de GPU para un rendimiento óptimo. +og_title: Medir el tiempo de inferencia – Cargar modelo GGUF y optimizar GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Medir el tiempo de inferencia – Cargar modelo GGUF y optimizar GPU +url: /es/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Medir el Tiempo de Inferencia – Cargar Modelo GGUF y Optimizar GPU + +¿Alguna vez necesitaste **measure inference time** para un modelo de lenguaje grande pero no sabías por dónde empezar? No estás solo—muchos desarrolladores se encuentran con el mismo obstáculo cuando primero descargan un archivo GGUF de Hugging Face y tratan de ejecutarlo en una configuración mixta de CPU/GPU. + +En esta guía recorreremos **how to load a GGUF model**, lo configuraremos para Hugging Face y **measure inference time** con un fragmento de Python limpio. A lo largo del camino también te mostraremos cómo **optimize inference GPU** para que tus ejecuciones sean lo más rápidas posible. Sin rodeos, solo una solución práctica de extremo a extremo que puedes copiar y pegar hoy. + +## Lo que aprenderás + +- Cómo **configure a HuggingFace model** con `AsposeAIModelConfig`. +- Los pasos exactos para **load a GGUF model** (cuantización `fp16`) desde el hub de Hugging Face. +- Un patrón reutilizable para **timing Python code** alrededor de una llamada de inferencia. +- Consejos para **optimize inference GPU** ajustando `gpu_layers`. +- Salida esperada y cómo verificar que tu temporización tiene sentido. + +### Requisitos previos + +| Requisito | Por qué es importante | +|-------------|----------------| +| Python 3.9+ | Sintaxis moderna y anotaciones de tipos. | +| `asposeai` package (o el SDK equivalente) | Proporciona `AsposeAI` y `AsposeAIModelConfig`. | +| Access to the Hugging Face repo `bartowski/Qwen2.5-3B-Instruct-GGUF` | El modelo GGUF que cargaremos. | +| A GPU with at least 8 GB VRAM (optional but recommended) | Habilita el paso **optimize inference GPU**. | + +Si aún no has instalado el SDK, ejecuta: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +![measure inference time diagram](https://example.com/measure-inference-time.png){alt="diagrama de medir tiempo de inferencia"} + +## Paso 1: Cargar el Modelo GGUF – Configurar Modelo HuggingFace + +Lo primero que necesitas es un objeto de configuración adecuado que indique a Aspose AI dónde obtener el modelo y cómo tratarlo. Aquí es donde **load a GGUF model** y **configure huggingface model** parámetros. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Por qué es importante:** +- `hugging_face_repo_id` apunta al archivo GGUF exacto en el Hub. +- `fp16` reduce el ancho de banda de memoria mientras mantiene la mayor parte de la fidelidad del modelo. +- `gpu_layers` es el control que ajustas cuando deseas **optimize inference GPU**; más capas en la GPU normalmente significan menor latencia, siempre que tengas suficiente VRAM. + +## Paso 2: Crear la Instancia Aspose AI + +Ahora que el modelo está descrito, iniciamos un objeto `AsposeAI`. Este paso es sencillo, pero es donde el SDK realmente descarga el archivo GGUF (si no está en caché) y prepara el tiempo de ejecución. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Consejo profesional:** La primera ejecución tomará unos segundos más porque el modelo se está descargando y compilando para la GPU. Las ejecuciones posteriores son ultrarrápidas. + +## Paso 3: Ejecutar Inferencia y **Measure Inference Time** + +Este es el núcleo del tutorial: envolver la llamada de inferencia con `time.time()` para **measure inference time**. También alimentamos un pequeño resultado OCR solo para mantener el ejemplo autocontenido. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Lo que deberías ver:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Si el número parece alto, probablemente estés ejecutando la mayoría de las capas en la CPU. Eso nos lleva al siguiente paso. + +## Paso 4: **Optimize Inference GPU** – Ajustar `gpu_layers` + +A veces el valor predeterminado `gpu_layers=40` es demasiado agresivo (causando OOM) o demasiado conservador (dejando rendimiento sin aprovechar). Aquí tienes un bucle rápido que puedes usar para encontrar el punto óptimo: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Por qué funciona esto:** +- Cada llamada reconstruye el tiempo de ejecución con una asignación de GPU diferente, permitiéndote ver instantáneamente el compromiso de latencia. +- El bucle también demuestra **time python code** de forma reutilizable, que puedes adaptar para otras pruebas de rendimiento. + +Una salida típica en una RTX 3080 de 16 GB podría verse así: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +A partir de eso, elegirías `gpu_layers=40` como el punto óptimo para este hardware. + +## Ejemplo Completo Funcional + +Juntando todo, aquí tienes un script único que puedes colocar en un archivo (`measure_inference.py`) y ejecutar: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Ejecuta con: + +```bash +python measure_inference.py +``` + +Deberías ver una latencia inferior a un segundo en una GPU decente, confirmando que has **measure inference time** y **optimize inference GPU** con éxito. + +--- + +## Preguntas Frecuentes (FAQs) + +**Q: ¿Funciona esto con otros formatos de cuantización?** +A: Absolutamente. Cambia `hugging_face_quantization="int8"` (o `q4_0`, etc.) en la configuración y vuelve a ejecutar la prueba. Espera un compromiso: menor uso de memoria vs. una ligera disminución de precisión. + +**Q: ¿Qué pasa si no tengo una GPU?** +A: Establece `gpu_layers=0`. El código recurrirá completamente a la CPU, y aún podrás **measure inference time**—solo espera números más altos. + +**Q: ¿Puedo cronometrar solo el paso forward del modelo, excluyendo el post‑procesamiento?** +A: Sí. Llama a `ai_engine.run_model(...)` (o al método equivalente) directamente y envuelve esa llamada con `time.time()`. El patrón para **time python code** sigue siendo el mismo. + +## Conclusión + +Ahora tienes una solución completa, lista para copiar y pegar, para **measure inference time** de un modelo GGUF, **load gguf model** desde Hugging Face, y afinar los ajustes de **optimize inference GPU**. Ajustando `gpu_layers` y experimentando con la cuantización, puedes exprimir cada milisegundo de rendimiento. + +- Integra esta lógica de temporización en una canalización CI para detectar regresiones. +- Explora la inferencia por lotes para mejorar aún más el rendimiento. +- Combina el modelo con una canalización OCR real en lugar del texto ficticio que usamos aquí. + +¡Feliz codificación, y que tus números de latencia siempre se mantengan bajos! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/spanish/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..1d25a1073 --- /dev/null +++ b/ocr/spanish/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-04-26 +description: Reconocer texto manuscrito usando el motor OCR de Python. Aprende cómo + extraer texto de una imagen, activar el modo manuscrito y leer notas manuscritas + rápidamente. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: es +og_description: reconocer texto manuscrito con Python. Este tutorial muestra cómo + extraer texto de una imagen, activar el modo manuscrito y leer notas manuscritas + usando un motor OCR simple. +og_title: reconocer texto manuscrito en Python – Guía completa de OCR +tags: +- OCR +- Python +- Handwriting Recognition +title: Reconocer texto manuscrito en Python – Tutorial del motor OCR +url: /es/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# reconocer texto manuscrito en Python – Tutorial del motor OCR + +¿Alguna vez necesitaste **reconocer texto manuscrito** pero te sentiste atascado en el “¿por dónde empiezo?”? No eres el único. Ya sea que estés digitalizando garabatos de reuniones o extrayendo datos de un formulario escaneado, obtener un resultado de OCR fiable puede sentirse como perseguir un unicornio. + +Buenas noticias: con solo unas pocas líneas de Python puedes **extraer texto de imagen** archivos, **activar el modo manuscrito**, y finalmente **leer notas manuscritas** sin buscar bibliotecas obscuras. En esta guía recorreremos todo el proceso, desde la configuración al estilo **create OCR engine python** hasta imprimir el resultado en pantalla. + +## Lo que aprenderás + +- Cómo crear una instancia **create OCR engine python** usando el paquete `ocr`. +- Qué configuración de idioma te brinda soporte integrado para manuscritos. +- La llamada exacta para **turn on handwritten mode** para que el motor sepa que estás tratando con cursiva. +- Cómo proporcionar una foto de una nota y **recognize handwritten text** de ella. +- Consejos para manejar diferentes formatos de imagen, solucionar problemas comunes y ampliar la solución. + +Sin relleno, sin callejones sin salida de “ver la documentación”—solo un script completo y ejecutable que puedes copiar‑pegar y probar hoy. + +## Requisitos previos + +1. Python 3.8+ instalado (el código usa f‑strings). +2. La hipotética biblioteca `ocr` (`pip install ocr‑engine` – reemplaza con el nombre real del paquete que estés usando). +3. Un archivo de imagen claro de una nota manuscrita (JPEG, PNG o TIFF funciona). +4. Una cantidad modesta de curiosidad—todo lo demás está cubierto a continuación. + +> **Consejo profesional:** Si tu imagen es ruidosa, ejecuta un paso rápido de preprocesamiento con Pillow (p. ej., `Image.open(...).convert('L')`) antes de enviarla al motor OCR. A menudo mejora la precisión. + +## Cómo reconocer texto manuscrito con Python + +A continuación se muestra el script completo que **creates OCR engine python** objetos, los configura para manuscritos y muestra la cadena extraída. Guárdalo como `handwriting_ocr.py` y ejecútalo desde tu terminal. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Salida esperada + +Cuando el script se ejecute correctamente, verás algo como: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Si el motor OCR no puede detectar ningún carácter, el campo `text` será una cadena vacía. En ese caso, verifica nuevamente la calidad de la imagen o prueba con un escaneo de mayor resolución. + +## Explicación paso a paso + +### Paso 1 – instancia **create OCR engine python** + +La clase `OcrEngine` es el punto de entrada. Piensa en ella como un cuaderno en blanco—no ocurre nada hasta que le indiques qué idioma esperar y si estás tratando con manuscritos. + +### Paso 2 – Elige un idioma que soporte manuscritos + +`ocr.Language.EXTENDED_LATIN` no es solo “English”. Agrupa un conjunto de scripts basados en latín y, crucialmente, incluye modelos entrenados con muestras de cursiva. Omitir este paso a menudo produce una salida confusa porque el motor usa por defecto un modelo de texto impreso. + +### Paso 3 – **turn on handwritten mode** + +Llamar a `enable_handwritten_mode(True)` activa una bandera interna. El motor entonces cambia a su red neuronal ajustada para el espaciado irregular y los anchos de trazo variables que se ven en notas del mundo real. Olvidar esta línea es un error común; el motor tratará tus garabatos como ruido. + +### Paso 4 – Proporciona la imagen y **recognize handwritten text** + +`recognize_image` hace el trabajo pesado: preprocesa el bitmap, lo pasa por el modelo de manuscrito y devuelve un objeto con el atributo `text`. También puedes inspeccionar `handwritten_result.confidence` si necesitas una métrica de calidad. + +### Paso 5 – Imprime el resultado y **read handwritten notes** + +`print(handwritten_result.text)` es la forma más simple de verificar que has **extract text from image** con éxito. En producción probablemente almacenarías la cadena en una base de datos o la pasarías a otro servicio. + +## Manejo de casos límite y variaciones comunes + +| Situación | Qué hacer | +|-----------|------------| +| **La imagen está rotada** | Usa Pillow para rotar (`Image.rotate(angle)`) antes de llamar a `recognize_image`. | +| **Bajo contraste** | Convierte a escala de grises y aplica umbral adaptativo (`Image.point(lambda p: p > 128 and 255)`). | +| **Múltiples páginas** | Itera sobre una lista de rutas de archivo y concatena los resultados. | +| **Scripts no latinos** | Reemplaza `EXTENDED_LATIN` con `ocr.Language.CHINESE` (u otro apropiado) y mantén `enable_handwritten_mode(True)`. | +| **Preocupaciones de rendimiento** | Reutiliza la misma instancia `ocr_engine` para muchas imágenes; inicializarla cada vez agrega sobrecarga. | + +### Consejo profesional sobre uso de memoria + +Si estás procesando cientos de notas en lote, llama a `ocr_engine.dispose()` después de terminar. Libera recursos nativos que el wrapper de Python podría estar reteniendo. + +## Recapitulación visual rápida + +![ejemplo de reconocimiento de texto manuscrito](https://example.com/handwritten-note.png "ejemplo de reconocimiento de texto manuscrito") + +*La imagen anterior muestra una nota manuscrita típica que nuestro script puede convertir en texto plano.* + +## Ejemplo completo funcional (script de un solo archivo) + +Para quienes aman la simplicidad de copiar‑pegar, aquí está todo de nuevo sin los comentarios explicativos: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Ejecuta con: + +```bash +python handwriting_ocr.py +``` + +Ahora deberías ver la salida de **recognize handwritten text** en tu consola. + +## Conclusión + +Acabamos de cubrir todo lo que necesitas para **recognize handwritten text** en Python—comenzando con una llamada fresca a **create OCR engine python**, seleccionando el idioma correcto, **turn on handwritten mode**, y finalmente **extract text from image** para **read handwritten notes**. + +En un único script autocontenido puedes pasar de una foto borrosa de un garabato de reunión a texto limpio y buscable. A continuación, considera alimentar la salida a una canalización de lenguaje natural, almacenarla en un índice buscable, o incluso devolverla a un servicio de transcripción para generar voz en off. + +### ¿A dónde ir desde aquí? + +- **Procesamiento por lotes:** Envuelve el script en un bucle para manejar una carpeta de escaneos. +- **Filtrado por confianza:** Usa `result.confidence` para descartar lecturas de baja calidad. +- **Bibliotecas alternativas:** Si `ocr` no encaja perfectamente, explora `pytesseract` con `--psm 13` para modo manuscrito. +- **Integración UI:** Combínalo con Flask o FastAPI para ofrecer un servicio de carga web. + +¿Tienes preguntas sobre un formato de imagen en particular o necesitas ayuda afinando el modelo? Deja un comentario abajo, ¡y feliz codificación! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/swedish/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..ecc1c95ae --- /dev/null +++ b/ocr/swedish/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-04-26 +description: Lär dig hur du laddar ner HuggingFace-modellen python och extraherar + text från bild python samtidigt som du förbättrar OCR‑noggrannheten python med Aspose + OCR Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: sv +og_description: Ladda ner HuggingFace-modellen för Python och förbättra din OCR-pipeline. + Följ den här guiden för att extrahera text från bild med Python och förbättra OCR‑noggrannheten + med Python. +og_title: Ladda ner Huggingface-modell Python – Komplett OCR-förbättringstutorial +tags: +- OCR +- HuggingFace +- Python +- AI +title: ladda ner huggingface-modell python – steg‑för‑steg OCR Boost‑guide +url: /sv/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – Komplett OCR-förbättringstutorial + +Har du någonsin försökt **download HuggingFace model python** och känt dig lite vilse? Du är inte ensam. I många projekt är den största flaskhalsen att få en bra modell på din maskin och sedan göra OCR-resultaten faktiskt användbara. + +I den här guiden går vi igenom ett praktiskt exempel som visar exakt hur du **download HuggingFace model python**, extraherar text från en bild med **extract text from image python**, och sedan **improve OCR accuracy python** med Asposes AI‑postprocessor. I slutet har du ett färdigt skript som omvandlar en brusig fakturabild till ren, läsbar text—ingen magi, bara tydliga steg. + +## Vad du behöver + +- Python 3.9+ (koden fungerar även på 3.11) +- En internetanslutning för den engångsmodellnedladdning som krävs +- `asposeocrcloud`‑paketet (`pip install asposeocrcloud`) +- En exempelbild (t.ex. `sample_invoice.png`) placerad i en mapp du kontrollerar + +Det är allt—inga tunga ramverk, inga GPU‑specifika drivrutiner om du inte vill snabba upp processen. + +Nu, låt oss dyka ner i den faktiska implementeringen. + +![download huggingface model python arbetsflöde](image.png "download huggingface model python diagram") + +## Steg 1: Ställ in OCR‑motorn och välj ett språk +*(Det här är där vi börjar **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Varför detta är viktigt:** +OCR‑motorn är den första försvarslinjen; att välja rätt språkpaket minskar teckenigenkänningsfel omedelbart, vilket är en kärnkomponent i **improve OCR accuracy python**. + +## Steg 2: Konfigurera AsposeAI‑modellen – Nedladdning från HuggingFace +*(Här **download HuggingFace model python** faktiskt.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**Vad händer under huven?** +När `allow_auto_download` är true kontaktar SDK:t HuggingFace, hämtar `Qwen2.5‑3B‑Instruct‑GGUF`‑modellen och lagrar den i den mapp du angav. Detta är kärnan i **download huggingface model python**—SDK:t sköter det tunga arbetet, så du behöver inte skriva några `git clone`‑ eller `wget`‑kommandon själv. + +*Proffstips:* Håll `directory_model_path` på en SSD för snabbare laddning; modellen är ~3 GB även i `int8`‑format. + +## Steg 3: Anslut AI‑motorn till OCR‑motorn +*(Kopplar ihop de två delarna så vi kan **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Varför binda dem?** +OCR‑motorn ger oss råtext, som kan innehålla stavfel, brutna rader eller felaktig interpunktion. AI‑motorn fungerar som en smart redigerare som rensar upp dessa problem—precis vad du behöver för att **improve OCR accuracy python**. + +## Steg 4: Kör OCR på din bild +*(Ögonblicket då vi äntligen **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` innehåller nu ett `text`‑attribut med de råa tecknen som motorn såg. I praktiken kommer du märka några småfel—kanske blev “Invoice” till “Inv0ice” eller ett radbryt i mitten av en mening. + +## Steg 5: Rensa upp med AI‑postprocessorn +*(Detta steg förbättrar direkt **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +AI‑modellen skriver om texten och applicerar språkmedvetna korrigeringar. Eftersom vi använde en instruktion‑tuned modell från HuggingFace är resultatet vanligtvis flytande och redo för efterföljande bearbetning. + +## Steg 6: Visa före och efter +*(En snabb kontroll för att se hur bra vi **extract text from image python** och **improve OCR accuracy python**.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Förväntat resultat + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Lägg märke till hur AI korrigerade “Inv0ice” till “Invoice” och jämnade ut eventuella lösa radbryt. Det är det konkreta resultatet av **improve OCR accuracy python** med en nedladdad HuggingFace‑modell. + +## Vanliga frågor (FAQ) + +### Behöver jag ett GPU för att köra modellen? +Nej. Inställningen `gpu_layers=20` säger åt SDK:t att använda upp till 20 GPU‑lager om ett kompatibelt GPU finns; annars faller det tillbaka på CPU. På en modern laptop klarar CPU‑vägen fortfarande några hundra token per sekund—perfekt för sporadisk fakturaparsning. + +### Vad händer om modellen misslyckas med att laddas ner? +Se till att din miljö kan nå `https://huggingface.co`. Om du sitter bakom en företagsproxy, sätt miljövariablerna `HTTP_PROXY` och `HTTPS_PROXY`. SDK:t kommer automatiskt att försöka igen, men du kan också manuellt `git lfs pull` repot till `directory_model_path`. + +### Kan jag byta modellen mot en mindre? +Absolut. Byt bara ut `hugging_face_repo_id` mot ett annat repo (t.ex. `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) och justera `hugging_face_quantization` därefter. Mindre modeller laddas ner snabbare och använder mindre RAM, även om du kan förlora lite korrigeringskvalitet. + +### Hur hjälper detta mig att **extract text from image python** i andra domäner? +Samma pipeline fungerar för kvitton, pass eller handskrivna anteckningar. Den enda förändringen är språkpaketet (`ocr.Language.FRENCH` osv.) och eventuellt en domänspecifik fin‑tuned modell från HuggingFace. + +## Bonus: Automatisera flera filer + +Om du har en mapp full av bilder, slå in OCR‑anropet i en enkel loop: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +Detta lilla tillägg låter dig **download huggingface model python** en gång, och sedan batch‑processa dussintals filer—perfekt för att skala upp din dokument‑automationspipeline. + +## Slutsats + +Vi har precis gått igenom ett komplett, end‑to‑end‑exempel som visar hur du **download HuggingFace model python**, **extract text from image python**, och **improve OCR accuracy python** med Asposes OCR Cloud och en AI‑postprocessor. Skriptet är redo att köras, koncepten är förklarade, och du har sett före‑och‑efter‑resultatet så du vet att det fungerar. + +Vad blir nästa steg? Prova att byta till en annan HuggingFace‑modell, experimentera med andra språkpaket, eller mata in den rensade texten i en efterföljande NLP‑pipeline (t.ex. entitetsutvinning för fakturarader). Himlen är gränsen, och grunden du just byggt är solid. + +Har du frågor eller en knepig bild som fortfarande får OCR:n att krångla? Lägg en kommentar nedan, så felsöker vi tillsammans. Lycka till med kodandet! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/swedish/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..434366205 --- /dev/null +++ b/ocr/swedish/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-04-26 +description: Ladda ner OCR-modell snabbt med Aspose OCR Python. Lär dig hur du ställer + in modellkatalog, konfigurerar modellens sökväg och hur du laddar ner modellen på + några rader. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: sv +og_description: Ladda ner OCR-modell på några sekunder med Aspose OCR Python. Denna + guide visar hur du ställer in modellkatalog, konfigurerar modellens sökväg och hur + du laddar ner modellen säkert. +og_title: ladda ner OCR-modell – Komplett Aspose OCR Python-handledning +tags: +- OCR +- Python +- Aspose +title: Ladda ner OCR-modell med Aspose OCR Python – Steg‑för‑steg guide +url: /sv/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ladda ner ocr-modell – Komplett Aspose OCR Python‑handledning + +Har du någonsin undrat hur man **download ocr model** med Aspose OCR i Python utan att leta igenom ändlösa dokument? Du är inte ensam. Många utvecklare stöter på problem när modellen inte finns lokalt och SDK:n kastar ett kryptiskt fel. Den goda nyheten? Lösningen är några få rader, och du har modellen klar på några minuter. + +I den här handledningen går vi igenom allt du behöver veta: från att importera rätt klasser, till **set model directory**, till faktiskt **how to download model**, och slutligen verifiera sökvägen. I slutet kommer du kunna köra OCR på vilken bild som helst med ett enda funktionsanrop, och du kommer förstå **configure model path**‑alternativen som håller ditt projekt prydligt. Inga onödiga detaljer, bara ett praktiskt, körbart exempel för **aspose ocr python**‑användare. + +## Vad du kommer att lära dig + +- Hur du importerar Aspose OCR Cloud‑klasserna korrekt. +- De exakta stegen för att **download ocr model** automatiskt. +- Sätt att **set model directory** och **configure model path** för reproducerbara byggen. +- Hur du verifierar att modellen är initierad och var den finns på disken. +- Vanliga fallgropar (behörigheter, saknade kataloger) och snabba lösningar. + +### Förutsättningar + +- Python 3.8+ installerat på din maskin. +- `asposeocrcloud`‑paketet (`pip install asposeocrcloud`). +- Skrivbehörighet till en mapp där du vill lagra modellen (t.ex. `C:\models` eller `~/ocr_models`). + +--- + +## Steg 1: Importera Aspose OCR Cloud‑klasser + +Det första du behöver är rätt import‑sats. Den hämtar klasserna som hanterar modellkonfiguration och OCR‑operationer. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Varför detta är viktigt:* `AsposeAI` är motorn som kör OCR, medan `AsposeAIModelConfig` talar om för motorn **var** den ska leta efter modellen och **om** den ska hämta den automatiskt. Att hoppa över detta steg eller importera fel modul kommer att orsaka ett `ModuleNotFoundError` innan du ens kommer till nedladdningsdelen. + +--- + +## Steg 2: Definiera modellkonfigurationen (Set Model Directory & Configure Model Path) + +Nu berättar vi för Aspose var modellfilerna ska lagras. Här **set model directory** och **configure model path**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Tips & fallgropar** + +- **Absoluta sökvägar** undviker förvirring när skriptet körs från en annan arbetskatalog. +- På Linux/macOS kan du använda `"/home/you/ocr_models"`; på Windows, prefixa med `r` för att behandla bakstreck bokstavligt. +- Att sätta `allow_auto_download="true"` är nyckeln till **how to download model** utan att skriva extra kod. + +--- + +## Steg 3: Skapa AsposeAI‑instansen med konfigurationen + +När konfigurationen är klar, instansiera OCR‑motorn. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Varför detta är viktigt:* `ocr_ai`‑objektet innehåller nu konfigurationen vi just definierade. Om modellen inte finns, kommer nästa anrop att automatiskt trigga nedladdningen—detta är kärnan i **how to download model** på ett hands‑off‑sätt. + +--- + +## Steg 4: Initiera modellnedladdning (om behövs) + +Innan du kan köra OCR måste du säkerställa att modellen faktiskt finns på disken. Metoden `is_initialized()` både kontrollerar och tvingar initiering. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**Vad händer under huven?** + +- Det första anropet till `is_initialized()` returnerar `False` eftersom modellmappen är tom. +- `print` informerar användaren om att en nedladdning är på väg att starta. +- Det andra anropet tvingar Aspose att hämta modellen från Hugging Face‑repo du angav tidigare. +- När den är nedladdad returnerar metoden `True` vid efterföljande kontroller. + +**Edge case:** Om ditt nätverk blockerar Hugging Face kommer du att få ett undantag. I så fall, ladda ner modell‑zippet manuellt, extrahera det till `directory_model_path` och kör skriptet igen. + +--- + +## Steg 5: Rapportera den lokala sökvägen där modellen nu finns tillgänglig + +När nedladdningen är klar vill du förmodligen veta var filerna hamnade. Detta hjälper vid felsökning och vid uppsättning av CI‑pipelines. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Typisk utskrift ser ut så här: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Nu har du framgångsrikt **download ocr model**, satt katalogen och bekräftat sökvägen. + +--- + +## Visuell översikt + +Nedan är ett enkelt diagram som visar flödet från konfiguration till en färdig‑att‑använda modell. + +![diagram över nedladdning av ocr-modell som visar konfiguration, automatisk nedladdning och lokal sökväg](/images/download-ocr-model-flow.png) + +*Alt‑texten innehåller huvudnyckelordet för SEO.* + +--- + +## Vanliga variationer & hur du hanterar dem + +### 1. Använda ett annat modell‑repo + +Om du behöver en modell annan än `openai/gpt2`, ersätt bara värdet på `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Se till att repot är offentligt eller att du har nödvändig token konfigurerad i din miljö. + +### 2. Inaktivera automatisk nedladdning + +Ibland vill du kontrollera nedladdningen själv (t.ex. i luftgap‑miljöer). Sätt `allow_auto_download` till `"false"` och anropa ett eget nedladdningsskript innan initiering: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Ändra modellkatalogen vid körning + +Du kan omkonfigurera sökvägen utan att återskapa `AsposeAI`‑objektet: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Pro‑tips för produktionsanvändning + +- **Cachea modellen**: Håll katalogen på en delad nätverksenhet om flera tjänster behöver samma modell. Detta undviker onödiga nedladdningar. +- **Version‑pinning**: Hugging Face‑repo kan uppdateras. För att låsa till en specifik version, lägg till `@v1.0.0` till repo‑ID:t (`"openai/gpt2@v1.0.0"`). +- **Behörigheter**: Säkerställ att användaren som kör skriptet har läs‑/skrivrättigheter på `directory_model_path`. På Linux räcker vanligtvis `chmod 755`. +- **Loggning**: Ersätt de enkla `print`‑satserna med Pythons `logging`‑modul för bättre observabilitet i större applikationer. + +--- + +## Fullt fungerande exempel (klart att kopiera och klistra in) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Förväntad utskrift** (första körningen laddar ner, efterföljande körningar hoppar över nedladdning): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Kör skriptet igen; du kommer bara se sökvägsraden eftersom modellen redan är cachad. + +--- + +## Slutsats + +Vi har just gått igenom hela processen för att **download ocr model** med Aspose OCR Python, visat hur man **set model directory**, och förklarat nyanserna i **configure model path**. Med bara några rader kod kan du automatisera nedladdningen, undvika manuella steg och hålla din OCR‑pipeline reproducerbar. + +Nästa steg kan vara att utforska det faktiska OCR‑anropet (`ocr_ai.recognize_image(...)`) eller experimentera med en annan Hugging Face‑modell för att förbättra noggrannheten. Oavsett så ger grunden du byggt här—klar konfiguration, automatisk nedladdning och sökvägsverifiering—en smidig framtida integration. + +Har du frågor om edge cases, eller vill du dela hur du justerade modellkatalogen för moln‑distributioner? Lämna en kommentar nedan, och lycka till med kodandet! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/swedish/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..44c2259ed --- /dev/null +++ b/ocr/swedish/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-04-26 +description: Hur man efterbehandlar OCR‑resultat och extraherar text med koordinater. + Lär dig en steg‑för‑steg‑lösning med strukturerad output och AI‑korrigering. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: sv +og_description: Hur man efterbehandlar OCR‑resultat och extraherar text med koordinater. + Följ den här omfattande handledningen för ett pålitligt arbetsflöde. +og_title: Hur man efterbehandlar OCR – Komplett guide +tags: +- OCR +- Python +- AI +- Text Extraction +title: Hur man efterbehandlar OCR – Extrahera text med koordinater i Python +url: /sv/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hur man efterbehandlar OCR – Extrahera text med koordinater i Python + +Har du någonsin behövt **how to post‑process OCR** resultat eftersom den råa utdata var brusig eller feljusterad? Du är inte ensam. I många verkliga projekt—fakturaskanning, kvitto‑digitalisering eller till och med förstärkning av AR‑upplevelser—ger OCR‑motorn dig råa ord, men du måste fortfarande rensa dem och hålla reda på var varje ord finns på sidan. Det är där ett strukturerat utdata‑läge kombinerat med en AI‑driven efterbehandlare glänser. + +I den här handledningen kommer vi att gå igenom en komplett, körbar Python‑pipeline som **extraherar text med koordinater** från en bild, kör ett AI‑baserat korrigeringssteg och skriver ut varje ord tillsammans med dess (x, y)‑position. Inga saknade imports, inga vaga “se dokumentationen”-genvägar—bara en självständig lösning som du kan lägga in i ditt projekt idag. + +> **Pro tip:** Om du använder ett annat OCR‑bibliotek, leta efter ett “structured” eller “layout”‑läge; koncepten är desamma. + +--- + +## Förutsättningar + +Innan vi dyker ner, se till att du har: + +| Krav | Varför det är viktigt | +|------|-----------------------| +| Python 3.9+ | Modern syntax och typ‑hints | +| `ocr`‑bibliotek som stödjer `OutputMode.STRUCTURED` (t.ex. ett fiktivt `myocr`) | Behövs för bounding‑box‑data | +| En AI‑efterbehandlingsmodul (kan vara OpenAI, HuggingFace eller en anpassad modell) | Förbättrar noggrannheten efter OCR | +| En bildfil (`input.png`) i din arbetskatalog | Källan vi läser | + +Om något av detta låter obekant, installera bara platshållarpaketen med `pip install myocr ai‑postproc`. Koden nedan innehåller också fallback‑stubb så att du kan testa flödet utan de riktiga biblioteken. + +## Steg 1: Aktivera strukturerat utdata‑läge för OCR‑motorn + +Det första vi gör är att tala om för OCR‑motorn att ge oss mer än bara vanlig text. Strukturerat utdata returnerar varje ord tillsammans med dess bounding‑box och förtroendescore, vilket är avgörande för **extrahera text med koordinater** senare på. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Varför detta är viktigt:* Utan strukturerat läge får du bara en lång sträng, och du förlorar den rumsliga informationen du behöver för att överlagra text på bilder eller mata in i efterföljande layout‑analys. + +## Steg 2: Känn igen bilden och fånga ord, rutor och förtroende + +Nu matar vi bilden i motorn. Resultatet är ett objekt som innehåller en lista med ord‑objekt, där varje exponerar `text`, `x`, `y`, `width`, `height` och `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Edge case:* Om bilden är tom eller oläsbar, kommer `structured_result.words` att vara en tom lista. Det är god praxis att kontrollera detta och hantera det på ett smidigt sätt. + +## Steg 3: Kör AI‑baserad efterbehandling samtidigt som positioner bevaras + +Även de bästa OCR‑motorerna gör misstag—tänk på “O” vs. “0” eller saknade diakritiska tecken. En AI‑modell tränad på domänspecifik text kan korrigera dessa fel. Avgörande är att vi behåller de ursprungliga koordinaterna så att den rumsliga layouten förblir intakt. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Varför vi bevarar koordinater:* Många efterföljande uppgifter (t.ex. PDF‑generering, AR‑märkning) förlitar sig på exakt placering. AI:n rör endast `text`‑fältet och lämnar `x`, `y`, `width`, `height` orörda. + +## Steg 4: Iterera över de korrigerade orden och visa deras text med koordinater + +Till sist loopar vi igenom de korrigerade orden och skriver ut varje ord tillsammans med dess övre‑vänstra hörn `(x, y)`. Detta uppfyller målet att **extrahera text med koordinater**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Förväntad utskrift (exempel):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Varje rad visar det korrigerade ordet och dess exakta plats på den ursprungliga bilden. + +## Fullt fungerande exempel + +Nedan är ett enda skript som binder ihop allt. Du kan kopiera‑klistra in det, justera import‑satserna så att de matchar dina faktiska bibliotek, och köra det direkt. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Kör skriptet** + +```bash +python ocr_postprocess_demo.py +``` + +Om du har de riktiga biblioteken installerade kommer skriptet att bearbeta din `input.png`. Annars låter stub‑implementationen dig se det förväntade flödet och utskriften utan några externa beroenden. + +## Vanliga frågor (FAQ) + +| Fråga | Svar | +|-------|------| +| *Fungerar detta med Tesseract?* | Tesseract i sig exponerar inte ett strukturerat läge direkt, men omslag som `pytesseract.image_to_data` returnerar bounding‑boxes som du kan mata in i samma AI‑efterbehandlare. | +| *Vad händer om jag behöver det nedre‑högra hörnet istället för det övre‑vänstra?* | Varje ord‑objekt ger också `width` och `height`. Beräkna `x2 = x + width` och `y2 = y + height` för att få det motsatta hörnet. | +| *Kan jag batch‑processa flera bilder?* | Absolut. Wrappa stegen i en `for image_path in Path("folder").glob("*.png"):`‑loop och samla resultat per fil. | +| *Hur väljer jag en AI‑modell för korrigering?* | För generisk text fungerar en liten GPT‑2 fin‑justerad på OCR‑fel. För domänspecifik data (t.ex. medicinska recept) tränas en sekvens‑till‑sekvens‑modell på parade brusiga‑rena data. | +| *Är förtroendescore användbart efter AI‑korrigering?* | Du kan fortfarande behålla den ursprungliga confidence för felsökning, men AI:n kan ge sin egen confidence om modellen stödjer det. | + +## Edge Cases & Bästa praxis + +1. **Tomma eller korrupta bilder** – verifiera alltid att `structured_result.words` inte är tomt innan du fortsätter. +2. **Icke‑latinska skript** – säkerställ att din OCR‑motor är konfigurerad för målspråket; AI‑efterbehandlare måste vara tränad på samma skript. +3. **Prestanda** – AI‑korrigering kan vara dyrt. Cacha resultat om du återanvänder samma bild, eller kör AI‑steget asynkront. +4. **Koordinatsystem** – OCR‑bibliotek kan använda olika origo (övre‑vänster vs. nedre‑vänster). Justera därefter när du överlagrar på PDF‑filer eller canvas. + +## Slutsats + +Du har nu ett gediget, end‑to‑end‑recept för **how to post‑process OCR** och pålitligt **extrahera text med koordinater**. Genom att aktivera strukturerat utdata, skicka resultatet genom ett AI‑korrigeringslager och bevara de ursprungliga bounding‑boxes kan du förvandla brusiga OCR‑skanningar till ren, rumsligt medveten text redo för efterföljande uppgifter som PDF‑generering, automatisering av datainmatning eller förstärkta‑realitets‑överlappningar. + +Redo för nästa steg? Prova att byta ut stub‑AI:n mot ett OpenAI `gpt‑4o‑mini`‑anrop, eller integrera pipelinen i en FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/swedish/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..d2d600e3d --- /dev/null +++ b/ocr/swedish/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-26 +description: Hur man snabbt känner igen bilder med Python. Lär dig en bildigenkänningspipeline, + batchbearbetning och automatisera bildigenkänning med AI. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: sv +og_description: Hur man snabbt känner igen bilder med Python. Denna guide går igenom + en bildigenkänningspipeline, batchning och automatisering med AI. +og_title: Hur man känner igen bilder – Automatisera en bildigenkänningspipeline +tags: +- image-processing +- python +- ai +title: Hur man känner igen bilder – Automatisera en bildigenkänningspipeline +url: /sv/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hur man känner igen bilder – Automatisera en bildigenkänningspipeline + +Har du någonsin undrat **hur man känner igen bilder** utan att skriva tusen rader kod? Du är inte ensam—många utvecklare stöter på samma hinder när de för första gången måste bearbeta dussintals eller hundratals bilder. Den goda nyheten? Med några enkla steg kan du sätta upp en komplett bildigenkänningspipeline som batchar, kör och rensar upp allt automatiskt. + +I den här handledningen går vi igenom ett komplett, körbart exempel som visar **hur man batchar bilder**, matar varje bild till en AI‑motor, efterbehandlar resultaten och slutligen frigör resurser. I slutet har du ett självständigt skript som du kan släppa in i vilket projekt som helst, oavsett om du bygger en fotomärkare, ett kvalitetskontrollsystem eller en forskningsdatamängdsgenerator. + +## Vad du kommer att lära dig + +- **Hur man känner igen bilder** med en mock AI‑motor (mönstret är identiskt för riktiga tjänster som TensorFlow, PyTorch eller moln‑API:er). +- Hur man bygger en **image recognition pipeline** som hanterar batchar effektivt. +- Det bästa sättet att **automate image recognition** så att du inte behöver loopa manuellt över filer varje gång. +- Tips för att skala pipelinen och frigöra resurser på ett säkert sätt. + +> **Förutsättningar:** Python 3.8+, grundläggande kunskap om funktioner och loopar, samt ett fåtal bildfiler (eller sökvägar) du vill bearbeta. Inga externa bibliotek krävs för kärnexemplet, men vi nämner var du kan ansluta riktiga AI‑SDK:er. + +![Diagram över hur man känner igen bilder i en batch‑bearbetningspipeline](pipeline.png "Diagram över hur man känner igen bilder") + +## Steg 1: Batcha dina bilder – Hur man batchar bilder effektivt + +Innan AI:n gör något tungt arbete behöver du en samling bilder att mata in den med. Tänk på detta som din inköpslista; motorn kommer senare att plocka varje vara från listan en efter en. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Varför batcha?** +Batchning minskar mängden boilerplate‑kod du skriver och gör det enkelt att lägga till parallellism senare. Om du någonsin behöver bearbeta 10 000 bilder ändrar du bara källan till `image_batch`—resten av pipelinen förblir oförändrad. + +## Steg 2: Kör bildigenkänningspipeline (Känn igen bilder med AI) + +Nu kopplar vi batchen till den faktiska igenkännaren. I ett verkligt scenario kan du anropa `torchvision.models` eller en moln‑endpoint; här mockar vi beteendet så att handledningen förblir självständig. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Förklaring:** +- `engine.recognize_image` är hjärtat i **image recognition pipeline**; den kan vara ett anrop till en deep‑learning‑modell eller ett REST‑API. +- `postprocessor.run` demonstrerar **automate image recognition** genom att normalisera råa prediktioner till en ren dictionary som du kan lagra eller strömma. +- Vi samlar varje `corrected`‑dictionary i `recognized_results` så att efterföljande steg (t.ex. databas‑insättning) blir enkla. + +## Steg 3: Efterbehandla och lagra – Automatisera bildigenkänningsresultat + +Efter att du har en prydlig lista med prediktioner vill du vanligtvis persistera dem. Exemplet nedan skriver en CSV‑fil; byt gärna ut mot en databas eller meddelandekö. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Varför en CSV?** +CSV är universellt läsbar—Excel, pandas, till och med enkla textredigerare kan öppna den. Om du senare behöver **automate image recognition** i stor skala, ersätt skrivblocket med en bulk‑insättning i ditt datalake. + +## Steg 4: Rensa upp – Frigör AI‑resurser på ett säkert sätt + +Många AI‑SDK:er allokerar GPU‑minne eller startar worker‑trådar. Att glömma att frigöra dem kan leda till minnesläckor och tuffa krascher. Även om våra mock‑objekt inte behöver det, visar vi det korrekta mönstret. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +När skriptet körs skrivs en vänlig bekräftelse ut, vilket visar att pipelinen har avslutats på ett rent sätt. + +## Fullständigt fungerande skript + +När vi sätter ihop allt får du det kompletta, kopiera‑och‑klistra‑klara programmet: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Förväntad utskrift + +När du kör skriptet (förutsatt att de tre platshållarsökvägarna finns) kommer du att se något i stil med: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +Och den genererade `recognition_results.csv` kommer att innehålla: + +| image | label | confidence | +|---------------------|-------|------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Slutsats + +Du har nu ett gediget, end‑to‑end‑exempel på **hur man känner igen bilder** i Python, komplett med en **image recognition pipeline**, batch‑hantering och automatiserad efterbehandling. Mönstret skalar: byt ut mock‑klasserna mot en riktig modell, mata in en större `image_batch`, så har du en produktionsklar lösning. + +Vill du gå vidare? Prova dessa nästa steg: + +- Byt ut `MockEngine` mot en TensorFlow‑ eller PyTorch‑modell för riktiga prediktioner. +- Parallellisera loopen med `concurrent.futures.ThreadPoolExecutor` för att snabba upp stora batchar. +- Koppla CSV‑skrivaren till en molnlagrings‑bucket för att **automate image recognition** över distribuerade arbetare. + +Känn dig fri att experimentera, bryta saker och sedan fixa dem—det är så du verkligen behärskar bildigenkänningspipelines. Om du stöter på problem eller har idéer för förbättringar, lämna en kommentar nedan. Lycka till med kodandet! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/swedish/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..ab7cad145 --- /dev/null +++ b/ocr/swedish/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-04-26 +description: Maskera kreditkortsnummer snabbt med AsposeAI OCR‑efterbehandling. Lär + dig PCI‑efterlevnad, maskering med reguljära uttryck och datarengöring i en steg‑för‑steg‑handledning. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: sv +og_description: Maskera kreditkortsnummer i OCR‑resultat med AsposeAI. Denna handledning + täcker PCI‑efterlevnad, maskering med reguljära uttryck och datarengöring. +og_title: Maskera kreditkortsnummer – Fullständig guide för Python OCR‑efterbehandling +tags: +- OCR +- Python +- security +title: Maskera kreditkortsnummer i OCR‑utdata – Komplett Python‑guide +url: /sv/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maskera kreditkortsnummer – Komplett Python‑guide + +Har du någonsin behövt **maskera kreditkortsnummer** i text som kommer direkt från en OCR‑motor? Du är inte ensam. I reglerade branscher kan exponering av ett fullt PAN (Primary Account Number) leda till problem med PCI‑revisorer. Den goda nyheten? Med några rader Python och AsposeAI:s efterbehandlings‑hook kan du automatiskt dölja de åttonde siffrorna i mitten och hålla dig på den säkra sidan. + +I den här handledningen går vi igenom ett verkligt scenario: köra OCR på en kvittobild och sedan tillämpa en anpassad **OCR post‑processing**‑funktion som sanerar all PCI‑data. I slutet har du ett återanvändbart kodsnutt som du kan lägga in i vilket AsposeAI‑arbetsflöde som helst, samt ett antal praktiska tips för att hantera kantfall och skala lösningen. + +## Vad du kommer att lära dig + +- Hur man registrerar en anpassad post‑processor med **AsposeAI**. +- Varför en **regular expression masking**‑metod är både snabb och pålitlig. +- Grunderna i **PCI compliance** relaterat till datasanering. +- Sätt att utöka mönstret för flera kortformat eller internationella nummer. +- Förväntad output och hur man verifierar att maskeringen fungerade. + +> **Förutsättningar** – Du bör ha en fungerande Python 3‑miljö, Aspose.AI för OCR‑paketet installerat (`pip install aspose-ocr`), och en exempelbild (t.ex. `receipt.png`) som innehåller ett kreditkortsnummer. Inga andra externa tjänster krävs. + +--- + +## Steg 1: Definiera en post‑processor som maskerar kreditkortsnummer + +Kärnan i lösningen finns i en liten funktion som tar emot OCR‑resultatet, kör en **regular expression masking**‑rutin och returnerar den sanerade texten. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Varför detta fungerar:** +- Regex‑uttrycket `(\d{4})\d{8}(\d{4})` matchar exakt 16 på varandra följande siffror, det vanliga formatet för Visa, MasterCard och många andra. +- Genom att fånga de första och sista fyra siffrorna (`\1` och `\2`) bevarar vi tillräckligt med information för felsökning samtidigt som vi följer **PCI compliance**‑reglerna som förbjuder lagring av hela PAN. +- Ersättningen `\1****\2` döljer de känsliga åtta siffrorna i mitten och omvandlar `1234567812345678` till `1234****5678`. + +> **Proffstips:** Om du behöver stödja 15‑siffriga American Express‑nummer, lägg till ett andra mönster som `r'(\d{4})\d{6}(\d{5})'` och kör båda ersättningarna sekventiellt. + +--- + +## Steg 2: Initiera AsposeAI‑motorn + +Innan vi kan fästa vår post‑processor behöver vi en instans av OCR‑motorn. AsposeAI paketera OCR‑modellen och ett enkelt API för anpassad bearbetning. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Varför initiera här?** +Att skapa `AsposeAI`‑objektet en gång och återanvända det över flera bilder minskar overhead. Motorn cachar också språkmodeller, vilket snabbar upp efterföljande anrop—praktiskt när du skannar batcher av kvitton. + +--- + +## Steg 3: Registrera den anpassade maskeringsfunktionen + +AsposeAI exponerar en `set_post_processor`‑metod som låter dig ansluta vilken callable som helst. Vi skickar vår `mask_pci`‑funktion tillsammans med en valfri inställnings‑dictionary (tom för tillfället). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**Vad händer bakom kulisserna?** +När du senare anropar `run_postprocessor` kommer AsposeAI att skicka det råa OCR‑resultatet till `mask_pci`. Funktionen får ett lättviktigt objekt (`data`) som innehåller den igenkända texten, och du returnerar en ny sträng. Denna design håller kärn‑OCR‑delen intakt samtidigt som du kan verkställa **data sanitization**‑policyer på ett ställe. + +--- + +## Steg 4: Kör OCR på kvittobilden + +Nu när motorn vet hur den ska rensa outputen, matar vi den med en bild. För denna handledning antar vi att du redan har ett `engine`‑objekt konfigurerat med rätt språk‑ och upplösningsinställningar. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Tips:** Om du inte har ett förkonfigurerat objekt kan du skapa ett med: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +`recognize_image`‑anropet returnerar ett objekt vars `text`‑attribut innehåller den råa, omaskerade strängen. + +--- + +## Steg 5: Använd den registrerade post‑processorn + +Med den råa OCR‑datan i handen överlämnar vi den till AI‑instansen. Motorn kör automatiskt `mask_pci`‑funktionen som vi registrerade tidigare. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Varför använda `run_postprocessor` istället för att anropa funktionen manuellt?** +Att göra så håller arbetsflödet konsekvent, särskilt när du har flera post‑processorer (t.ex. stavningskontroll, språkdetection). AsposeAI köar dem i den ordning du registrerar dem, vilket garanterar deterministisk output. + +--- + +## Steg 6: Verifiera den sanerade outputen + +Till sist, låt oss skriva ut den sanerade texten och bekräfta att eventuella kreditkortsnummer är korrekt maskerade. + +```python +print(final_result.text) +``` + +**Förväntad output** (excerpt): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Om kvittot inte innehöll något kortnummer förblir texten oförändrad—inget att maskera, inget att oroa sig för. + +--- + +## Hantera kantfall och vanliga variationer + +### Flera kortnummer i ett dokument +Om ett kvitto innehåller mer än ett PAN (t.ex. ett lojalitetskort plus ett betalkort) kör regexen globalt och maskerar alla träffar automatiskt. Ingen extra kod behövs. + +### Icke‑standardformat +Ibland infogar OCR mellanslag eller bindestreck (`1234 5678 1234 5678` eller `1234-5678-1234-5678`). Utöka mönstret för att ignorera dessa tecken: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +Den tillagda `[ -]?` tolererar valfria mellanslag eller bindestreck mellan siffrablok. + +### Internationella kort +För 19‑siffriga PAN‑nummer som används i vissa regioner kan du bredda mönstret: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Kom bara ihåg att **PCI compliance** fortfarande kräver maskering av de mellersta siffrorna, oavsett längd. + +### Loggning av maskerade värden (valfritt) +Om du behöver revisionsspår, skicka en flagga via `custom_settings` och justera funktionen: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Registrera sedan med: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Fullt fungerande exempel (klar att kopiera och klistra in) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Att köra detta skript på ett kvitto som innehåller `4111111111111111` kommer att producera: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +Det är hela pipeline‑processen—från rå OCR till **data sanitization**—insvept i några rena rader Python. + +--- + +## Slutsats + +Vi har just visat hur du **maskerar kreditkortsnummer** i OCR‑resultat med AsposeAI:s efterbehandlings‑hook, en kortfattad regular‑expression‑rutin och ett antal bästa‑praxis‑tips för **PCI compliance**. Lösningen är helt självständig, fungerar med vilken bild som helst som OCR‑motorn kan läsa, och kan utökas för att täcka mer komplexa kortformat eller loggningskrav. + +Redo för nästa steg? Prova att kombinera denna mask med en **databasinsättnings**‑rutin som bara lagrar de sista fyra siffrorna för referens, eller integrera en **batch‑processor** som skannar en hel mapp med kvitton över natten. Du kan också utforska andra **OCR post‑processing**‑uppgifter som adressstandardisering eller språkdetection—varje följer samma mönster som vi använde här. + +Har du frågor om kantfall, prestanda eller hur du anpassar koden för ett annat OCR‑bibliotek? Lämna en kommentar nedan, så fortsätter vi samtalet. Lycka till med kodandet, och håll dig säker! + +![Diagram som visar hur maskering av kreditkortsnummer fungerar i en OCR‑pipeline](https://example.com/images/ocr-mask-flow.png "Diagram av OCR efterbehandlings‑maskeringsflöde") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/swedish/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..d16b24537 --- /dev/null +++ b/ocr/swedish/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-04-26 +description: Lär dig hur du mäter inferenstid i Python, laddar en GGUF-modell från + Hugging Face och optimerar GPU-användning för snabbare resultat. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: sv +og_description: Mät inferenstid i Python genom att ladda en GGUF-modell från Hugging + Face och finjustera GPU-lager för optimal prestanda. +og_title: Mät inferenstid – Ladda GGUF-modell och optimera GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Mät inferenstid – Ladda GGUF-modell & optimera GPU +url: /sv/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mät inferenstid – Ladda GGUF-modell & Optimera GPU + +Har du någonsin behövt **mäta inferenstid** för en stor språkmodell men varit osäker på var du ska börja? Du är inte ensam—många utvecklare stöter på samma problem när de först hämtar en GGUF‑fil från Hugging Face och försöker köra den på en blandad CPU/GPU‑miljö. + +I den här guiden går vi igenom **hur du laddar en GGUF-modell**, konfigurerar den för Hugging Face och **mäter inferenstid** med ett rent Python‑exempel. På vägen visar vi också hur du **optimerar inferens‑GPU**‑användning så att dina körningar blir så snabba som möjligt. Inga onödiga utsvävningar, bara en praktisk, end‑to‑end‑lösning som du kan kopiera‑klistra in idag. + +## Vad du kommer att lära dig + +- Hur du **konfigurerar en HuggingFace‑modell** med `AsposeAIModelConfig`. +- De exakta stegen för att **ladda en GGUF-modell** (`fp16`‑kvantisering) från Hugging Face‑hubben. +- Ett återanvändbart mönster för **tidtagning av Python‑kod** runt ett inferens‑anrop. +- Tips för att **optimera inferens‑GPU** genom att justera `gpu_layers`. +- Förväntad output och hur du verifierar att din tidtagning är rimlig. + +### Förutsättningar + +| Krav | Varför det är viktigt | +|------|-----------------------| +| Python 3.9+ | Modern syntax och typ‑hints. | +| `asposeai`‑paket (eller motsvarande SDK) | Tillhandahåller `AsposeAI` och `AsposeAIModelConfig`. | +| Tillgång till Hugging Face‑repo `bartowski/Qwen2.5-3B-Instruct-GGUF` | GGUF‑modellen vi ska ladda. | +| Ett GPU med minst 8 GB VRAM (valfritt men rekommenderat) | Möjliggör steget **optimera inferens‑GPU**. | + +Om du ännu inte har installerat SDK:n, kör: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![mäta inferenstid diagram](https://example.com/measure-inference-time.png){alt="mäta inferenstid diagram"} + +## Steg 1: Ladda GGUF‑modellen – Konfigurera HuggingFace‑modell + +Det första du behöver är ett korrekt konfigurationsobjekt som talar om för Aspose AI var modellen ska hämtas och hur den ska behandlas. Här **laddar vi en GGUF-modell** och **konfigurerar huggingface‑modell**‑parametrar. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Varför detta är viktigt:** +- `hugging_face_repo_id` pekar på den exakta GGUF‑filen på Hubben. +- `fp16` minskar minnesbandbredden samtidigt som den behåller största delen av modellens noggrannhet. +- `gpu_layers` är reglaget du justerar när du vill **optimera inferens‑GPU**‑prestanda; fler lager på GPU:n betyder vanligtvis lägre latens, förutsatt att du har tillräckligt med VRAM. + +## Steg 2: Skapa Aspose AI‑instansen + +Nu när modellen är beskriven skapar vi ett `AsposeAI`‑objekt. Detta steg är enkelt, men det är här SDK:n faktiskt laddar ner GGUF‑filen (om den inte redan finns i cache) och förbereder runtime‑miljön. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Pro‑tips:** Första körningen tar några sekunder längre eftersom modellen laddas ner och kompileras för GPU:n. Efterföljande körningar är blixtsnabba. + +## Steg 3: Kör inferens och **mät inferenstid** + +Här kommer hjärtat i tutorialen: vi omsluter inferens‑anropet med `time.time()` för att **mäta inferenstid**. Vi matar också in ett litet OCR‑resultat bara för att hålla exemplet självständigt. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Vad du bör se:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Om siffran känns hög kör du förmodligen de flesta lagren på CPU:n. Det leder oss till nästa steg. + +## Steg 4: **Optimera inferens‑GPU** – Justera `gpu_layers` + +Ibland är standardvärdet `gpu_layers=40` antingen för aggressivt (orsakar OOM) eller för konservativt (lämnar prestanda på bordet). Här är en snabb loop du kan använda för att hitta den optimala balansen: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Varför detta fungerar:** +- Varje anrop bygger om runtime‑miljön med en annan GPU‑allokering, så du kan se latens‑trade‑offen omedelbart. +- Loopen demonstrerar också **time python code** på ett återanvändbart sätt, vilket du kan anpassa för andra prestandatester. + +Typisk output på ett 16 GB RTX 3080‑kort kan se ut så här: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +Utifrån detta skulle du välja `gpu_layers=40` som den optimala punkten för den här hårvaran. + +## Fullt fungerande exempel + +Sammanfogat, här är ett komplett skript du kan lägga i en fil (`measure_inference.py`) och köra: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Kör det med: + +```bash +python measure_inference.py +``` + +Du bör se en sub‑sekund latens på ett rimligt GPU, vilket bekräftar att du framgångsrikt har **mätt inferenstid** och **optimerat inferens‑GPU**. + +--- + +## Vanliga frågor (FAQ) + +**Q: Fungerar detta med andra kvantiseringsformat?** +A: Absolut. Byt `hugging_face_quantization="int8"` (eller `q4_0` osv.) i konfigurationen och kör benchmarken igen. Förvänta dig en avvägning: lägre minnesanvändning kontra en liten noggrannhetsförlust. + +**Q: Vad händer om jag inte har ett GPU?** +A: Sätt `gpu_layers=0`. Koden faller tillbaka helt till CPU, och du kan fortfarande **mäta inferenstid**—förvänta dig bara högre siffror. + +**Q: Kan jag bara tidta modellens forward‑pass och exkludera efterbehandling?** +A: Ja. Anropa `ai_engine.run_model(...)` (eller motsvarande metod) direkt och omslut det anropet med `time.time()`. Mönstret för **time python code** förblir detsamma. + +--- + +## Slutsats + +Du har nu en komplett, kopiera‑och‑klistra‑lösning för att **mäta inferenstid** för en GGUF‑modell, **ladda gguf‑modell** från Hugging Face, och finjustera **optimera inferens‑GPU**‑inställningarna. Genom att justera `gpu_layers` och experimentera med kvantisering kan du pressa varje millisekund av prestanda. + +Nästa steg kan vara att: + +- Integrera denna tidtagningslogik i en CI‑pipeline för att fånga regressions‑buggar. +- Utforska batch‑inferens för att ytterligare förbättra genomströmning. +- Kombinera modellen med en riktig OCR‑pipeline istället för den dummy‑text vi använde här. + +Lycka till med kodandet, och må dina latens‑tal alltid hålla sig låga! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/swedish/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..dce7fd199 --- /dev/null +++ b/ocr/swedish/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-04-26 +description: Känn igen handskriven text med Pythons OCR-motor. Lär dig hur du extraherar + text från en bild, slår på handskriftsläge och snabbt läser handskrivna anteckningar. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: sv +og_description: Känn igen handskriven text med Python. Denna handledning visar hur + du extraherar text från en bild, aktiverar handskriftsläge och läser handskrivna + anteckningar med en enkel OCR-motor. +og_title: Känn igen handskriven text i Python – Komplett OCR-guide +tags: +- OCR +- Python +- Handwriting Recognition +title: Känn igen handskriven text i Python – OCR-motorhandledning +url: /sv/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# känna igen handskriven text i Python – OCR Engine Tutorial + +Har du någonsin behövt **recognize handwritten text** men känt dig fast på “var börjar jag?”? Du är inte ensam. Oavsett om du digitaliserar mötesklotter eller extraherar data från ett skannat formulär, kan det kännas som att jaga en enhörning att få ett pålitligt OCR‑resultat. + +God nyhet: med bara några rader Python kan du **extract text from image**‑filer, **turn on handwritten mode**, och slutligen **read handwritten notes** utan att leta efter obskyra bibliotek. I den här guiden går vi igenom hela processen, från **create OCR engine python**‑liknande setup till att skriva ut resultatet på skärmen. + +## Vad du kommer att lära dig + +- Hur du skapar en **create OCR engine python**‑instans med `ocr`‑paketet. +- Vilken språkinställning som ger inbyggt stöd för handskrift. +- Det exakta anropet för att **turn on handwritten mode** så att motorn vet att du hanterar kursiv handskrift. +- Hur du matar in en bild av en anteckning och **recognize handwritten text** från den. +- Tips för att hantera olika bildformat, felsöka vanliga fallgropar och utöka lösningen. + +Ingen onödig fluff, inga “se dokumentationen” återvändsgränder—bara ett komplett, körbart skript som du kan kopiera‑klistra in och testa idag. + +## Förutsättningar + +1. Python 3.8+ installerat (koden använder f‑strings). +2. Det hypotetiska `ocr`‑biblioteket (`pip install ocr‑engine` – ersätt med det faktiska paketnamnet du använder). +3. En tydlig bildfil av en handskriven anteckning (JPEG, PNG eller TIFF fungerar). +4. En måttlig mängd nyfikenhet—allt annat täcks nedan. + +> **Pro tip:** Om din bild är brusig, kör ett snabbt förbehandlingssteg med Pillow (t.ex. `Image.open(...).convert('L')`) innan du skickar den till OCR‑motorn. Det ökar ofta noggrannheten. + +## Så här känner du igen handskriven text med Python + +Nedan är hela skriptet som **creates OCR engine python**‑objekt, konfigurerar dem för handskrift och skriver ut den extraherade strängen. Spara det som `handwriting_ocr.py` och kör det från din terminal. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Förväntad output + +När skriptet körs framgångsrikt kommer du att se något liknande: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Om OCR‑motorn inte kan upptäcka några tecken blir `text`‑fältet en tom sträng. I så fall, dubbelkolla bildkvaliteten eller prova en skanning med högre upplösning. + +## Steg‑för‑steg‑förklaring + +### Steg 1 – **create OCR engine python**‑instans + +`OcrEngine`‑klassen är startpunkten. Tänk på den som en tom anteckningsbok—inget händer förrän du talar om vilket språk som förväntas och om du hanterar handskrift. + +### Steg 2 – Välj ett språk som stödjer handskrift + +`ocr.Language.EXTENDED_LATIN` är inte bara “English”. Det samlar en uppsättning latinbaserade skript och, avgörande, inkluderar modeller tränade på kursiva exempel. Att hoppa över detta steg leder ofta till förvrängd output eftersom motorn standardmässigt använder en modell för tryckt text. + +### Steg 3 – **turn on handwritten mode** + +Att anropa `enable_handwritten_mode(True)` växlar en intern flagga. Motorn byter sedan till sitt neurala nätverk som är fininställt för den oregelbundna avståndet och variabla penseldrag du ser i verkliga anteckningar. Att glömma denna rad är ett vanligt misstag; motorn kommer att behandla dina klotter som brus. + +### Steg 4 – Mata in bilden och **recognize handwritten text** + +`recognize_image` gör det tunga arbetet: den förbehandlar bitmapen, kör den genom handskrift‑modellen och returnerar ett objekt med attributet `text`. Du kan också inspektera `handwritten_result.confidence` om du behöver ett kvalitetsmått. + +### Steg 5 – Skriv ut resultatet och **read handwritten notes** + +`print(handwritten_result.text)` är det enklaste sättet att verifiera att du framgångsrikt har **extract text from image**. I produktion skulle du troligen lagra strängen i en databas eller skicka den till en annan tjänst. + +## Hantera kantfall & vanliga variationer + +| Situation | Vad du ska göra | +|-----------|-----------------| +| **Bilden är roterad** | Använd Pillow för att rotera (`Image.rotate(angle)`) innan du anropar `recognize_image`. | +| **Låg kontrast** | Konvertera till gråskala och applicera adaptiv tröskelvärde (`Image.point(lambda p: p > 128 and 255)`). | +| **Flera sidor** | Loopa över en lista med filvägar och sammanfoga resultaten. | +| **Icke‑latin skript** | Ersätt `EXTENDED_LATIN` med `ocr.Language.CHINESE` (eller lämplig) och behåll `enable_handwritten_mode(True)`. | +| **Prestandaproblem** | Återanvänd samma `ocr_engine`‑instans för många bilder; att initiera den varje gång ger extra overhead. | + +### Pro tip om minnesanvändning + +Om du bearbetar hundratals anteckningar i ett batch, anropa `ocr_engine.dispose()` när du är klar. Det frigör inhemska resurser som Python‑omslaget kan hålla på. + +## Snabb visuell återblick + +![exempel på att känna igen handskriven text](https://example.com/handwritten-note.png "recognize handwritten text example") + +*Bilden ovan visar en typisk handskriven anteckning som vårt skript kan omvandla till vanlig text.* + +## Fullt fungerande exempel (en‑filsskript) + +För dig som älskar copy‑paste‑enkelhet, här är hela sak igen utan förklarande kommentarer: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Kör det med: + +```bash +python handwriting_ocr.py +``` + +Du bör nu se **recognize handwritten text**‑output i din konsol. + +## Slutsats + +Vi har precis gått igenom allt du behöver för att **recognize handwritten text** i Python—från ett fräscht **create OCR engine python**‑anrop, välja rätt språk, **turn on handwritten mode**, och slutligen **extract text from image** till **read handwritten notes**. + +I ett enda, självständigt skript kan du gå från ett suddigt foto av ett mötesklotter till ren, sökbar text. Nästa steg kan vara att föra output till en naturlig språk‑pipeline, lagra den i ett sökbart index, eller till och med skicka tillbaka den till en transkriptionstjänst för röst‑översättning. + +### Vad du kan göra härnäst? + +- **Batch processing:** Packa in skriptet i en loop för att hantera en mapp med skanningar. +- **Confidence filtering:** Använd `result.confidence` för att filtrera bort lågkvalitativa avläsningar. +- **Alternative libraries:** Om `ocr` inte är en perfekt match, utforska `pytesseract` med `--psm 13` för handskriftsläge. +- **UI integration:** Kombinera med Flask eller FastAPI för att erbjuda en webb‑baserad uppladdningstjänst. + +Har du frågor om ett specifikt bildformat eller behöver hjälp med att finjustera modellen? Lämna en kommentar nedan, och lycka till med kodandet! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/thai/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..88b1a7e4d --- /dev/null +++ b/ocr/thai/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-04-26 +description: เรียนรู้วิธีดาวน์โหลดโมเดล HuggingFace ด้วย Python และสกัดข้อความจากภาพด้วย + Python พร้อมปรับปรุงความแม่นยำของ OCR ด้วย Python โดยใช้ Aspose OCR Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: th +og_description: ดาวน์โหลดโมเดล HuggingFace สำหรับ Python และเพิ่มประสิทธิภาพให้กับ + pipeline OCR ของคุณ ตามคำแนะนำนี้เพื่อดึงข้อความจากรูปภาพด้วย Python และปรับปรุงความแม่นยำของ + OCR ด้วย Python. +og_title: ดาวน์โหลดโมเดล HuggingFace ด้วย Python – คู่มือการปรับปรุง OCR อย่างสมบูรณ์ +tags: +- OCR +- HuggingFace +- Python +- AI +title: ดาวน์โหลดโมเดล HuggingFace ด้วย Python – คู่มือขั้นตอนต่อขั้นตอนเพื่อเพิ่มประสิทธิภาพ + OCR +url: /th/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – คู่มือการปรับปรุง OCR อย่างสมบูรณ์ + +เคยลอง **download HuggingFace model python** แล้วรู้สึกสับสนบ้างไหม? คุณไม่ได้เป็นคนเดียว ในหลายโครงการอุปสรรคใหญ่ที่สุดคือการนำโมเดลที่ดีมาลงบนเครื่องของคุณและทำให้ผลลัพธ์ OCR มีประโยชน์จริง + +ในคู่มือนี้เราจะพาคุณผ่านตัวอย่างเชิงปฏิบัติที่แสดงให้เห็นอย่างชัดเจนว่า **download HuggingFace model python** ทำอย่างไร ดึงข้อความจากรูปภาพด้วย **extract text from image python** แล้ว **improve OCR accuracy python** ด้วย AI post‑processor ของ Aspose. เมื่อจบคุณจะมีสคริปต์พร้อมรันที่เปลี่ยนรูปใบแจ้งหนี้ที่มีเสียงรบกวนให้เป็นข้อความที่สะอาดและอ่านง่าย—ไม่มีเวทมนตร์ มีแต่ขั้นตอนที่ชัดเจน + +## สิ่งที่คุณต้องเตรียม + +- Python 3.9+ (โค้ดทำงานบน 3.11 ด้วยเช่นกัน) +- การเชื่อมต่ออินเทอร์เน็ตสำหรับการดาวน์โหลดโมเดลครั้งเดียว +- แพคเกจ `asposeocrcloud` (`pip install asposeocrcloud`) +- รูปภาพตัวอย่าง (เช่น `sample_invoice.png`) ที่วางไว้ในโฟลเดอร์ที่คุณควบคุม + +แค่นั้นเอง—ไม่มีเฟรมเวิร์กหนัก ๆ ไม่มีไดรเวอร์เฉพาะ GPU เว้นแต่คุณต้องการเร่งความเร็ว + +ตอนนี้มาลงลึกเข้าสู่การทำงานจริงกันเลย + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## ขั้นตอนที่ 1: ตั้งค่า OCR Engine และเลือกภาษา +*(นี่คือจุดที่เราจะเริ่ม **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**ทำไมเรื่องนี้ถึงสำคัญ:** +OCR engine คือแนวป้องกันแรก; การเลือก language pack ที่ถูกต้องช่วยลดข้อผิดพลาดการจดจำอักขระตั้งแต่ต้น ซึ่งเป็นส่วนสำคัญของ **improve OCR accuracy python**. + +## ขั้นตอนที่ 2: กำหนดค่า AsposeAI Model – ดาวน์โหลดจาก HuggingFace +*(นี่คือจุดที่เราจริง ๆ **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**อะไรกำลังเกิดขึ้นเบื้องหลัง?** +เมื่อ `allow_auto_download` เป็น true, SDK จะติดต่อ HuggingFace, ดึงโมเดล `Qwen2.5‑3B‑Instruct‑GGUF` มาและเก็บไว้ในโฟลเดอร์ที่คุณระบุ นี่คือหัวใจของ **download huggingface model python**—SDK ทำงานหนักให้คุณ ไม่ต้องเขียนคำสั่ง `git clone` หรือ `wget` เอง + +*Pro tip:* เก็บ `directory_model_path` ไว้บน SSD เพื่อให้โหลดเร็วขึ้น; โมเดลมีขนาดประมาณ 3 GB แม้ในรูปแบบ `int8`. + +## ขั้นตอนที่ 3: เชื่อมต่อ AI Engine กับ OCR Engine +*(เชื่อมสองส่วนนี้เพื่อให้เราสามารถ **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**ทำไมต้องผูกมันเข้าด้วยกัน?** +OCR engine ให้ข้อความดิบที่อาจมีการสะกดผิด, บรรทัดขาดหรือเครื่องหมายวรรคตอนไม่ถูกต้อง AI engine ทำหน้าที่เป็นบรรณาธิการอัจฉริยะ ทำความสะอาดปัญหาเหล่านั้น—ตรงกับสิ่งที่คุณต้องการเพื่อ **improve OCR accuracy python**. + +## ขั้นตอนที่ 4: รัน OCR บนรูปภาพของคุณ +*(นี่คือช่วงเวลาที่เราจริง ๆ **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` ตอนนี้มีแอตทริบิวต์ `text` ที่บรรจุตัวอักษรดิบที่ engine เห็น ในการใช้งานจริงคุณอาจเจอข้อผิดพลาดเล็กน้อย—เช่น “Invoice” กลายเป็น “Inv0ice” หรือมีการตัดบรรทัดกลางประโยค + +## ขั้นตอนที่ 5: ทำความสะอาดด้วย AI Post‑Processor +*(ขั้นตอนนี้ทำให้ **improve OCR accuracy python** โดยตรง.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +โมเดล AI จะเขียนข้อความใหม่โดยใช้การแก้ไขที่รับรู้ภาษา เนื่องจากเราใช้โมเดลที่ปรับจูนจาก HuggingFace ผลลัพธ์มักจะเป็นธรรมชาติและพร้อมสำหรับการประมวลผลต่อไป + +## ขั้นตอนที่ 6: แสดงผลก่อนและหลัง +*(การตรวจสอบอย่างรวดเร็วเพื่อดูว่าเราดึงข้อความจากรูปภาพและปรับปรุงความแม่นยำได้ดีแค่ไหน.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### ผลลัพธ์ที่คาดหวัง + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +สังเกตว่า AI แก้ “Inv0ice” เป็น “Invoice” และลบการตัดบรรทัดที่ไม่จำเป็น นี่คือผลลัพธ์ที่จับต้องได้ของ **improve OCR accuracy python** ด้วยโมเดล HuggingFace ที่ดาวน์โหลดมา + +## คำถามที่พบบ่อย (FAQ) + +### ฉันต้องการ GPU เพื่อรันโมเดลหรือไม่? +ไม่จำเป็น การตั้งค่า `gpu_layers=20` บอก SDK ให้ใช้ GPU สูงสุด 20 ชั้นหากมี GPU ที่รองรับ; หากไม่มีจะกลับไปใช้ CPU บนแล็ปท็อปสมัยใหม่ CPU ยังประมวลผลหลายร้อยโทเคนต่อวินาทีได้ดีพอสำหรับการแยกใบแจ้งหนี้เป็นครั้งคราว + +### ถ้าโมเดลไม่สามารถดาวน์โหลดได้จะทำอย่างไร? +ตรวจสอบให้แน่ใจว่าสภาพแวดล้อมของคุณเข้าถึง `https://huggingface.co` ได้ หากอยู่หลังพร็อกซีขององค์กรให้ตั้งค่า environment variables `HTTP_PROXY` และ `HTTPS_PROXY`. SDK จะลองใหม่อัตโนมัติ, หรือคุณสามารถทำ `git lfs pull` เองเพื่อดึงรีโปไปยัง `directory_model_path` + +### ฉันสามารถเปลี่ยนโมเดลเป็นรุ่นที่เล็กลงได้หรือไม่? +ได้เลย เพียงเปลี่ยนค่า `hugging_face_repo_id` เป็นรีโปอื่น (เช่น `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) แล้วปรับ `hugging_face_quantization` ให้สอดคล้อง โมเดลเล็กจะดาวน์โหลดเร็วกว่าและใช้ RAM น้อยกว่า แต่คุณอาจสูญเสียคุณภาพการแก้ไขเล็กน้อย + +### วิธีนี้ช่วยฉัน **extract text from image python** ในโดเมนอื่นอย่างไร? +พายป์ไลน์เดียวกันใช้ได้กับใบเสร็จ, หนังสือเดินทาง หรือโน้ตมือเขียน เพียงเปลี่ยน language pack (`ocr.Language.FRENCH` เป็นต้น) และอาจใช้โมเดลที่ปรับจูนเฉพาะโดเมนจาก HuggingFace + +## โบนัส: การทำงานอัตโนมัติหลายไฟล์ + +หากคุณมีโฟลเดอร์ที่เต็มไปด้วยรูปภาพ ให้ใส่การเรียก OCR ไว้ในลูปง่าย ๆ: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +การเพิ่มเล็ก ๆ นี้ทำให้คุณ **download huggingface model python** ครั้งเดียว แล้วประมวลผลหลายไฟล์พร้อมกัน—เหมาะสำหรับการขยายขนาดพายป์ไลน์อัตโนมัติของเอกสาร + +## สรุป + +เราพาไปผ่านตัวอย่างครบวงจรจากต้นจนจบที่แสดงวิธี **download HuggingFace model python**, **extract text from image python**, และ **improve OCR accuracy python** ด้วย Aspose OCR Cloud และ AI post‑processor สคริปต์พร้อมรัน แนวคิดอธิบายครบถ้วน และคุณได้เห็นผลลัพธ์ก่อน‑หลังแล้วจึงมั่นใจว่าใช้งานได้ + +ต่อไปคุณอาจลองสลับโมเดล HuggingFace อื่น ๆ ทดลอง language pack เพิ่มเติม หรือส่งข้อความที่ทำความสะอาดแล้วเข้าสู่พายป์ไลน์ NLP ต่อ (เช่น การสกัด entity จากรายการในใบแจ้งหนี้) ไม่มีขีดจำกัด และพื้นฐานที่คุณสร้างไว้ตอนนี้แข็งแรง + +มีคำถามหรือรูปภาพที่ยังทำให้ OCR สับสน? แสดงความคิดเห็นด้านล่าง แล้วมาช่วยกันแก้ไขกันเถอะ Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/thai/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..daa891b6c --- /dev/null +++ b/ocr/thai/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-04-26 +description: ดาวน์โหลดโมเดล OCR อย่างรวดเร็วด้วย Aspose OCR Python. เรียนรู้วิธีตั้งค่าไดเรกทอรีโมเดล, + กำหนดเส้นทางโมเดล, และวิธีดาวน์โหลดโมเดลในไม่กี่บรรทัด. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: th +og_description: ดาวน์โหลดโมเดล OCR ในไม่กี่วินาทีด้วย Aspose OCR Python คู่มือนี้แสดงวิธีตั้งค่าไดเรกทอรีโมเดล + กำหนดเส้นทางโมเดล และวิธีดาวน์โหลดโมเดลอย่างปลอดภัย +og_title: ดาวน์โหลดโมเดล OCR – บทเรียน Aspose OCR Python อย่างครบถ้วน +tags: +- OCR +- Python +- Aspose +title: ดาวน์โหลดโมเดล OCR ด้วย Aspose OCR Python – คู่มือแบบขั้นตอนต่อขั้นตอน +url: /th/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ดาวน์โหลดโมเดล ocr – Complete Aspose OCR Python Tutorial + +เคยสงสัยไหมว่า **download ocr model** ทำอย่างไรโดยใช้ Aspose OCR ใน Python โดยไม่ต้องค้นหาเอกสารยาว ๆ? คุณไม่ได้เป็นคนเดียว นักพัฒนาหลายคนเจออุปสรรคเมื่อโมเดลไม่มีอยู่ในเครื่องและ SDK แสดงข้อผิดพลาดที่ไม่ชัดเจน ข่าวดีคือ? วิธีแก้เพียงไม่กี่บรรทัด และคุณจะมีโมเดลพร้อมใช้งานในไม่กี่นาที + +ในบทแนะนำนี้เราจะพาคุณผ่านทุกอย่างที่ต้องรู้: ตั้งแต่การนำเข้าคลาสที่ถูกต้อง, **set model directory**, วิธี **how to download model**, และสุดท้ายการตรวจสอบเส้นทาง เมื่อจบคุณจะสามารถเรียกใช้ OCR บนรูปภาพใด ๆ ด้วยการเรียกฟังก์ชันเดียว และคุณจะเข้าใจตัวเลือก **configure model path** ที่ช่วยให้โปรเจกต์ของคุณเป็นระเบียบ ไม่ฟุ่มเฟือย มีเพียงตัวอย่างที่ทำงานได้จริงสำหรับผู้ใช้ **aspose ocr python** เท่านั้น + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีนำเข้าคลาส Aspose OCR Cloud อย่างถูกต้อง +- ขั้นตอนที่แม่นยำเพื่อ **download ocr model** อัตโนมัติ +- วิธี **set model directory** และ **configure model path** สำหรับการสร้างที่ทำซ้ำได้ +- วิธีตรวจสอบว่าโมเดลถูกเริ่มต้นและอยู่ที่ไหนบนดิสก์ +- จุดบกพร่องทั่วไป (สิทธิ์, โฟลเดอร์ที่หายไป) และวิธีแก้อย่างรวดเร็ว + +### ข้อกำหนดเบื้องต้น + +- Python 3.8+ ติดตั้งบนเครื่องของคุณ +- แพคเกจ `asposeocrcloud` (`pip install asposeocrcloud`) +- สิทธิ์การเขียนในโฟลเดอร์ที่คุณต้องการเก็บโมเดล (เช่น `C:\models` หรือ `~/ocr_models`) + +--- + +## Step 1: Import Aspose OCR Cloud Classes + +สิ่งแรกที่คุณต้องมีคือคำสั่ง import ที่ถูกต้อง ซึ่งจะดึงคลาสที่จัดการการตั้งค่าโมเดลและการทำ OCR มาใช้ + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*ทำไมเรื่องนี้สำคัญ:* `AsposeAI` คือเอนจินที่จะรัน OCR ส่วน `AsposeAIModelConfig` บอกเอนจินว่า **where** จะหาโมเดลและ **whether** ควรดาวน์โหลดอัตโนมัติ หากข้ามขั้นตอนนี้หรือ import โมดูลผิด จะเกิด `ModuleNotFoundError` ก่อนที่คุณจะถึงส่วนดาวน์โหลดเลย + +--- + +## Step 2: Define the Model Configuration (Set Model Directory & Configure Model Path) + +ตอนนี้เราบอก Aspose ว่าโมเดลไฟล์ควรเก็บไว้ที่ไหน นี่คือขั้นตอน **set model directory** และ **configure model path** + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**เคล็ดลับ & สิ่งต้องระวัง** + +- **Absolute paths** ช่วยหลีกเลี่ยงความสับสนเมื่อสคริปต์รันจากโฟลเดอร์ทำงานอื่น +- บน Linux/macOS คุณอาจใช้ `"/home/you/ocr_models"`; บน Windows ให้ใส่ prefix `r` เพื่อให้ backslashes ถูกตีความตามตัวอักษร +- การตั้งค่า `allow_auto_download="true"` คือกุญแจสำคัญสำหรับ **how to download model** โดยไม่ต้องเขียนโค้ดเพิ่มเติม + +--- + +## Step 3: Create the AsposeAI Instance Using the Configuration + +เมื่อกำหนดค่าพร้อมแล้ว ให้สร้างอินสแตนซ์ของเอนจิน OCR + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*ทำไมเรื่องนี้สำคัญ:* อ็อบเจ็กต์ `ocr_ai` ตอนนี้ถือการตั้งค่าที่เรากำหนดไว้ หากโมเดลไม่มีอยู่ การเรียกครั้งต่อไปจะทำให้ดาวน์โหลดอัตโนมัติ—นี่คือแกนหลักของ **how to download model** แบบไม่มีการแทรกแซง + +--- + +## Step 4: Trigger the Model Download (If Needed) + +ก่อนที่คุณจะรัน OCR ต้องแน่ใจว่าโมเดลอยู่บนดิสก์แล้ว เมธอด `is_initialized()` จะตรวจสอบและบังคับให้เริ่มต้น + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**สิ่งที่เกิดขึ้นเบื้องหลัง** + +- การเรียก `is_initialized()` ครั้งแรกคืนค่า `False` เพราะโฟลเดอร์โมเดลว่างเปล่า +- `print` แจ้งผู้ใช้ว่าการดาวน์โหลดกำลังจะเริ่ม +- การเรียกครั้งที่สองบังคับให้ Aspose ดึงโมเดลจากรีโพ Hugging Face ที่คุณระบุไว้ก่อนหน้า +- หลังดาวน์โหลดเสร็จ เมธอดจะคืนค่า `True` ในการตรวจสอบต่อ ๆ ไป + +**กรณีขอบ:** หากเครือข่ายของคุณบล็อก Hugging Face คุณจะเห็น exception ในกรณีนั้น ให้ดาวน์โหลดไฟล์ zip ของโมเดลด้วยตนเอง แยกไฟล์ลงใน `directory_model_path` แล้วรันสคริปต์ใหม่ + +--- + +## Step 5: Report the Local Path Where the Model Is Now Available + +หลังจากดาวน์โหลดเสร็จ คุณอาจต้องการรู้ว่าไฟล์อยู่ที่ไหน ซึ่งช่วยในการดีบักและตั้งค่า CI pipelines + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +ผลลัพธ์ที่พบบ่อยจะเป็นแบบนี้: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +ตอนนี้คุณได้ **download ocr model** สำเร็จ ตั้งค่าโฟลเดอร์ และยืนยันเส้นทางแล้ว + +--- + +## Visual Overview + +ด้านล่างเป็นแผนภาพง่าย ๆ ที่แสดงกระบวนการจากการตั้งค่าไปจนถึงโมเดลพร้อมใช้ + +![แผนภาพการไหลของการดาวน์โหลดโมเดล ocr แสดงการตั้งค่า, การดาวน์โหลดอัตโนมัติ, และเส้นทางในเครื่อง](/images/download-ocr-model-flow.png) + +*ข้อความแทนภาพรวมถึงคีย์เวิร์ดหลักสำหรับ SEO.* + +--- + +## Common Variations & How to Handle Them + +### 1. Using a Different Model Repository + +หากต้องการโมเดลอื่นนอกจาก `openai/gpt2` เพียงเปลี่ยนค่า `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +ตรวจสอบให้แน่ใจว่ารีโพเป็นสาธารณะหรือคุณได้ตั้งค่า token ที่จำเป็นใน environment แล้ว + +### 2. Disabling Automatic Download + +บางครั้งคุณต้องการควบคุมการดาวน์โหลดด้วยตนเอง (เช่นในสภาพแวดล้อมที่ไม่มีอินเทอร์เน็ต) ให้ตั้งค่า `allow_auto_download` เป็น `"false"` แล้วเรียกสคริปต์ดาวน์โหลดของคุณก่อนทำการเริ่มต้น: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Changing the Model Directory at Runtime + +คุณสามารถปรับเปลี่ยนเส้นทางได้โดยไม่ต้องสร้างอ็อบเจ็กต์ `AsposeAI` ใหม่: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Pro Tips for Production Use + +- **Cache the model**: เก็บโฟลเดอร์บนเครือข่ายแชร์ หากหลายบริการต้องใช้โมเดลเดียวกัน จะช่วยลดการดาวน์โหลดซ้ำ +- **Version pinning**: รีโพ Hugging Face อาจอัปเดต เพื่อล็อกเวอร์ชันให้ใส่ `@v1.0.0` ต่อท้าย repo ID (`"openai/gpt2@v1.0.0"`) +- **Permissions**: ตรวจสอบให้ผู้ใช้ที่รันสคริปต์มีสิทธิ์อ่าน/เขียนที่ `directory_model_path` บน Linux `chmod 755` มักเพียงพอ +- **Logging**: แทนที่ `print` ธรรมดาด้วยโมดูล `logging` ของ Python เพื่อให้การสังเกตในแอปขนาดใหญ่ทำได้ดียิ่งขึ้น + +--- + +## Full Working Example (Copy‑Paste Ready) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**ผลลัพธ์ที่คาดหวัง** (การรันครั้งแรกจะดาวน์โหลด, ครั้งต่อ ๆ ไปจะข้ามการดาวน์โหลด): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +รันสคริปต์อีกครั้ง; คุณจะเห็นเพียงบรรทัดเส้นทางเท่านั้น เพราะโมเดลถูกแคชไว้แล้ว + +--- + +## Conclusion + +เราได้ครอบคลุมกระบวนการทั้งหมดเพื่อ **download ocr model** ด้วย Aspose OCR Python แสดงวิธี **set model directory** และอธิบายรายละเอียดของ **configure model path** ด้วยไม่กี่บรรทัดของโค้ด คุณสามารถทำให้การดาวน์โหลดอัตโนมัติ หลีกเลี่ยงขั้นตอนมือและทำให้ pipeline OCR ของคุณทำซ้ำได้ + +ต่อไปคุณอาจอยากสำรวจการเรียก OCR จริง (`ocr_ai.recognize_image(...)`) หรือทดลองโมเดล Hugging Face อื่นเพื่อเพิ่มความแม่นยำ ไม่ว่าคุณจะทำอย่างไร พื้นฐานที่คุณสร้างไว้—การตั้งค่าชัดเจน, การดาวน์โหลดอัตโนมัติ, และการตรวจสอบเส้นทาง—จะทำให้การรวมระบบในอนาคตเป็นเรื่องง่าย + +มีคำถามเกี่ยวกับกรณีขอบ หรืออยากแชร์วิธีที่คุณปรับเปลี่ยนโฟลเดอร์โมเดลสำหรับการปรับใช้บนคลาวด์? แสดงความคิดเห็นด้านล่าง แล้วขอให้สนุกกับการเขียนโค้ด! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/thai/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..c2ace6c42 --- /dev/null +++ b/ocr/thai/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-04-26 +description: วิธีทำหลังการประมวลผลผลลัพธ์ OCR และดึงข้อความพร้อมพิกัด เรียนรู้วิธีแก้ปัญหาแบบขั้นตอนโดยใช้ผลลัพธ์เชิงโครงสร้างและการแก้ไขด้วย + AI. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: th +og_description: วิธีการประมวลผลผลลัพธ์ OCR หลังการสแกนและสกัดข้อความพร้อมพิกัด ปฏิบัติตามบทเรียนเชิงลึกนี้เพื่อกระบวนการทำงานที่เชื่อถือได้ +og_title: วิธีการประมวลผลต่อ OCR – คู่มือครบถ้วน +tags: +- OCR +- Python +- AI +- Text Extraction +title: วิธีการประมวลผลต่อ OCR – ดึงข้อความพร้อมพิกัดด้วย Python +url: /th/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีการประมวลผลต่อ OCR – ดึงข้อความพร้อมพิกัดใน Python + +เคยต้องการ **how to post‑process OCR** ผลลัพธ์หรือไม่ เพราะผลลัพธ์ดิบเต็มไปด้วยเสียงรบกวนหรือจัดตำแหน่งไม่ตรง? คุณไม่ได้เป็นคนเดียว ในหลายโครงการจริง—การสแกนใบแจ้งหนี้, การแปลงใบเสร็จเป็นดิจิทัล, หรือแม้กระทั่งการเสริมประสบการณ์ AR—เครื่อง OCR จะให้คำศัพท์ดิบแก่คุณ แต่คุณยังต้องทำความสะอาดและติดตามตำแหน่งของแต่ละคำบนหน้า นั่นคือจุดที่โหมดผลลัพธ์แบบโครงสร้างร่วมกับตัวประมวลผลหลังที่ขับเคลื่อนด้วย AI จะโดดเด่น + +ในบทแนะนำนี้ เราจะพาไปผ่าน pipeline Python ที่สมบูรณ์และสามารถรันได้ ซึ่ง **extracts text with coordinates** จากภาพ, รันขั้นตอนการแก้ไขด้วย AI, และพิมพ์แต่ละคำพร้อมตำแหน่ง (x, y) ของมัน ไม่มีการนำเข้าโค้ดที่ขาดหาย ไม่มีทางลัดแบบ “ดูเอกสาร” ที่คลุมเครือ—เพียงโซลูชันที่เป็นอิสระที่คุณสามารถนำไปใช้ในโปรเจกต์ของคุณได้ทันที + +> **เคล็ดลับ:** หากคุณใช้ไลบรารี OCR ที่แตกต่างกัน ให้มองหาโหมด “structured” หรือ “layout”; แนวคิดยังคงเหมือนเดิม. + +## ข้อกำหนดเบื้องต้น + +ก่อนที่เราจะเริ่มลงลึก ตรวจสอบให้แน่ใจว่าคุณมี: + +| ความต้องการ | เหตุผลที่สำคัญ | +|-------------|----------------| +| Python 3.9+ | ไวยากรณ์สมัยใหม่และ type hints | +| `ocr` library that supports `OutputMode.STRUCTURED` (e.g., a fictional `myocr`) | จำเป็นสำหรับข้อมูล bounding‑box | +| An AI post‑processing module (could be OpenAI, HuggingFace, or a custom model) | ปรับปรุงความแม่นยำหลัง OCR | +| An image file (`input.png`) in your working directory | แหล่งที่เราจะอ่าน | + +หากส่วนใดส่วนหนึ่งฟังดูแปลกใหม่ เพียงติดตั้งแพคเกจจำลองด้วย `pip install myocr ai‑postproc`. โค้ดด้านล่างยังรวม stub สำรองเพื่อให้คุณทดสอบการทำงานโดยไม่ต้องใช้ไลบรารีจริง + +## ขั้นตอนที่ 1: เปิดใช้งานโหมด Structured Output สำหรับ OCR Engine + +สิ่งแรกที่เราทำคือบอกให้ OCR engine ให้ข้อมูลมากกว่าข้อความธรรมดา Structured output จะคืนค่าคำแต่ละคำพร้อมกับ bounding box และคะแนนความมั่นใจ ซึ่งเป็นสิ่งจำเป็นสำหรับ **extract text with coordinates** ในภายหลัง. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*ทำไมสิ่งนี้ถึงสำคัญ:* หากไม่ได้เปิดโหมด structured คุณจะได้เพียงสตริงยาว ๆ และจะสูญเสียข้อมูลเชิงพื้นที่ที่จำเป็นสำหรับการวางข้อความบนภาพหรือการวิเคราะห์ layout ต่อไป + +## ขั้นตอนที่ 2: จดจำภาพและจับคำ, กล่อง, และความมั่นใจ + +ตอนนี้เราจะส่งภาพเข้า engine ผลลัพธ์เป็นอ็อบเจกต์ที่มีรายการของอ็อบเจกต์คำแต่ละตัว ซึ่งแต่ละอ็อบเจกต์จะเปิดเผย `text`, `x`, `y`, `width`, `height`, และ `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*กรณีขอบ:* หากภาพว่างหรืออ่านไม่ออก `structured_result.words` จะเป็นรายการว่าง ควรตรวจสอบและจัดการอย่างราบรื่น + +## ขั้นตอนที่ 3: รัน AI‑Based Post‑Processing พร้อมรักษาตำแหน่ง + +แม้ OCR engine ที่ดีที่สุดก็อาจทำผิดพลาด—เช่น “O” กับ “0” หรือการขาด diacritics โมเดล AI ที่ฝึกบนข้อความเฉพาะโดเมนสามารถแก้ไขข้อผิดพลาดเหล่านี้ได้ อย่างสำคัญ เราจะรักษาพิกัดเดิมไว้เพื่อให้ layout เชิงพื้นที่คงที่ + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*ทำไมเราถึงรักษาพิกัด:* งานต่อไปหลายอย่าง (เช่น การสร้าง PDF, การติดป้าย AR) พึ่งพาการวางตำแหน่งที่แม่นยำ AI จะทำการแก้ไขเฉพาะฟิลด์ `text` เท่านั้น ไม่กระทบ `x`, `y`, `width`, `height` + +## ขั้นตอนที่ 4: วนลูปผ่านคำที่แก้ไขและแสดงข้อความพร้อมพิกัด + +สุดท้าย เราจะวนลูปผ่านคำที่แก้ไขและพิมพ์แต่ละคำพร้อมมุมบน‑ซ้าย `(x, y)` ของมัน ซึ่งสอดคล้องกับเป้าหมาย **extract text with coordinates**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**ผลลัพธ์ที่คาดหวัง (ตัวอย่าง):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +แต่ละบรรทัดจะแสดงคำที่แก้ไขและตำแหน่งที่แน่นอนบนภาพต้นฉบับ + +## ตัวอย่างการทำงานเต็มรูปแบบ + +ด้านล่างเป็นสคริปต์เดียวที่เชื่อมทุกขั้นตอนเข้าด้วยกัน คุณสามารถคัดลอก‑วาง ปรับคำสั่ง import ให้ตรงกับไลบรารีของคุณ และรันได้โดยตรง + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**การรันสคริปต์** + +```bash +python ocr_postprocess_demo.py +``` + +หากคุณติดตั้งไลบรารีจริงสคริปต์จะประมวลผล `input.png` ของคุณ มิฉะนั้น การทำงานแบบ stub จะทำให้คุณเห็นกระบวนการและผลลัพธ์ที่คาดหวังโดยไม่มีการพึ่งพาไลบรารีภายนอก + +## คำถามที่พบบ่อย (FAQ) + +| คำถาม | คำตอบ | +|----------|--------| +| *ทำงานกับ Tesseract ได้หรือไม่?* | Tesseract เองไม่ได้เปิดโหมด structured โดยตรง แต่ wrapper อย่าง `pytesseract.image_to_data` จะคืนค่า bounding boxes ที่คุณสามารถส่งต่อไปยัง AI post‑processor เดียวกันได้. | +| *ถ้าต้องการมุมล่าง‑ขวาแทนมุมบน‑ซ้ายจะทำอย่างไร?* | แต่ละวัตถุคำยังให้ค่า `width` และ `height` ด้วย คำนวณ `x2 = x + width` และ `y2 = y + height` เพื่อให้ได้มุมตรงข้าม. | +| *ฉันสามารถประมวลผลหลายภาพเป็นชุดได้หรือไม่?* | ได้เลย. ห่อขั้นตอนทั้งหมดในลูป `for image_path in Path("folder").glob("*.png"):` แล้วเก็บผลลัพธ์ต่อไฟล์. | +| *ฉันจะเลือกโมเดล AI สำหรับการแก้ไขอย่างไร?* | สำหรับข้อความทั่วไป โมเดล GPT‑2 ขนาดเล็กที่ฝึกต่อบนข้อผิดพลาดของ OCR จะทำงานได้ สำหรับข้อมูลเฉพาะโดเมน (เช่น ใบสั่งยา) ให้ฝึกโมเดล sequence‑to‑sequence บนข้อมูลคู่ noisy‑clean. | +| *คะแนนความมั่นใจมีประโยชน์หลังการแก้ไขด้วย AI หรือไม่?* | คุณยังสามารถเก็บคะแนนความมั่นใจเดิมไว้เพื่อการดีบักได้ แต่ AI อาจให้คะแนนความมั่นใจของมันเองหากโมเดลรองรับ. | + +## กรณีขอบและแนวทางปฏิบัติที่ดีที่สุด + +1. **ภาพที่ว่างหรือเสียหาย** – ตรวจสอบเสมอว่า `structured_result.words` ไม่เป็นรายการว่างก่อนดำเนินการต่อ. +2. **สคริปต์ที่ไม่ใช่ละติน** – ตรวจสอบว่า OCR engine ของคุณตั้งค่าตามภาษาที่ต้องการ; AI post‑processor ต้องได้รับการฝึกบนสคริปต์เดียวกัน. +3. **ประสิทธิภาพ** – การแก้ไขด้วย AI อาจมีค่าใช้จ่ายสูง. แคชผลลัพธ์หากคุณจะใช้ภาพเดียวกันซ้ำ, หรือรันขั้นตอน AI แบบอะซิงโครนัส. +4. **ระบบพิกัด** – ไลบรารี OCR อาจใช้จุดเริ่มต้นที่ต่างกัน (บน‑ซ้าย vs. ล่าง‑ซ้าย). ปรับให้เหมาะสมเมื่อวางทับบน PDF หรือ canvas. + +## สรุป + +คุณมีสูตรครบวงจรสำหรับ **how to post‑process OCR** และ **extract text with coordinates** อย่างมั่นคงแล้ว ด้วยการเปิดใช้งาน structured output, ส่งผลลัพธ์ผ่านชั้นการแก้ไขด้วย AI, และรักษา bounding box ดั้งเดิม คุณสามารถเปลี่ยนสแกน OCR ที่มีเสียงรบกวนให้เป็นข้อความที่สะอาดและรับรู้เชิงพื้นที่ พร้อมใช้งานในงานต่อไปเช่น การสร้าง PDF, การอัตโนมัติการป้อนข้อมูล, หรือการวางข้อความเสริมในความเป็นจริงเสมือน + +พร้อมสำหรับขั้นตอนต่อไปหรือยัง? ลองเปลี่ยน stub AI เป็นการเรียก OpenAI `gpt‑4o‑mini`, หรือรวม pipeline นี้เข้ากับ FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/thai/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..d3577571e --- /dev/null +++ b/ocr/thai/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-26 +description: วิธีจดจำภาพอย่างรวดเร็วด้วย Python. เรียนรู้กระบวนการจดจำภาพ การประมวลผลแบบกลุ่ม + และทำให้การจดจำภาพเป็นอัตโนมัติด้วย AI. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: th +og_description: วิธีจดจำภาพอย่างรวดเร็วด้วย Python คู่มือนี้จะอธิบายขั้นตอนการทำงานของระบบจดจำภาพ + การทำเป็นชุด และการอัตโนมัติด้วย AI. +og_title: วิธีการจดจำภาพ – ทำให้กระบวนการจดจำภาพเป็นอัตโนมัติ +tags: +- image-processing +- python +- ai +title: วิธีจดจำภาพ – ทำให้กระบวนการจดจำภาพเป็นอัตโนมัติ +url: /th/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีจดจำภาพ – ทำให้กระบวนการจดจำภาพเป็นอัตโนมัติ + +เคยสงสัย **วิธีจดจำภาพ** โดยไม่ต้องเขียนโค้ดหลายพันบรรทัดหรือไม่? คุณไม่ได้เป็นคนเดียว—นักพัฒนาหลายคนเจออุปสรรคเดียวกันเมื่อต้องประมวลผลรูปภาพหลายสิบหรือหลายร้อยรูป ข่าวดีคือ? ด้วยขั้นตอนสั้น ๆ คุณสามารถสร้าง **pipeline การจดจำภาพ** ที่ทำการแบตช์, รัน, และทำความสะอาดโดยอัตโนมัติ + +ในบทเรียนนี้เราจะเดินผ่านตัวอย่างที่สมบูรณ์และสามารถรันได้ ซึ่งแสดง **วิธีแบตช์รูปภาพ**, ส่งแต่ละรูปไปยังเอ็นจิ้น AI, ประมวลผลผลลัพธ์, และสุดท้ายปล่อยทรัพยากร เมื่อเสร็จคุณจะได้สคริปต์ที่เป็นอิสระซึ่งสามารถนำไปใช้ในโปรเจกต์ใดก็ได้ ไม่ว่าจะเป็นการสร้างแท็กรูปภาพ, ระบบตรวจสอบคุณภาพ, หรือเครื่องมือสร้างชุดข้อมูลวิจัย + +## สิ่งที่คุณจะได้เรียนรู้ + +- **วิธีจดจำภาพ** ด้วยเอ็นจิ้น AI จำลอง (รูปแบบเดียวกันกับบริการจริงเช่น TensorFlow, PyTorch หรือ Cloud API) +- วิธีสร้าง **pipeline การจดจำภาพ** ที่จัดการแบตช์ได้อย่างมีประสิทธิภาพ +- วิธีที่ดีที่สุดในการ **ทำให้การจดจำภาพเป็นอัตโนมัติ** เพื่อไม่ต้องวนลูปไฟล์ด้วยตนเองทุกครั้ง +- เคล็ดลับการขยายขนาด pipeline และการปล่อยทรัพยากรอย่างปลอดภัย + +> **Prerequisites:** Python 3.8+, ความคุ้นเคยพื้นฐานกับฟังก์ชันและลูป, และไฟล์รูปภาพ (หรือพาธ) จำนวนหนึ่งที่คุณต้องการประมวลผล ไม่จำเป็นต้องใช้ไลบรารีภายนอกสำหรับตัวอย่างหลัก แต่เราจะกล่าวถึงจุดที่คุณสามารถเชื่อมต่อ SDK AI จริงได้ + +![แผนภาพการจดจำภาพในกระบวนการประมวลผลแบบแบตช์](pipeline.png "แผนภาพการจดจำภาพ") + +## ขั้นตอนที่ 1: แบตช์รูปภาพของคุณ – วิธีแบตช์รูปภาพอย่างมีประสิทธิภาพ + +ก่อนที่ AI จะทำงานหนักใด ๆ คุณต้องมีคอลเลกชันของรูปภาพเพื่อป้อนให้มัน คิดว่าเป็นรายการของของชำ; เอ็นจิ้นจะค่อย ๆ เลือกรายการออกมาทีละรายการ + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**ทำไมต้องแบตช์?** +การแบตช์ช่วยลดโค้ดซ้ำซ้อนและทำให้การเพิ่มการทำงานแบบขนานในภายหลังเป็นเรื่องง่าย หากคุณต้องประมวลผลรูปภาพ 10 000 รูป คุณเพียงเปลี่ยนแหล่งของ `image_batch` — ส่วนที่เหลือของ pipeline จะไม่ต้องแก้ไข + +## ขั้นตอนที่ 2: รัน Pipeline การจดจำภาพ (Recognize Images with AI) + +ต่อไปเราจะเชื่อมแบตช์เข้ากับตัวจดจำจริง ในสถานการณ์จริงคุณอาจเรียก `torchvision.models` หรือ endpoint ของคลาวด์; ที่นี่เราจำลองพฤติกรรมเพื่อให้บทเรียนเป็นอิสระ + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**คำอธิบาย:** +- `engine.recognize_image` คือหัวใจของ **pipeline การจดจำภาพ**; มันอาจเป็นการเรียกโมเดล deep‑learning หรือ REST API +- `postprocessor.run` แสดง **ทำให้การจดจำภาพเป็นอัตโนมัติ** โดยทำให้การพยากรณ์ดิบเป็นพจนานุกรมที่สะอาดและพร้อมจัดเก็บหรือสตรีม +- เราเก็บพจนานุกรม `corrected` แต่ละอันใน `recognized_results` เพื่อให้ขั้นตอนต่อไป (เช่น การแทรกลงฐานข้อมูล) ทำได้อย่างตรงไปตรงมา + +## ขั้นตอนที่ 3: ประมวลผลต่อและจัดเก็บ – ทำให้ผลลัพธ์การจดจำภาพเป็นอัตโนมัติ + +หลังจากได้รายการพยากรณ์ที่เรียบร้อยแล้ว คุณมักต้องการบันทึกไว้ ตัวอย่างด้านล่างเขียนไฟล์ CSV; คุณสามารถเปลี่ยนเป็นฐานข้อมูลหรือคิวข้อความได้ตามต้องการ + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**ทำไมต้องเป็น CSV?** +CSV สามารถอ่านได้โดยทั่วไประดับโลก—Excel, pandas, หรือแม้แต่โปรแกรมแก้ไขข้อความธรรมดาก็เปิดได้ หากคุณต้องการ **ทำให้การจดจำภาพเป็นอัตโนมัติ** ในระดับใหญ่ต่อไป เพียงเปลี่ยนบล็อกการเขียนเป็นการแทรกแบบ bulk ไปยัง data lake ของคุณ + +## ขั้นตอนที่ 4: ทำความสะอาด – ปล่อยทรัพยากร AI อย่างปลอดภัย + +SDK AI หลายตัวจะจองหน่วยความจำ GPU หรือสร้างเธรดทำงาน หากลืมปล่อยอาจทำให้เกิด memory leak และแครชได้ แม้ว่าวัตถุจำลองของเราไม่ต้องการ แต่เราจะสาธิตรูปแบบที่ถูกต้อง + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +การรันสคริปต์จะแสดงข้อความยืนยันที่เป็นมิตร บอกว่ากระบวนการได้เสร็จสิ้นอย่างเรียบร้อย + +## สคริปต์ทำงานเต็มรูปแบบ + +รวมทุกอย่างเข้าด้วยกัน นี่คือโปรแกรมที่พร้อมคัดลอก‑วาง + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### ผลลัพธ์ที่คาดหวัง + +เมื่อคุณรันสคริปต์ (สมมติว่ามีพาธาตัวอย่างสามพาธอยู่) คุณจะเห็นสิ่งคล้ายดังนี้ + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +และไฟล์ `recognition_results.csv` ที่สร้างขึ้นจะมีเนื้อหา: + +| ภาพ | ป้ายกำกับ | ความเชื่อมั่น | +|---------------------|-----------|----------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## สรุป + +คุณมีตัวอย่างครบวงจรของ **วิธีจดจำภาพ** ด้วย Python พร้อม **pipeline การจดจำภาพ**, การจัดการแบตช์, และการทำให้ผลลัพธ์เป็นอัตโนมัติ รูปแบบนี้สามารถขยายได้: เปลี่ยนคลาสจำลองเป็นโมเดลจริง, ป้อน `image_batch` ที่ใหญ่ขึ้น, และคุณจะได้โซลูชันพร้อมใช้งานในระดับผลิต + +อยากไปต่อ? ลองทำตามขั้นตอนต่อไปนี้: + +- แทนที่ `MockEngine` ด้วยโมเดล TensorFlow หรือ PyTorch เพื่อให้ได้การพยากรณ์จริง +- ทำให้ลูปทำงานแบบขนานด้วย `concurrent.futures.ThreadPoolExecutor` เพื่อเร่งความเร็วของแบตช์ขนาดใหญ่ +- เชื่อมตัวเขียน CSV เข้ากับ bucket ของคลาวด์เพื่อ **ทำให้การจดจำภาพเป็นอัตโนมัติ** ข้าม worker ที่กระจายอยู่ + +อย่ากลัวทดลอง, ทำให้พัง, แล้วแก้ไข—นี่คือวิธีที่คุณจะเชี่ยวชาญ pipeline การจดจำภาพอย่างแท้จริง หากเจออุปสรรคหรือมีไอเดียปรับปรุง แบ่งปันคอมเมนต์ด้านล่างได้เลย. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/thai/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..081d0d1b4 --- /dev/null +++ b/ocr/thai/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-26 +description: ปกปิดหมายเลขบัตรเครดิตอย่างรวดเร็วด้วยการประมวลผลหลัง OCR ของ AsposeAI + เรียนรู้การปฏิบัติตาม PCI, การปกปิดด้วย regular expression, และการทำความสะอาดข้อมูลในบทเรียนแบบขั้นตอนต่อขั้นตอน. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: th +og_description: ปกปิดหมายเลขบัตรเครดิตในผลลัพธ์ OCR ด้วย AsposeAI. บทเรียนนี้ครอบคลุมการปฏิบัติตามมาตรฐาน + PCI, การปกปิดด้วย regular expression, และการทำความสะอาดข้อมูล. +og_title: ซ่อนหมายเลขบัตรเครดิต – คู่มือการประมวลผลหลัง OCR ด้วย Python อย่างเต็มรูปแบบ +tags: +- OCR +- Python +- security +title: ซ่อนหมายเลขบัตรเครดิตในผลลัพธ์ OCR – คู่มือ Python ฉบับสมบูรณ์ +url: /th/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ซ่อนหมายเลขบัตรเครดิต – คู่มือ Python ฉบับสมบูรณ์ + +เคยต้องการ **ซ่อนหมายเลขบัตรเครดิต** ในข้อความที่มาจากเครื่อง OCR โดยตรงหรือไม่? คุณไม่ได้เป็นคนเดียว ในอุตสาหกรรมที่มีการควบคุม การเปิดเผย PAN (Primary Account Number) เต็มรูปแบบอาจทำให้คุณเจอปัญหากับผู้ตรวจสอบการปฏิบัติตาม PCI ข่าวดีคือ? ด้วยไม่กี่บรรทัดของ Python และ post‑processing hook ของ AsposeAI คุณสามารถซ่อนเลข 8 หลักตรงกลางโดยอัตโนมัติและอยู่ในความปลอดภัย + +ในบทแนะนำนี้ เราจะเดินผ่านสถานการณ์จริง: การทำ OCR บนภาพใบเสร็จ แล้วใช้ฟังก์ชัน **OCR post‑processing** แบบกำหนดเองที่ทำความสะอาดข้อมูล PCI ใด ๆ เมื่อเสร็จคุณจะได้สคริปต์ที่นำกลับมาใช้ใหม่ได้ซึ่งสามารถใส่ลงใน workflow ของ AsposeAI ใดก็ได้ พร้อมกับเคล็ดลับเชิงปฏิบัติเพื่อจัดการกับกรณีขอบและการขยายโซลูชัน + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีการลงทะเบียน post‑processor แบบกำหนดเองกับ **AsposeAI**. +- ทำไมวิธี **regular expression masking** ถึงเร็วและเชื่อถือได้. +- พื้นฐานของ **PCI compliance** ที่เกี่ยวข้องกับการทำความสะอาดข้อมูล. +- วิธีขยายรูปแบบเพื่อรองรับหลายรูปแบบบัตรหรือหมายเลขระหว่างประเทศ. +- ผลลัพธ์ที่คาดหวังและวิธีตรวจสอบว่าการซ่อนทำงานถูกต้องหรือไม่. + +> **Prerequisites** – คุณควรมีสภาพแวดล้อม Python 3 ที่ทำงานได้, ติดตั้งแพคเกจ Aspose.AI for OCR (`pip install aspose-ocr`), และมีภาพตัวอย่าง (เช่น `receipt.png`) ที่มีหมายเลขบัตรเครดิต ไม่จำเป็นต้องใช้บริการภายนอกอื่นใด + +--- + +## ขั้นตอนที่ 1: กำหนด Post‑Processor ที่ซ่อนหมายเลขบัตรเครดิต + +หัวใจของวิธีแก้ปัญหาอยู่ในฟังก์ชันเล็ก ๆ ที่รับผลลัพธ์ OCR, รันขั้นตอน **regular expression masking**, และคืนข้อความที่ทำความสะอาดแล้ว + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**ทำไมวิธีนี้ถึงได้ผล:** +- regex `(\d{4})\d{8}(\d{4})` จะจับตรงกับตัวเลขต่อเนื่อง 16 หลัก ซึ่งเป็นรูปแบบทั่วไปสำหรับ Visa, MasterCard และอื่น ๆ +- โดยการจับสี่หลักแรกและสี่หลักสุดท้าย (`\1` และ `\2`) เราเก็บข้อมูลเพียงพอสำหรับการดีบัก ในขณะเดียวกันก็สอดคล้องกับกฎ **PCI compliance** ที่ห้ามเก็บ PAN เต็มรูปแบบ +- การแทนที่ `\1****\2` จะซ่อนเลข 8 หลักตรงกลางที่เป็นข้อมูลสำคัญ ทำให้ `1234567812345678` กลายเป็น `1234****5678` + +> **Pro tip:** หากคุณต้องการรองรับหมายเลข American Express ที่มี 15 หลัก ให้เพิ่มรูปแบบที่สองเช่น `r'(\d{4})\d{6}(\d{5})'` และทำการแทนที่ทั้งสองแบบต่อเนื่องกัน + +--- + +## ขั้นตอนที่ 2: เริ่มต้น AsposeAI Engine + +ก่อนที่เราจะผูก post‑processor ของเรา เราต้องมีอินสแตนซ์ของ OCR engine. AsposeAI มีโมเดล OCR และ API อย่างง่ายสำหรับการประมวลผลแบบกำหนดเอง + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**ทำไมต้องเริ่มต้นที่นี่?** +การสร้างอ็อบเจ็กต์ `AsposeAI` ครั้งเดียวและนำกลับมาใช้ใหม่กับหลายภาพจะลดภาระการทำงาน เครื่องยังเก็บโมเดลภาษาไว้ในแคช ซึ่งทำให้การเรียกครั้งต่อไปเร็วขึ้น—สะดวกเมื่อคุณสแกนชุดใบเสร็จหลายใบ + +--- + +## ขั้นตอนที่ 3: ลงทะเบียนฟังก์ชันการซ่อนแบบกำหนดเอง + +AsposeAI มีเมธอด `set_post_processor` ที่ให้คุณเชื่อมต่อกับ callable ใดก็ได้ เราจะส่งฟังก์ชัน `mask_pci` ของเราพร้อมกับพจนานุกรมการตั้งค่า (ว่างเปล่าสำหรับตอนนี้) + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**เกิดอะไรขึ้นเบื้องหลัง?** +เมื่อคุณเรียก `run_postprocessor` ภายหลัง AsposeAI จะส่งผลลัพธ์ OCR ดิบให้กับ `mask_pci`. ฟังก์ชันจะรับอ็อบเจ็กต์น้ำหนักเบา (`data`) ที่มีข้อความที่รับรู้แล้ว และคุณจะคืนสตริงใหม่ การออกแบบนี้ทำให้ส่วนหลักของ OCR ไม่ถูกแก้ไขขณะเดียวกันคุณสามารถบังคับใช้แนวทาง **data sanitization** ในที่เดียว + +--- + +## ขั้นตอนที่ 4: รัน OCR บนภาพใบเสร็จ + +ตอนนี้ engine รู้วิธีทำความสะอาดผลลัพธ์แล้ว เราจะส่งภาพเข้าไป เพื่อความสะดวกในบทแนะนำนี้ เราจะสมมติว่าคุณมีอ็อบเจ็กต์ `engine` ที่ตั้งค่าภาษาและความละเอียดแล้ว + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**เคล็ดลับ:** หากคุณไม่มีอ็อบเจ็กต์ที่ตั้งค่าไว้ล่วงหน้า คุณสามารถสร้างได้ด้วย: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +การเรียก `recognize_image` จะคืนอ็อบเจ็กต์ที่มีแอตทริบิวต์ `text` ซึ่งเก็บสตริงดิบที่ยังไม่ได้ซ่อน + +--- + +## ขั้นตอนที่ 5: ใช้ Post‑Processor ที่ลงทะเบียนไว้ + +เมื่อได้ข้อมูล OCR ดิบแล้ว เราจะส่งต่อให้กับอินสแตนซ์ AI Engine Engine จะรันฟังก์ชัน `mask_pci` ที่เราลงทะเบียนไว้โดยอัตโนมัติ + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**ทำไมต้องใช้ `run_postprocessor` แทนการเรียกฟังก์ชันด้วยตนเอง?** +การทำเช่นนี้ทำให้ workflow สม่ำเสมอ โดยเฉพาะเมื่อคุณมี post‑processor หลายตัว (เช่น การตรวจสอบการสะกด, การตรวจจับภาษา) AsposeAI จะจัดคิวตามลำดับที่คุณลงทะเบียน เพื่อรับประกันผลลัพธ์ที่กำหนดได้ + +--- + +## ขั้นตอนที่ 6: ตรวจสอบผลลัพธ์ที่ทำความสะอาดแล้ว + +สุดท้าย เรามาพิมพ์ข้อความที่ทำความสะอาดแล้วและยืนยันว่าหมายเลขบัตรเครดิตใด ๆ ถูกซ่อนอย่างถูกต้อง + +```python +print(final_result.text) +``` + +**ผลลัพธ์ที่คาดหวัง** (ส่วนย่อย): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +หากใบเสร็จไม่มีหมายเลขบัตร ข้อความจะคงเดิม—ไม่มีอะไรต้องซ่อน ไม่มีอะไรต้องกังวล + +--- + +## การจัดการกรณีขอบและรูปแบบทั่วไป + +### หมายเลขบัตรหลายใบในเอกสารเดียว + +หากใบเสร็จมี PAN มากกว่าหนึ่ง (เช่น บัตรสมาชิกและบัตรชำระเงิน) regex จะทำงานทั่วทั้งข้อความและซ่อนทุกการจับคู่โดยอัตโนมัติ ไม่ต้องเขียนโค้ดเพิ่มเติม + +### รูปแบบที่ไม่เป็นมาตรฐาน + +บางครั้ง OCR จะใส่ช่องว่างหรือขีด (`1234 5678 1234 5678` หรือ `1234-5678-1234-5678`). ขยายรูปแบบเพื่อไม่สนใจอักขระเหล่านั้น: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +ส่วนเพิ่ม `[ -]?` จะยอมรับช่องว่างหรือขีดที่เป็นตัวเลือกระหว่างบล็อกตัวเลข + +### บัตรระหว่างประเทศ + +สำหรับ PAN 19 หลักที่ใช้ในบางภูมิภาค คุณสามารถขยายรูปแบบได้: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +จำไว้ว่า **PCI compliance** ยังต้องการการซ่อนเลขตรงกลาง ไม่ว่าความยาวจะเท่าใด + +### การบันทึกค่าที่ซ่อน (ทางเลือก) + +หากคุณต้องการบันทึกการตรวจสอบ ให้ส่งแฟล็กผ่าน `custom_settings` และปรับฟังก์ชัน: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +จากนั้นลงทะเบียนด้วย: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## ตัวอย่างทำงานเต็ม (พร้อมคัดลอก‑วาง) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +การรันสคริปต์นี้บนใบเสร็จที่มี `4111111111111111` จะให้ผลลัพธ์: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +นี่คือทั้งหมดของ pipeline—จาก OCR ดิบถึง **data sanitization**—ห่อหุ้มด้วยไม่กี่บรรทัดของ Python ที่สะอาด + +--- + +## สรุป + +เราได้แสดงวิธี **ซ่อนหมายเลขบัตรเครดิต** ในผลลัพธ์ OCR ด้วย post‑processing hook ของ AsposeAI, ขั้นตอน regular‑expression ที่กระชับ, และเคล็ดลับปฏิบัติที่ดีที่สุดสำหรับ **PCI compliance**. วิธีแก้ปัญหานี้เป็นอิสระเต็มรูปแบบ ทำงานกับภาพใด ๆ ที่ OCR engine สามารถอ่านได้ และสามารถขยายเพื่อรองรับรูปแบบบัตรที่ซับซ้อนหรือความต้องการบันทึกเพิ่มเติม + +พร้อมสำหรับขั้นตอนต่อไปหรือยัง? ลองเชื่อมต่อการซ่อนนี้กับขั้นตอน **database insertion** ที่เก็บเฉพาะสี่หลักสุดท้ายเพื่ออ้างอิง, หรือรวมกับ **batch processor** ที่สแกนโฟลเดอร์ใบเสร็จทั้งหมดในช่วงคืน คุณอาจสำรวจงาน **OCR post‑processing** อื่น ๆ เช่น การทำมาตรฐานที่อยู่หรือการตรวจจับภาษา—แต่ละงานใช้รูปแบบเดียวกับที่เราใช้ที่นี่ + +มีคำถามเกี่ยวกับกรณีขอบ, ประสิทธิภาพ, หรือวิธีปรับโค้ดให้เข้ากับไลบรารี OCR อื่น? แสดงความคิดเห็นด้านล่างและเราจะสนทนาต่อไป ขอให้เขียนโค้ดอย่างสนุกและปลอดภัย! + +![แผนภาพแสดงวิธีการซ่อนหมายเลขบัตรเครดิตทำงานใน pipeline ของ OCR](https://example.com/images/ocr-mask-flow.png "แผนภาพของการซ่อนในขั้นตอน post‑processing ของ OCR") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/thai/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..00ba908c9 --- /dev/null +++ b/ocr/thai/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-04-26 +description: เรียนรู้วิธีวัดเวลา inference ใน Python, โหลดโมเดล GGUF จาก Hugging Face + และเพิ่มประสิทธิภาพการใช้ GPU เพื่อให้ได้ผลลัพธ์ที่เร็วขึ้น. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: th +og_description: วัดเวลา inference ใน Python โดยโหลดโมเดล GGUF จาก Hugging Face และปรับแต่งชั้น + GPU เพื่อประสิทธิภาพที่ดีที่สุด. +og_title: วัดเวลาในการสรุปผล – โหลดโมเดล GGUF และเพิ่มประสิทธิภาพ GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: วัดเวลาอินเฟอเรนซ์ – โหลดโมเดล GGUF และเพิ่มประสิทธิภาพ GPU +url: /th/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วัดเวลา Inference – โหลดโมเดล GGUF & ปรับประสิทธิภาพ GPU + +เคยต้อง **วัดเวลา inference** สำหรับโมเดลภาษาใหญ่แต่ไม่รู้จะเริ่มจากตรงไหนหรือไม่? คุณไม่ได้อยู่คนเดียว—นักพัฒนาหลายคนเจออุปสรรคเดียวกันเมื่อต้องดึงไฟล์ GGUF จาก Hugging Face แล้วพยายามรันบนสภาพแวดล้อม CPU/GPU ผสม + +ในคู่มือนี้เราจะพาคุณผ่าน **วิธีโหลดโมเดล GGUF**, ตั้งค่าให้ทำงานกับ Hugging Face, และ **วัดเวลา inference** ด้วยโค้ด Python ที่เรียบง่าย พร้อมแสดงวิธี **ปรับประสิทธิภาพ inference GPU** เพื่อให้การรันของคุณเร็วที่สุด ไม่มีเนื้อหาเกินความจำเป็น เพียงโซลูชันครบวงจรที่คุณสามารถคัดลอก‑วางได้ทันที + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธี **ตั้งค่าโมเดล HuggingFace** ด้วย `AsposeAIModelConfig` +- ขั้นตอนที่แม่นยำในการ **โหลดโมเดล GGUF** (quantization `fp16`) จาก Hugging Face hub +- รูปแบบที่นำกลับมาใช้ใหม่สำหรับ **วัดเวลาโค้ด Python** รอบการเรียก inference +- เคล็ดลับเพื่อ **ปรับประสิทธิภาพ inference GPU** ด้วยการปรับ `gpu_layers` +- ตัวอย่างผลลัพธ์ที่คาดหวังและวิธีตรวจสอบว่าการวัดเวลาของคุณมีความสมเหตุสมผลหรือไม่ + +### ข้อกำหนดเบื้องต้น + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.9+ | ไวยากรณ์สมัยใหม่และ type hints | +| `asposeai` package (หรือ SDK ที่เทียบเท่า) | ให้บริการ `AsposeAI` และ `AsposeAIModelConfig` | +| การเข้าถึงรีโป Hugging Face `bartowski/Qwen2.5-3B-Instruct-GGUF` | โมเดล GGUF ที่เราจะโหลด | +| GPU ที่มี VRAM อย่างน้อย 8 GB (ไม่บังคับแต่แนะนำ) | เปิดใช้งานขั้นตอน **optimize inference GPU** | + +หากคุณยังไม่ได้ติดตั้ง SDK ให้รัน: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![measure inference time diagram](https://example.com/measure-inference-time.png){alt="แผนภาพการวัดเวลา inference"} + +## ขั้นตอนที่ 1: โหลดโมเดล GGUF – ตั้งค่าโมเดล HuggingFace + +สิ่งแรกที่คุณต้องมีคืออ็อบเจกต์การตั้งค่าที่บอก Aspose AI ว่าจะดึงโมเดลจากที่ไหนและจะจัดการอย่างไร ที่นี่เราจะ **โหลดโมเดล GGUF** และ **ตั้งค่าพารามิเตอร์ huggingface model** + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**ทำไมจึงสำคัญ:** +- `hugging_face_repo_id` ชี้ไปยังไฟล์ GGUF ที่ต้องการบน Hub +- `fp16` ลดการใช้แบนด์วิธของหน่วยความจำในขณะที่ยังคงรักษาความแม่นยำของโมเดลไว้ได้มาก +- `gpu_layers` เป็นตัวควบคุมที่คุณปรับเมื่ออยาก **optimize inference GPU**; การใส่เลเยอร์มากขึ้นบน GPU มักทำให้ latency ลดลง หากคุณมี VRAM เพียงพอ + +## ขั้นตอนที่ 2: สร้างอินสแตนซ์ Aspose AI + +เมื่อโมเดลถูกอธิบายแล้ว เราจะสร้างอ็อบเจกต์ `AsposeAI` ขั้นตอนนี้ตรงไปตรงมา แต่เป็นจุดที่ SDK ดาวน์โหลดไฟล์ GGUF (หากยังไม่ได้แคช) และเตรียม runtime + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**เคล็ดลับ:** การรันครั้งแรกอาจใช้เวลานานกว่าสักสองสามวินาที เพราะโมเดลกำลังถูกดาวน์โหลดและคอมไพล์สำหรับ GPU การรันต่อ ๆ ไปจะเร็วเหมือนแสง + +## ขั้นตอนที่ 3: รัน Inference และ **วัดเวลา Inference** + +นี่คือหัวใจของบทเรียน: ห่อการเรียก inference ด้วย `time.time()` เพื่อ **วัดเวลา inference** เราจะใส่ผลลัพธ์ OCR เล็ก ๆ เพื่อให้ตัวอย่างเป็นอิสระ + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**สิ่งที่คุณควรเห็น:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +หากค่าที่ได้สูงเกินไป แสดงว่าคุณอาจกำลังรันส่วนใหญ่บน CPU ซึ่งนำเราไปสู่ขั้นตอนต่อไป + +## ขั้นตอนที่ 4: **ปรับประสิทธิภาพ Inference GPU** – ปรับ `gpu_layers` + +บางครั้งค่าเริ่มต้น `gpu_layers=40` อาจรุนแรงเกินไป (ทำให้ OOM) หรืออ่อนเกินไป (ทำให้ประสิทธิภาพไม่เต็มที่) นี่คือลูปสั้น ๆ ที่คุณสามารถใช้หาจุดที่เหมาะสม: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**ทำไมวิธีนี้ถึงได้ผล:** +- ทุกการเรียกจะสร้าง runtime ใหม่ด้วยการจัดสรร GPU ที่ต่างกัน ทำให้คุณเห็นการเปลี่ยนแปลง latency ได้ทันที +- ลูปนี้ยังแสดงวิธี **time python code** ที่นำกลับมาใช้ใหม่ได้ ซึ่งคุณสามารถปรับใช้กับการทดสอบประสิทธิภาพอื่น ๆ + +ผลลัพธ์ทั่วไปบน RTX 3080 16 GB อาจมีลักษณะดังนี้: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +จากนั้นคุณอาจเลือก `gpu_layers=40` เป็นค่าที่เหมาะสมที่สุดสำหรับฮาร์ดแวร์นี้ + +## ตัวอย่างทำงานเต็มรูปแบบ + +รวมทุกอย่างเข้าด้วยกัน นี่คือสคริปต์เดียวที่คุณสามารถบันทึกเป็นไฟล์ (`measure_inference.py`) แล้วรันได้: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +รันด้วยคำสั่ง: + +```bash +python measure_inference.py +``` + +คุณควรเห็น latency ต่ำกว่า 1 วินาทีบน GPU ที่ดีพอ ซึ่งยืนยันว่าคุณได้ **วัดเวลา inference** และ **ปรับประสิทธิภาพ inference GPU** สำเร็จแล้ว + +--- + +## คำถามที่พบบ่อย (FAQs) + +**Q: วิธีนี้ทำงานกับรูปแบบ quantization อื่นได้หรือไม่?** +A: ทำได้แน่นอน เปลี่ยน `hugging_face_quantization="int8"` (หรือ `q4_0` ฯลฯ) ใน config แล้วรัน benchmark ใหม่ คาดว่าจะมีการแลกเปลี่ยนระหว่างการใช้หน่วยความจำน้อยลงกับความแม่นยำที่ลดลงเล็กน้อย + +**Q: ถ้าฉันไม่มี GPU จะทำอย่างไร?** +A: ตั้งค่า `gpu_layers=0` โค้ดจะทำงานทั้งหมดบน CPU และคุณยังสามารถ **วัดเวลา inference** ได้—แต่คาดว่าจะได้ค่าที่สูงกว่า + +**Q: ฉันสามารถวัดเฉพาะการ forward ของโมเดลโดยไม่รวม post‑processing ได้หรือไม่?** +A: ทำได้ ให้เรียก `ai_engine.run_model(...)` (หรือเมธอดที่เทียบเท่า) โดยตรงและห่อการเรียกนั้นด้วย `time.time()` รูปแบบสำหรับ **time python code** ยังคงเหมือนเดิม + +--- + +## สรุป + +ตอนนี้คุณมีโซลูชันครบชุดที่สามารถ **วัดเวลา inference** สำหรับโมเดล GGUF, **โหลด gguf model** จาก Hugging Face, และปรับแต่งการตั้งค่า **optimize inference GPU** ได้แล้ว โดยการปรับ `gpu_layers` และทดลอง quantization คุณสามารถบีบอัดประสิทธิภาพให้ได้ทุกมิลลิวินาที + +ขั้นตอนต่อไปที่คุณอาจทำคือ: + +- ผสานตรรกะการวัดเวลานี้เข้ากับ pipeline CI เพื่อจับ regression +- สำรวจการทำ batch inference เพื่อเพิ่ม throughput +- เชื่อมโมเดลกับ pipeline OCR จริงแทนข้อความจำลองที่ใช้ในตัวอย่างนี้ + +ขอให้เขียนโค้ดอย่างสนุกและ latency ของคุณต่ำตลอดไป! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/thai/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..f12d159dc --- /dev/null +++ b/ocr/thai/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-04-26 +description: จดจำข้อความที่เขียนด้วยมือโดยใช้ OCR engine ของ Python. เรียนรู้วิธีดึงข้อความจากภาพ, + เปิดโหมดการเขียนด้วยมือ, และอ่านโน้ตที่เขียนด้วยมือได้อย่างรวดเร็ว. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: th +og_description: จดจำข้อความที่เขียนด้วยมือด้วย Python. บทเรียนนี้แสดงวิธีดึงข้อความจากภาพ, + เปิดโหมดการเขียนด้วยมือ, และอ่านบันทึกที่เขียนด้วยมือโดยใช้เครื่องมือ OCR อย่างง่าย. +og_title: จดจำข้อความลายมือใน Python – คู่มือ OCR ครบวงจร +tags: +- OCR +- Python +- Handwriting Recognition +title: จดจำข้อความลายมือใน Python – บทเรียนเครื่องมือ OCR +url: /th/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# จดจำข้อความลายมือใน Python – บทแนะนำ OCR Engine + +เคยต้อง **จดจำข้อความลายมือ** แต่รู้สึกติดขัดที่ “จะเริ่มจากตรงไหนดี?” หรือไม่? คุณไม่ได้เป็นคนเดียว ไม่ว่าจะเป็นการแปลงบันทึกการประชุมเป็นดิจิทัลหรือดึงข้อมูลจากแบบฟอร์มที่สแกน ผลลัพธ์ OCR ที่เชื่อถือได้บางครั้งก็เหมือนตามหาม้ายในตำนาน + +ข่าวดี: ด้วยเพียงไม่กี่บรรทัดของ Python คุณสามารถ **extract text from image** ไฟล์, **turn on handwritten mode**, และสุดท้าย **read handwritten notes** ได้โดยไม่ต้องค้นหาห้องสมุดที่ซับซ้อน ในคู่มือนี้เราจะพาคุณผ่านกระบวนการทั้งหมด ตั้งแต่การตั้งค่าแบบ **create OCR engine python** จนถึงการพิมพ์ผลลัพธ์บนหน้าจอ + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธี **create OCR engine python** อินสแตนซ์โดยใช้แพ็กเกจ `ocr` +- การตั้งค่าภาษาที่มีการสนับสนุนลายมือโดยอัตโนมัติ +- คำสั่งที่แน่นอนเพื่อ **turn on handwritten mode** ให้เครื่องรู้ว่ากำลังจัดการกับลายมือ +- วิธีป้อนรูปภาพของบันทึกและ **recognize handwritten text** จากมัน +- เคล็ดลับการจัดการรูปแบบภาพต่าง ๆ, การแก้ปัญหาข้อผิดพลาดทั่วไป, และการขยายโซลูชัน + +ไม่มีเนื้อหาเกินความจำเป็น, ไม่มี “ดูเอกสาร” ที่ทำให้ติดขัด—เพียงสคริปต์ที่ทำงานได้เต็มรูปแบบที่คุณสามารถคัดลอก‑วางและทดสอบได้ทันที + +## ข้อกำหนดเบื้องต้น + +ก่อนที่เราจะลงลึก, ตรวจสอบให้แน่ใจว่าคุณมี: + +1. Python 3.8+ ติดตั้งอยู่ (โค้ดใช้ f‑strings) +2. ไลบรารี `ocr` สมมุติ (`pip install ocr‑engine` – แทนที่ด้วยชื่อแพ็กเกจจริงที่คุณใช้) +3. ไฟล์รูปภาพที่ชัดเจนของบันทึกลายมือ (รองรับ JPEG, PNG, หรือ TIFF) +4. ความอยากรู้อยากเห็นเล็กน้อย—ส่วนที่เหลือเราจะอธิบายให้ครบ + +> **Pro tip:** หากภาพของคุณมีสัญญาณรบกวน, ให้ทำขั้นตอนการเตรียมล่วงหน้าด้วย Pillow (เช่น `Image.open(...).convert('L')`) ก่อนส่งให้ OCR engine จะช่วยเพิ่มความแม่นยำได้อย่างมาก + +## วิธีจดจำข้อความลายมือด้วย Python + +ด้านล่างเป็นสคริปต์เต็มที่ **creates OCR engine python** objects, ตั้งค่าให้รองรับลายมือ, และพิมพ์ข้อความที่สกัดออกมา บันทึกเป็น `handwriting_ocr.py` แล้วรันจากเทอร์มินัลของคุณ + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### ผลลัพธ์ที่คาดหวัง + +เมื่อสคริปต์ทำงานสำเร็จ, คุณจะเห็นประมาณนี้: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +หาก OCR engine ไม่สามารถตรวจจับอักขระใด ๆ ได้, ฟิลด์ `text` จะเป็นสตริงว่าง ในกรณีนั้นให้ตรวจสอบคุณภาพของภาพหรือลองสแกนด้วยความละเอียดที่สูงขึ้น + +## คำอธิบายทีละขั้นตอน + +### ขั้นตอนที่ 1 – **create OCR engine python** อินสแตนซ์ + +คลาส `OcrEngine` คือจุดเริ่มต้น คิดว่าเป็นสมุดโน้ตเปล่า—ไม่มีอะไรเกิดขึ้นจนกว่าคุณจะบอกว่าต้องการภาษาที่คาดหวังและว่ากำลังจัดการกับลายมือหรือไม่ + +### ขั้นตอนที่ 2 – เลือกภาษาที่รองรับลายมือ + +`ocr.Language.EXTENDED_LATIN` ไม่ได้หมายถึงแค่ “English” เท่านั้น มันรวมชุดสคริปต์ที่อิงจากละตินและสำคัญที่สุดคือมีโมเดลที่ฝึกด้วยตัวอย่างลายมือ หากข้ามขั้นตอนนี้มักทำให้ผลลัพธ์เป็นข้อความที่อ่านไม่ออก เพราะเครื่องจะใช้โมเดลข้อความพิมพ์โดยอัตโนมัติ + +### ขั้นตอนที่ 3 – **turn on handwritten mode** + +การเรียก `enable_handwritten_mode(True)` จะสลับแฟล็กภายในเครื่องมือ ทำให้ engine เปลี่ยนไปใช้เครือข่ายประสาทเทียมที่ปรับแต่งสำหรับการเว้นระยะห่างและความกว้างของเส้นที่ไม่สม่ำเสมอในบันทึกจริง การลืมบรรทัดนี้เป็นข้อผิดพลาดที่พบบ่อย; engine จะถือว่าลายมือของคุณเป็นสัญญาณรบกวน + +### ขั้นตอนที่ 4 – ป้อนภาพและ **recognize handwritten text** + +`recognize_image` ทำงานหนักทั้งหมด: เตรียมบิตแมพ, ส่งผ่านโมเดลลายมือ, แล้วคืนออบเจ็กต์ที่มีแอตทริบิวต์ `text` คุณยังสามารถตรวจสอบ `handwritten_result.confidence` หากต้องการเมตริกคุณภาพ + +### ขั้นตอนที่ 5 – พิมพ์ผลลัพธ์และ **read handwritten notes** + +`print(handwritten_result.text)` เป็นวิธีที่ง่ายที่สุดในการยืนยันว่าคุณ **extract text from image** สำเร็จแล้ว ในการใช้งานจริงคุณอาจเก็บสตริงนี้ในฐานข้อมูลหรือส่งต่อให้บริการอื่นต่อไป + +## การจัดการกรณีขอบและความแปรผันทั่วไป + +| Situation | What to Do | +|-----------|------------| +| **Image is rotated** | ใช้ Pillow เพื่อหมุน (`Image.rotate(angle)`) ก่อนเรียก `recognize_image` | +| **Low contrast** | แปลงเป็นระดับสีเทาและใช้การทำ threshold แบบปรับตามสภาพ (`Image.point(lambda p: p > 128 and 255)`) | +| **Multiple pages** | วนลูปผ่านรายการไฟล์พาธและต่อผลลัพธ์เข้าด้วยกัน | +| **Non‑Latin scripts** | แทนที่ `EXTENDED_LATIN` ด้วย `ocr.Language.CHINESE` (หรือสคริปต์ที่เหมาะสม) และคง `enable_handwritten_mode(True)` | +| **Performance concerns** | ใช้อินสแตนซ์ `ocr_engine` เดียวกันหลายภาพ; การสร้างใหม่ทุกครั้งเพิ่มภาระงาน | + +### เคล็ดลับเกี่ยวกับการใช้หน่วยความจำ + +หากคุณประมวลผลหลายร้อยบันทึกเป็นชุด, เรียก `ocr_engine.dispose()` หลังจากเสร็จงาน จะช่วยปล่อยทรัพยากรเนทีฟที่ wrapper ของ Python อาจถือครองอยู่ + +## สรุปภาพอย่างรวดเร็ว + +![ตัวอย่างการจดจำข้อความลายมือ](https://example.com/handwritten-note.png "ตัวอย่างการจดจำข้อความลายมือ") + +*ภาพด้านบนแสดงบันทึกลายมือทั่วไปที่สคริปต์ของเราสามารถแปลงเป็นข้อความธรรมดาได้* + +## ตัวอย่างทำงานเต็มรูปแบบ (สคริปต์ไฟล์เดียว) + +สำหรับผู้ที่ชอบความเรียบง่ายแบบคัดลอก‑วาง, นี่คือโค้ดทั้งหมดอีกครั้งโดยไม่มีคอมเมนต์อธิบาย + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +รันด้วยคำสั่ง: + +```bash +python handwriting_ocr.py +``` + +คุณควรเห็นผลลัพธ์ **recognize handwritten text** แสดงในคอนโซลของคุณ + +## สรุป + +เราได้ครอบคลุมทุกอย่างที่คุณต้องการเพื่อ **recognize handwritten text** ใน Python—เริ่มจากการเรียก **create OCR engine python** ครั้งแรก, เลือกภาษาที่เหมาะสม, **turn on handwritten mode**, และสุดท้าย **extract text from image** เพื่อ **read handwritten notes** + +ด้วยสคริปต์เดียวที่ทำงานอิสระ คุณสามารถเปลี่ยนภาพถ่ายเบลอของการจดบันทึกการประชุมให้เป็นข้อความที่สะอาดและค้นหาได้ ต่อไปลองนำผลลัพธ์ไปใส่ใน pipeline การประมวลผลภาษา, เก็บไว้ในดัชนีที่ค้นหาได้, หรือแม้แต่ส่งกลับไปยังบริการแปลงข้อความเป็นเสียงสำหรับการสร้าง voice‑over + +### จะทำอะไรต่อจากนี้? + +- **Batch processing:** ห่อสคริปต์ในลูปเพื่อจัดการโฟลเดอร์ของสแกนหลายไฟล์ +- **Confidence filtering:** ใช้ `result.confidence` เพื่อตัดทอนผลลัพธ์ที่คุณภาพต่ำ +- **Alternative libraries:** หาก `ocr` ไม่ตรงใจ, ลอง `pytesseract` พร้อม `--psm 13` สำหรับโหมดลายมือ +- **UI integration:** ผสานกับ Flask หรือ FastAPI เพื่อให้บริการอัปโหลดผ่านเว็บ + +มีคำถามเกี่ยวกับรูปแบบไฟล์ภาพใดเป็นพิเศษหรืออยากปรับแต่งโมเดล? แสดงความคิดเห็นด้านล่างได้เลย, แล้วขอให้เขียนโค้ดสนุกนะ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/turkish/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..1f5f55edf --- /dev/null +++ b/ocr/turkish/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-04-26 +description: HuggingFace model python'ı nasıl indireceğinizi ve Aspose OCR Cloud ile + OCR doğruluğunu artırırken python ile görüntüden metin çıkarma yöntemini öğrenin. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: tr +og_description: huggingface modelini python ile indirin ve OCR hattınızı güçlendirin. + Görüntüden metin çıkarmak için bu rehberi python ile izleyin ve ocr doğruluğunu + python ile artırın. +og_title: HuggingFace Modelini Python ile İndirme – Tam OCR Geliştirme Eğitimi +tags: +- OCR +- HuggingFace +- Python +- AI +title: huggingface model python indirme – Adım Adım OCR Boost Rehberi +url: /tr/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download huggingface model python – Tam OCR Geliştirme Eğitimi + +Hiç **download HuggingFace model python** yapmayı denediniz mi ve biraz kaybolmuş hissettiniz? Tek başınıza değilsiniz. Birçok projede en büyük darboğaz, iyi bir modeli makinenize getirmek ve ardından OCR sonuçlarını gerçekten kullanışlı hâle getirmektir. + +Bu rehberde, size tam olarak nasıl **download HuggingFace model python** yapacağınızı, bir resimden **extract text from image python** ile metin çıkaracağınızı ve ardından Aspose'un AI sonrası işleyicisini kullanarak **improve OCR accuracy python** nasıl artıracağınızı gösteren uygulamalı bir örnek üzerinden ilerleyeceğiz. Sonunda, gürültülü bir fatura görüntüsünü temiz, okunabilir metne dönüştüren, çalıştırmaya hazır bir betiğiniz olacak—sihir yok, sadece net adımlar. + +## Gereksinimler + +- Python 3.9+ (kod 3.11'de de çalışır) +- Tek seferlik model indirme için bir internet bağlantısı +- `asposeocrcloud` paketi (`pip install asposeocrcloud`) +- Kontrol ettiğiniz bir klasöre yerleştirilmiş örnek bir görüntü (ör. `sample_invoice.png`) + +Hepsi bu—ağır çerçeveler yok, hızlandırmak istemediğiniz sürece GPU‑özel sürücüler de yok. + +Şimdi, gerçek uygulamaya dalalım. + +![download huggingface model python workflow](image.png "download huggingface model python diagram") + +## Adım 1: OCR Motorunu Kurun ve Bir Dil Seçin +*(Burada **extract text from image python** işlemine başlıyoruz.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Neden önemli:** +OCR motoru ilk savunma hattıdır; doğru dil paketini seçmek karakter tanıma hatalarını hemen azaltır ve bu da **improve OCR accuracy python**'ın temel bir parçasıdır. + +## Adım 2: AsposeAI Modelini Yapılandırın – HuggingFace'den İndiriliyor +*(Burada gerçekten **download HuggingFace model python** yapıyoruz.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**Arka planda neler oluyor?** +`allow_auto_download` true olduğunda, SDK HuggingFace'e bağlanır, `Qwen2.5‑3B‑Instruct‑GGUF` modelini alır ve belirttiğiniz klasöre kaydeder. Bu, **download huggingface model python**'ın özüdür—SDK ağır işi üstlenir, böylece kendiniz `git clone` ya da `wget` komutları yazmak zorunda kalmazsınız. + +*Pro ipucu:* `directory_model_path`'i daha hızlı yükleme süreleri için bir SSD'de tutun; model `int8` biçiminde bile yaklaşık 3 GB'dir. + +## Adım 3: AI Motorunu OCR Motoruna Bağlayın +*(İki parçayı birleştirerek **improve OCR accuracy python** yapabiliyoruz.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Neden bağlayalım?** +OCR motoru bize ham metin verir; bu metin yazım hataları, kırık satırlar ya da yanlış noktalama içerebilir. AI motoru akıllı bir editör gibi çalışır, bu sorunları temizler—tam da **improve OCR accuracy python** için ihtiyacınız olan şey. + +## Adım 4: Görüntünüzde OCR Çalıştırın +*(Nihayet **extract text from image python** yaptığımız an.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` artık motorun gördüğü ham karakterleri içeren bir `text` özelliğine sahip. Pratikte birkaç aksaklık fark edeceksiniz—belki “Invoice” kelimesi “Inv0ice” olmuş ya da bir cümlenin ortasında satır sonu var. + +## Adım 5: AI Son İşlemci ile Temizleme +*(Bu adım doğrudan **improve OCR accuracy python** sağlar.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +AI modeli metni yeniden yazar, dil‑bilgisine duyarlı düzeltmeler uygular. HuggingFace'ten talimat‑tuned bir model kullandığımız için çıktı genellikle akıcıdır ve sonraki işleme hazırdır. + +## Adım 6: Öncesi ve Sonrası Göster +*(**extract text from image python** ve **improve OCR accuracy python** ne kadar iyi çalıştığını görmek için hızlı bir kontrol.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Beklenen Çıktı + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +AI'nin “Inv0ice” kelimesini “Invoice” olarak düzelttiğine ve rastgele satır sonlarını yumuşattığına dikkat edin. Bu, indirilen bir HuggingFace modeli kullanarak **improve OCR accuracy python**'ın somut sonucudur. + +## Sık Sorulan Sorular (SSS) + +### Modeli çalıştırmak için GPU'ya ihtiyacım var mı? +Hayır. `gpu_layers=20` ayarı, uyumlu bir GPU mevcutsa SDK'nın en fazla 20 GPU katmanı kullanmasını söyler; aksi takdirde CPU'ya geri döner. Modern bir dizüstü bilgisayarda CPU yolu hâlâ saniyede birkaç yüz token işleyebilir—ara sıra fatura ayrıştırması için mükemmeldir. + +### Model indirilmezse ne olur? +Ortamınızın `https://huggingface.co` adresine ulaşabildiğinden emin olun. Kurumsal bir proxy arkasındaysanız `HTTP_PROXY` ve `HTTPS_PROXY` ortam değişkenlerini ayarlayın. SDK otomatik olarak yeniden deneyecek, ancak repoyu `directory_model_path` içine manuel olarak `git lfs pull` ile de çekebilirsiniz. + +### Modeli daha küçük bir modelle değiştirebilir miyim? +Kesinlikle. `hugging_face_repo_id` değerini başka bir repo (ör. `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) ile değiştirin ve `hugging_face_quantization`'ı buna göre ayarlayın. Daha küçük modeller daha hızlı indirilir ve daha az RAM tüketir, ancak düzeltme kalitesinde biraz kayıp yaşayabilirsiniz. + +### Bu, diğer alanlarda **extract text from image python** yapmama nasıl yardımcı olur? +Aynı işlem hattı makbuzlar, pasaportlar veya el yazısı notlar için de çalışır. Tek değişiklik dil paketi (`ocr.Language.FRENCH` vb.) ve muhtemelen HuggingFace'ten alan‑spesifik ince ayarlı bir modeldir. + +## Bonus: Birden Çok Dosyayı Otomatikleştirme + +Eğer içinde birçok görüntü bulunan bir klasörünüz varsa, OCR çağrısını basit bir döngüye sarın: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +Bu küçük ekleme, **download huggingface model python**'ı bir kez yapmanızı sağlar, ardından dosyaları toplu olarak işleyebilirsiniz—belge‑otomasyon hattınızı ölçeklendirmek için harika. + +## Sonuç + +Tam bir uçtan‑uca örnek üzerinden **download HuggingFace model python**, **extract text from image python** ve **improve OCR accuracy python**'ı Aspose'un OCR Cloud'u ve bir AI sonrası işleyicisiyle nasıl yapacağınızı gösterdik. Betik çalıştırmaya hazır, kavramlar açıklandı ve ön‑sonuç çıktısını gördünüz, böylece çalıştığını biliyorsunuz. + +Sırada ne var? Farklı bir HuggingFace modeli deneyin, diğer dil paketleriyle oynayın veya temizlenmiş metni sonraki bir NLP işlem hattına besleyin (ör. fatura satır öğeleri için varlık çıkarımı). Gökyüzü sınırdır ve yeni inşa ettiğiniz temel sağlamdır. + +Sorularınız mı var ya da OCR'ı hâlâ zorlayan bir görüntünüz mü var? Aşağıya bir yorum bırakın, birlikte sorun giderelim. Kodlamanın tadını çıkarın! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/turkish/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..aaf5f32aa --- /dev/null +++ b/ocr/turkish/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-04-26 +description: Aspose OCR Python kullanarak OCR modelini hızlıca indirin. Model dizinini + nasıl ayarlayacağınızı, model yolunu nasıl yapılandıracağınızı ve modeli birkaç + satırda nasıl indireceğinizi öğrenin. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: tr +og_description: Aspose OCR Python ile saniyeler içinde OCR modelini indirin. Bu kılavuz, + model dizinini nasıl ayarlayacağınızı, model yolunu nasıl yapılandıracağınızı ve + modeli güvenli bir şekilde nasıl indireceğinizi gösterir. +og_title: ocr modelini indir – Tam Aspose OCR Python Öğreticisi +tags: +- OCR +- Python +- Aspose +title: Aspose OCR Python ile OCR modelini indirin – Adım Adım Rehber +url: /tr/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# download ocr model – Tam Aspose OCR Python Öğreticisi + +Aspose OCR'ı Python'da **download ocr model** kullanarak, bitmek bilmeyen dokümanlar arasında dolaşmadan nasıl yapabileceğinizi hiç merak ettiniz mi? Tek başınıza değilsiniz. Birçok geliştirici, model yerel olarak bulunmadığında ve SDK gizemli bir hata verdiğinde bir duvara çarpar. İyi haber? Çözüm sadece birkaç satır ve model dakikalar içinde kullanıma hazır olacak. + +Bu öğreticide, bilmeniz gereken her şeyi adım adım inceleyeceğiz: doğru sınıfları içe aktarmaktan, **set model directory**'ye, aslında **how to download model**'e ve sonunda yolu doğrulamaya kadar. Sonunda tek bir fonksiyon çağrısıyla herhangi bir görüntüde OCR çalıştırabilecek ve projenizi düzenli tutan **configure model path** seçeneklerini anlayacaksınız. Gereksiz ayrıntı yok, sadece **aspose ocr python** kullanıcıları için uygulanabilir, çalıştırılabilir bir örnek. + +## Öğrenecekleriniz + +- Aspose OCR Cloud sınıflarını doğru şekilde nasıl içe aktaracağınızı. +- **download ocr model**'i otomatik olarak indirmek için kesin adımları. +- Tekrarlanabilir yapılar için **set model directory** ve **configure model path** yollarını. +- Modelin başlatıldığını ve diskte nerede bulunduğunu nasıl doğrulayacağınızı. +- Yaygın tuzaklar (izinler, eksik dizinler) ve hızlı çözümler. + +### Önkoşullar + +- Makinenizde Python 3.8+ yüklü olmalı. +- `asposeocrcloud` paketi (`pip install asposeocrcloud`). +- Modeli saklamak istediğiniz klasöre yazma izni (ör. `C:\models` veya `~/ocr_models`). + +--- + +## Adım 1: Aspose OCR Cloud Sınıflarını İçe Aktarın + +İhtiyacınız olan ilk şey doğru içe aktarma ifadesidir. Bu, model yapılandırmasını ve OCR işlemlerini yöneten sınıfları getirir. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Why this matters:* `AsposeAI` OCR'ı çalıştıracak motor iken, `AsposeAIModelConfig` motorun **nerede** modeli araması gerektiğini ve **otomatik olarak** indirmesi gerekip gerekmediğini belirler. Bu adımı atlamak ya da yanlış modülü içe aktarmak, indirme aşamasına gelmeden bir `ModuleNotFoundError` ile sonuçlanır. + +## Adım 2: Model Yapılandırmasını Tanımlayın (Set Model Directory & Configure Model Path) + +Şimdi Aspose'a model dosyalarını nerede tutacağını söylüyoruz. İşte **set model directory** ve **configure model path**'in yapıldığı yer. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**İpuçları & Uyarılar** + +- **Mutlak yollar** script farklı bir çalışma dizininden çalıştırıldığında karışıklığı önler. +- Linux/macOS'ta `"/home/you/ocr_models"`; Windows'ta ters eğik çizgileri olduğu gibi almak için ön ek `r` ekleyin. +- `allow_auto_download="true"` ayarı, **how to download model**'i ekstra kod yazmadan gerçekleştirmenin anahtarıdır. + +## Adım 3: Yapılandırmayı Kullanarak AsposeAI Örneğini Oluşturun + +Yapılandırma hazır olduğunda OCR motorunu örnekleyin. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Why this matters:* `ocr_ai` nesnesi artık tanımladığımız yapılandırmayı tutar. Model bulunmazsa, bir sonraki çağrı otomatik olarak indirmeyi tetikler—bu, **how to download model**'in eller serbest bir şekilde çalışmasının özüdür. + +## Adım 4: Model İndirmesini Tetikleyin (Gerekirse) + +OCR çalıştırmadan önce modelin gerçekten diskte olduğundan emin olmanız gerekir. `is_initialized()` metodu hem kontrol eder hem de başlatmayı zorlar. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**What happens under the hood?** + +- İlk `is_initialized()` çağrısı, model klasörü boş olduğu için `False` döner. +- `print` ifadesi kullanıcıya bir indirme işleminin başlayacağını bildirir. +- İkinci çağrı, Aspose'ın daha önce belirttiğiniz Hugging Face deposundan modeli çekmesini sağlar. +- İndirme tamamlandığında, sonraki kontrollerde metod `True` döner. + +**Edge case:** Ağınız Hugging Face'i engelliyorsa bir istisna alırsınız. Bu durumda modeli zip olarak manuel indirin, `directory_model_path` içine çıkarın ve scripti tekrar çalıştırın. + +## Adım 5: Modelin Şu Anda Bulunduğu Yerel Yolu Raporlayın + +İndirme bittiğinde dosyaların nereye düştüğünü bilmek isteyebilirsiniz. Bu, hata ayıklama ve CI boru hatları kurma açısından yardımcı olur. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Tipik çıktı şu şekildedir: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Artık **download ocr model** işlemini başarıyla tamamladınız, dizini ayarladınız ve yolu doğruladınız. + +## Görsel Genel Bakış + +Aşağıda, yapılandırmadan kullanıma hazır bir modele kadar olan akışı gösteren basit bir diyagram yer alıyor. + +![download ocr model akış diyagramı, yapılandırma, otomatik indirme ve yerel yolu gösteriyor](/images/download-ocr-model-flow.png) + +*Alt metin, SEO için anahtar kelimeyi içerir.* + +## Yaygın Varyasyonlar ve Nasıl Ele Alınır + +### 1. Farklı Bir Model Deposu Kullanma + +`openai/gpt2` dışındaki bir modele ihtiyacınız varsa, sadece `hugging_face_repo_id` değerini değiştirin: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Depo herkese açık olmalı veya ortam değişkenlerinizde gerekli token ayarlanmış olmalıdır. + +### 2. Otomatik İndirmeyi Devre Dışı Bırakma + +Bazen indirmeyi kendiniz kontrol etmek istersiniz (ör. hava boşluğu ortamlarında). `allow_auto_download` değerini `"false"` yapın ve başlatmadan önce özel bir indirme scripti çalıştırın: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Çalışma Zamanında Model Dizini Değiştirme + +`AsposeAI` nesnesini yeniden oluşturmadan yolu yeniden yapılandırabilirsiniz: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +## Üretim Kullanımı için Pro İpuçları + +- **Modeli önbellekle:** Birden fazla servis aynı modeli kullanıyorsa, dizini ortak bir ağ sürücüsünde tutun. Böylece gereksiz indirmeler önlenir. +- **Sürüm sabitleme:** Hugging Face deposu güncellenebilir. Belirli bir sürüme kilitlemek için repo kimliğine `@v1.0.0` ekleyin (`"openai/gpt2@v1.0.0"`). +- **İzinler:** Scripti çalıştıran kullanıcının `directory_model_path` üzerinde okuma/yazma hakları olduğundan emin olun. Linux'ta genellikle `chmod 755` yeterlidir. +- **Günlükleme:** Basit `print` ifadelerini Python'un `logging` modülüyle değiştirerek büyük uygulamalarda daha iyi gözlemlenebilirlik sağlayın. + +## Tam Çalışan Örnek (Kopyala‑Yapıştır Hazır) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Beklenen çıktı** (ilk çalıştırmada indirme gerçekleşir, sonraki çalıştırmalarda indirme atlanır): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Scripti tekrar çalıştırın; model zaten önbellekte olduğu için yalnızca yol satırını göreceksiniz. + +## Sonuç + +Aspose OCR Python kullanarak **download ocr model** işlemini, **set model directory** ayarını ve **configure model path** inceliklerini tamamen kapsadık. Birkaç satır kodla indirmeyi otomatikleştirebilir, manuel adımları ortadan kaldırabilir ve OCR boru hattınızı tekrarlanabilir tutabilirsiniz. + +Sonraki adımda gerçek OCR çağrısını (`ocr_ai.recognize_image(...)`) keşfedebilir ya da doğruluğu artırmak için farklı bir Hugging Face modeli deneyebilirsiniz. İster nasıl olursa olsun, burada oluşturduğunuz temel—temiz yapılandırma, otomatik indirme ve yol doğrulama—gelecekteki tüm entegrasyonları çok daha sorunsuz hale getirecek. + +Kenar durumlarıyla ilgili sorularınız mı var, yoksa bulut dağıtımları için model dizinini nasıl ayarladığınızı paylaşmak mı istiyorsunuz? Aşağıya bir yorum bırakın, iyi kodlamalar! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/turkish/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..c8a9809dd --- /dev/null +++ b/ocr/turkish/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-04-26 +description: OCR sonuçlarını nasıl son işleme tabi tutar ve koordinatlarla metin çıkarırsınız. + Yapılandırılmış çıktı ve AI düzeltmesi kullanarak adım adım bir çözüm öğrenin. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: tr +og_description: OCR sonuçlarını nasıl son işleme tabi tutar ve koordinatlarıyla metni + nasıl çıkarırsınız? Güvenilir bir iş akışı için bu kapsamlı öğreticiyi izleyin. +og_title: OCR'yi Nasıl Son İşleme Alırsınız – Tam Kılavuz +tags: +- OCR +- Python +- AI +- Text Extraction +title: OCR'yi Nasıl Son İşlemeye Alırsınız – Python'da Koordinatlarla Metin Çıkarma +url: /tr/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Sonrası Nasıl İşlenir – Python'da Koordinatlarla Metin Çıkarma + +Ever needed to **OCR sonrası nasıl işlenir** results because the raw output was noisy or mis‑aligned? You’re not the only one. In many real‑world projects—invoice scanning, receipt digitization, or even augmenting AR experiences—the OCR engine gives you raw words, but you still have to clean them up and keep track of where each word lives on the page. That’s where a structured output mode combined with an AI‑driven post‑processor shines. + +In this tutorial we’ll walk through a complete, runnable Python pipeline that **extracts text with coordinates** from an image, runs an AI‑based correction step, and prints each word together with its (x, y) position. No missing imports, no vague “see the docs” shortcuts—just a self‑contained solution you can drop into your project today. + +> **Pro tip:** If you’re using a different OCR library, look for a “structured” or “layout” mode; the concepts stay the same. + +--- + +## Önkoşullar + +| Requirement | Why it matters | +|-------------|----------------| +| Python 3.9+ | Modern sözdizimi ve tip ipuçları | +| `ocr` library that supports `OutputMode.STRUCTURED` (e.g., a fictional `myocr`) | Sınır kutusu verileri için gerekli | +| An AI post‑processing module (could be OpenAI, HuggingFace, or a custom model) | OCR sonrası doğruluğu artırır | +| An image file (`input.png`) in your working directory | Okuyacağımız kaynak | + +If any of these sound unfamiliar, just install the placeholder packages with `pip install myocr ai‑postproc`. The code below also includes fallback stubs so you can test the flow without the real libraries. + +--- + +## Adım 1: OCR Motoru için Yapılandırılmış Çıktı Modunu Etkinleştirin + +The first thing we do is tell the OCR engine to give us more than just plain text. Structured output returns each word together with its bounding box and confidence score, which is essential for **extract text with coordinates** later on. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Why this matters:* Without structured mode you’d only get a long string, and you’d lose the spatial information you need for overlaying text on images or feeding downstream layout analysis. + +--- + +## Adım 2: Görüntüyü Tanıyın ve Kelimeleri, Kutuları ve Güven Skorlarını Yakalayın + +Now we feed the image into the engine. The result is an object that contains a list of word objects, each exposing `text`, `x`, `y`, `width`, `height`, and `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Edge case:* If the image is empty or unreadable, `structured_result.words` will be an empty list. It’s good practice to check for that and handle it gracefully. + +--- + +## Adım 3: Pozisyonları Koruyarak AI‑Tabanlı Post‑İşleme Çalıştırın + +Even the best OCR engines make mistakes—think of “O” vs. “0” or missing diacritics. An AI model trained on domain‑specific text can correct those errors. Crucially, we keep the original coordinates so the spatial layout stays intact. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Why we preserve coordinates:* Many downstream tasks (e.g., PDF generation, AR labeling) rely on exact placement. The AI only touches the `text` field, leaving `x`, `y`, `width`, `height` untouched. + +--- + +## Adım 4: Düzeltlenmiş Kelimeler Üzerinde Döngü Oluşturun ve Metinlerini Koordinatlarıyla Görüntüleyin + +Finally, we loop through the corrected words and print each word together with its top‑left corner `(x, y)`. This satisfies the **extract text with coordinates** goal. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Beklenen çıktı (örnek):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Each line shows the corrected word and its exact location on the original image. + +--- + +## Tam Çalışan Örnek + +Below is a single script that ties everything together. You can copy‑paste it, adjust the import statements to match your actual libraries, and run it directly. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Betik Çalıştırma** + +```bash +python ocr_postprocess_demo.py +``` + +If you have the real libraries installed, the script will process your `input.png`. Otherwise, the stub implementation lets you see the expected flow and output without any external dependencies. + +--- + +## Sık Sorulan Sorular (SSS) + +| Question | Answer | +|----------|--------| +| *Bu Tesseract ile çalışır mı?* | Tesseract kendi başına kutu dışı bir yapılandırılmış mod sunmaz, ancak `pytesseract.image_to_data` gibi sarmalayıcılar, aynı AI post‑processor'a besleyebileceğiniz sınır kutularını döndürür. | +| *Üst‑sol yerine alt‑sağ köşeye ihtiyacım olursa ne yapmalıyım?* | Her kelime nesnesi ayrıca `width` ve `height` sağlar. Karşı köşeyi elde etmek için `x2 = x + width` ve `y2 = y + height` hesaplayın. | +| *Birden fazla görüntüyü toplu işleyebilir miyim?* | Kesinlikle. Adımları `for image_path in Path("folder").glob("*.png"):` döngüsü içinde sarın ve dosya başına sonuçları toplayın. | +| *Düzeltme için bir AI modeli nasıl seçilir?* | Genel metin için, OCR hataları üzerinde ince ayar yapılmış küçük bir GPT‑2 işe yarar. Alan‑spesifik veriler (ör. tıbbi reçeteler) için, gürültülü‑temiz eşleşmiş veri üzerinde bir sıralı‑sıralı model eğitin. | +| *AI düzeltmesinden sonra güven skoru faydalı mı?* | Hala hata ayıklama için orijinal güven skorunu tutabilirsiniz, ancak model destekliyorsa AI kendi güven skorunu da üretebilir. | + +## Kenar Durumları ve En İyi Uygulamalar + +1. **Boş veya bozuk görüntüler** – ilerlemeden önce her zaman `structured_result.words`'ün boş olmadığını doğrulayın. +2. **Latin dışı yazı sistemleri** – OCR motorunuzun hedef dil için yapılandırıldığından emin olun; AI post‑processor aynı yazı sisteminde eğitilmiş olmalıdır. +3. **Performans** – AI düzeltmesi maliyetli olabilir. Aynı görüntüyü yeniden kullanacaksanız sonuçları önbelleğe alın veya AI adımını eşzamansız çalıştırın. +4. **Koordinat sistemi** – OCR kütüphaneleri farklı kökenler (üst‑sol vs. alt‑sol) kullanabilir. PDF'lerde veya kanvaslarda yerleştirirken buna göre ayarlayın. + +## Sonuç + +You now have a solid, end‑to‑end recipe for **how to post‑process OCR** and reliably **extract text with coordinates**. By enabling structured output, feeding the result through an AI correction layer, and preserving the original bounding boxes, you can turn noisy OCR scans into clean, spatially‑aware text ready for downstream tasks like PDF generation, data entry automation, or augmented‑reality overlays. + +Ready for the next step? Try swapping the stub AI with an OpenAI `gpt‑4o‑mini` call, or integrate the pipeline into a FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/turkish/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..009787cac --- /dev/null +++ b/ocr/turkish/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-26 +description: Python ile görüntüleri hızlı bir şekilde tanıma. Görüntü tanıma boru + hattını, toplu işleme öğrenin ve AI kullanarak görüntü tanımayı otomatikleştirin. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: tr +og_description: Python ile görüntüleri hızlıca tanıma. Bu rehber, görüntü tanıma hattını, + toplu işleme ve AI ile otomasyonu anlatıyor. +og_title: Görselleri Nasıl Tanıyabilirsiniz – Görüntü Tanıma Boru Hattını Otomatikleştirin +tags: +- image-processing +- python +- ai +title: Görselleri Nasıl Tanıyabilirsiniz – Görüntü Tanıma Sürecini Otomatikleştirin +url: /tr/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Görüntüleri Tanıma – Görüntü Tanıma İş Akışını Otomatikleştirme + +Binlerce satır kod yazmadan **görüntüleri nasıl tanıyacağınızı** hiç merak ettiniz mi? Yalnız değilsiniz—birçok geliştirici, ilk kez onlarca ya da yüzlerce fotoğraf işlemek zorunda kaldığında aynı duvara çarpar. İyi haber? Birkaç düzenli adımla, toplu işleme, çalıştırma ve temizleme işlemlerini kendiliğinden yapan tam teşekküllü bir görüntü tanıma iş akışı oluşturabilirsiniz. + +Bu öğreticide, **görüntüleri nasıl toplu işleyebileceğinizi**, her birini bir AI motoruna besleyebileceğinizi, sonuçları post‑process edebileceğinizi ve sonunda kaynakları serbest bırakabileceğinizi gösteren eksiksiz, çalıştırılabilir bir örnek üzerinden ilerleyeceğiz. Sonunda, fotoğraf etiketleyici, kalite kontrol sistemi ya da araştırma veri seti oluşturucu gibi herhangi bir projeye ekleyebileceğiniz bağımsız bir betiğe sahip olacaksınız. + +## Öğrenecekleriniz + +- **Görüntüleri tanıma** nasıl yapılır, sahte bir AI motoru kullanarak (desen gerçek hizmetler için TensorFlow, PyTorch veya bulut API'leri gibi aynı şekildedir). +- Verimli bir şekilde toplu işlemleri yöneten bir **görüntü tanıma iş akışı** nasıl oluşturulur. +- Her seferinde dosyalar üzerinde manuel döngü yapmadan **görüntü tanımayı otomatikleştirmenin** en iyi yolu. +- İş akışını ölçeklendirme ve kaynakları güvenli bir şekilde serbest bırakma ipuçları. + +> **Prerequisites:** Python 3.8+, functions ve döngüler hakkında temel bilgi ve işlemek istediğiniz birkaç görüntü dosyası (veya yolu). Çekirdek örnek için dış kütüphaneler gerekmez, ancak gerçek AI SDK'larını nerede ekleyebileceğinizi belirteceğiz. + +![Batch işleme hattında görüntüleri tanıma diyagramı](pipeline.png "Görüntüleri tanıma diyagramı") + +## Adım 1: Görüntülerinizi Toplu İşleyin – Görüntüleri Verimli Bir Şekilde Nasıl Toplu İşlersiniz + +AI herhangi bir ağır işi yapmadan önce, ona besleyecek bir görüntü koleksiyonuna ihtiyacınız var. Bunu bir market alışveriş listeniz gibi düşünün; motor daha sonra listedeki her öğeyi tek tek alacak. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Neden toplu iş?** +Toplu işleme, yazdığınız tekrarlayan kod miktarını azaltır ve daha sonra paralellik eklemeyi çok basit hâle getirir. Eğer bir gün 10 000 fotoğraf işlemek zorunda kalırsanız, sadece `image_batch` kaynağını değiştirirsiniz—iş akışının geri kalanı dokunulmaz kalır. + +## Adım 2: Görüntü Tanıma İş Akışını Çalıştırın (AI ile Görüntüleri Tanıyın) + +Şimdi toplu işimizi gerçek tanıyıcıya bağlıyoruz. Gerçek bir senaryoda `torchvision.models` ya da bir bulut uç noktasını çağırabilirsiniz; burada davranışı taklit ediyoruz, böylece öğretici bağımsız kalıyor. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Açıklama:** +- `engine.recognize_image`, **görüntü tanıma iş akışının** kalbidir; bir derin öğrenme modeli ya da bir REST API çağrısı olabilir. +- `postprocessor.run`, ham tahminleri saklayabileceğiniz ya da akışa alabileceğiniz temiz bir sözlüğe normalleştirerek **görüntü tanımayı otomatikleştirmeyi** gösterir. +- Her bir `corrected` sözlüğünü `recognized_results` içinde toplarız, böylece sonraki adımlar (ör. veritabanı ekleme) basit olur. + +## Adım 3: Sonuçları Post‑process ve Depola – Görüntü Tanıma Sonuçlarını Otomatikleştir + +Tahminlerin düzenli bir listesini elde ettikten sonra, genellikle bunları kalıcı hale getirmek istersiniz. Aşağıdaki örnek bir CSV dosyası yazar; bir veritabanı ya da mesaj kuyruğu ile değiştirmekten çekinmeyin. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Neden CSV?** +CSV evrensel olarak okunabilir—Excel, pandas, hatta düz metin editörleri bile açabilir. Daha sonra ölçekli bir şekilde **görüntü tanımayı otomatikleştirmeniz** gerekirse, yazma bloğunu veri göletinize toplu ekleme ile değiştirin. + +## Adım 4: Temizleme – AI Kaynaklarını Güvenli Şekilde Serbest Bırakma + +Birçok AI SDK'sı GPU belleği tahsis eder veya işçi thread'leri oluşturur. Bunları serbest bırakmayı unutmak bellek sızıntılarına ve kötü çöküşlere yol açabilir. Sahte nesnelerimiz buna ihtiyaç duymasa da, doğru deseni göstereceğiz. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +Betik çalıştırıldığında dostça bir onay mesajı verir, iş akışının sorunsuz tamamlandığını bildirir. + +## Tam Çalışan Betik + +Her şeyi bir araya getirerek, işte eksiksiz, kopyala‑yapıştır‑hazır program: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Beklenen Çıktı + +Betik çalıştırıldığında (üç yer tutucu yolun var olduğunu varsayarak), aşağıdaki gibi bir şey göreceksiniz: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +Ve oluşturulan `recognition_results.csv` şunları içerecek: + +| görüntü | etiket | güven | +|---------------------|--------|-------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Sonuç + +Artık Python'da **görüntüleri nasıl tanıyacağınız** konusunda eksiksiz, uçtan uca bir örneğe sahipsiniz; **görüntü tanıma iş akışı**, toplu işleme ve otomatik post‑process içerir. Desen ölçeklenebilir: sahte sınıfları gerçek bir modelle değiştirin, daha büyük bir `image_batch` besleyin ve üretim‑hazır bir çözüm elde edin. + +Daha ileri gitmek ister misiniz? Bu sonraki adımları deneyin: + +- `MockEngine`'i gerçek tahminler için bir TensorFlow ya da PyTorch modeli ile değiştirin. +- Büyük toplu işlemleri hızlandırmak için döngüyü `concurrent.futures.ThreadPoolExecutor` ile paralelleştirin. +- CSV yazarını bir bulut depolama kovasına bağlayarak dağıtık çalışanlar arasında **görüntü tanımayı otomatikleştirin**. + +Denemekten, şeyleri kırmaktan ve ardından düzeltmekten çekinmeyin—bu, görüntü tanıma iş akışlarında gerçekten uzmanlaşmanın yoludur. Herhangi bir sorunla karşılaşırsanız ya da geliştirme fikirleriniz varsa, aşağıya bir yorum bırakın. İyi kodlamalar! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/turkish/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..17d06b061 --- /dev/null +++ b/ocr/turkish/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-04-26 +description: AsposeAI OCR sonrası işleme kullanarak kredi kartı numaralarını hızlıca + maskeleyin. PCI uyumluluğu, düzenli ifade maskelemesi ve veri temizleme konularını + adım adım bir öğreticide öğrenin. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: tr +og_description: AsposeAI ile OCR sonuçlarındaki kredi kartı numaralarını maskeleyin. + Bu öğreticide PCI uyumluluğu, düzenli ifade maskesi ve veri temizleme konuları ele + alınmaktadır. +og_title: Kredi Kartı Numaralarını Maskele – Tam Python OCR Son İşleme Rehberi +tags: +- OCR +- Python +- security +title: OCR Çıktısındaki Kredi Kartı Numaralarını Maskele – Tam Python Rehberi +url: /tr/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Kredi Kartı Numaralarını Maskeleme – Tam Python Rehberi + +OCR motorundan doğrudan gelen metinde **kredi kartı numaralarını maskelemeye** hiç ihtiyaç duydunuz mu? Tek başınıza değilsiniz. Düzenlenmiş sektörlerde, tam bir PAN (Primary Account Number) ifşa etmek, PCI uyumluluk denetçileriyle başınızı belaya sokabilir. İyi haber? Birkaç satır Python ve AsposeAI’nin post‑processing kancasıyla, orta sekiz rakamı otomatik olarak gizleyebilir ve güvende kalabilirsiniz. + +Bu öğreticide gerçek bir senaryoyu adım adım inceleyeceğiz: bir fiş görüntüsü üzerinde OCR çalıştırmak, ardından herhangi bir PCI verisini temizleyen özel bir **OCR post‑processing** işlevi uygulamak. Sonunda, herhangi bir AsposeAI iş akışına ekleyebileceğiniz yeniden kullanılabilir bir kod parçacığına ve kenar durumlarını yönetmek ve çözümü ölçeklendirmek için birkaç pratik ipucu elde edeceksiniz. + +## Öğrenecekleriniz + +- **AsposeAI** ile özel bir post‑processor nasıl kaydedilir. +- **regular expression masking** yaklaşımının neden hem hızlı hem de güvenilir olduğu. +- Veri temizleme ile ilgili **PCI compliance** temelleri. +- Birden fazla kart formatı veya uluslararası numaralar için deseni genişletme yolları. +- Beklenen çıktı ve maskenin doğru çalıştığını nasıl doğrulayacağınız. + +> **Önkoşullar** – Çalışan bir Python 3 ortamına, Aspose.AI for OCR paketinin kurulmuş olmasına (`pip install aspose-ocr`), ve içinde bir kredi kartı numarası bulunan örnek bir görüntüye (ör. `receipt.png`) sahip olmalısınız. Başka bir dış hizmete ihtiyaç yok. + +--- + +## Adım 1: Kredi Kartı Numaralarını Maskeleyen Bir Post‑Processor Tanımlayın + +Çözümün kalbi, OCR sonucunu alan, bir **regular expression masking** rutini çalıştıran ve temizlenmiş metni döndüren küçük bir işlevde yatar. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Neden bu çalışıyor:** +- Regex `(\d{4})\d{8}(\d{4})` tam olarak 16 ardışık rakama eşleşir; Visa, MasterCard ve birçok diğer kartın yaygın formatıdır. +- İlk ve son dört rakamı (`\1` ve `\2`) yakalayarak, tam PAN saklamayı yasaklayan **PCI compliance** kurallarına uyarak hata ayıklama için yeterli bilgi tutarız. +- `\1****\2` değişimi, hassas orta sekiz rakamı gizler ve `1234567812345678` → `1234****5678` haline getirir. + +> **Pro ipucu:** 15 haneli American Express numaralarını desteklemeniz gerekiyorsa, `r'(\d{4})\d{6}(\d{5})'` gibi ikinci bir desen ekleyin ve iki değişikliği ardışık olarak çalıştırın. + +--- + +## Adım 2: AsposeAI Motorunu Başlatın + +Post‑processor'ımızı eklemeden önce, OCR motorunun bir örneğine ihtiyacımız var. AsposeAI, OCR modelini ve özel işleme için basit bir API'yi bir arada sunar. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Neden burada başlatılıyor?** +`AsposeAI` nesnesini bir kez oluşturup birden fazla görüntüde yeniden kullanmak, aşırı yükü azaltır. Motor ayrıca dil modellerini önbelleğe alır, bu da sonraki çağrıları hızlandırır—fiş toplu tararken kullanışlıdır. + +--- + +## Adım 3: Özel Maskeleme Fonksiyonunu Kaydedin + +AsposeAI, herhangi bir çağrılabilir nesneyi takmanıza izin veren bir `set_post_processor` yöntemi sunar. `mask_pci` fonksiyonumuzu, şu an için boş bir opsiyonel ayar sözlüğüyle birlikte geçiriyoruz. + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**Arka planda ne oluyor?** +Daha sonra `run_postprocessor` çağırdığınızda, AsposeAI ham OCR sonucunu `mask_pci`'ye verir. Fonksiyon, tanınan metni içeren hafif bir nesne (`data`) alır ve yeni bir string döndürürsünüz. Bu tasarım, çekirdek OCR'yi dokunulmaz tutarken **veri temizleme** politikalarını tek bir yerde uygulamanıza olanak tanır. + +--- + +## Adım 4: Fiş Görüntüsü Üzerinde OCR Çalıştırın + +Motorun çıktıyı nasıl temizleyeceğini bildiğine göre, ona bir görüntü veriyoruz. Bu öğretici için, doğru dil ve çözünürlük ayarlarıyla yapılandırılmış bir `engine` nesnesine zaten sahip olduğunuzu varsayıyoruz. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**İpucu:** Önceden yapılandırılmış bir nesneniz yoksa, aşağıdaki gibi bir tane oluşturabilirsiniz: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +`recognize_image` çağrısı, `text` özelliği ham, maskesiz stringi tutan bir nesne döndürür. + +--- + +## Adım 5: Kaydedilen Post‑Processor'ı Uygulayın + +Ham OCR verisi elinizde olduğunda, bunu AI örneğine veriyoruz. Motor, daha önce kaydettiğimiz `mask_pci` fonksiyonunu otomatik olarak çalıştırır. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Fonksiyonu manuel olarak çağırmak yerine `run_postprocessor` kullanmanın nedeni nedir?** +Böyle yapmak, özellikle birden fazla post‑processor (ör. yazım denetimi, dil algılama) olduğunda iş akışını tutarlı tutar. AsposeAI, kaydettiğiniz sıraya göre bunları kuyruğa alır ve belirli bir çıktı garantiler. + +--- + +## Adım 6: Temizlenmiş Çıktıyı Doğrulayın + +Son olarak, temizlenmiş metni yazdıralım ve kredi kartı numaralarının doğru şekilde maskelendiğini doğrulayalım. + +```python +print(final_result.text) +``` + +**Beklenen çıktı** (alıntı): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Fişte kart numarası yoksa, metin değişmeden kalır—maskelenecek bir şey yok, endişelenecek bir şey de yok. + +--- + +## Kenar Durumlarını ve Yaygın Varyasyonları Ele Alma + +### Tek Bir Belgede Birden Fazla Kart Numarası +Bir fiş birden fazla PAN içeriyorsa (ör. bir sadakat kartı ve bir ödeme kartı), regex global olarak çalışır ve tüm eşleşmeleri otomatik olarak maskeler. Ek bir koda gerek yok. + +### Standart Olmayan Biçimlendirme +Bazen OCR boşluklar veya tireler ekler (`1234 5678 1234 5678` veya `1234-5678-1234-5678`). Bu karakterleri yok sayacak şekilde deseni genişletin: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +Eklenen `[ -]?` digit blokları arasında isteğe bağlı boşluk veya tireye tolerans gösterir. + +### Uluslararası Kartlar +Bazı bölgelerde kullanılan 19 haneli PAN'lar için deseni genişletebilirsiniz: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Sadece **PCI compliance**'in uzunluk ne olursa olsun orta rakamları maskelemesi gerektiğini unutmayın. + +### Maskelenmiş Değerleri Günlüğe Kaydetme (Opsiyonel) +Denetim izlerine ihtiyacınız varsa, `custom_settings` aracılığıyla bir bayrak geçirin ve fonksiyonu ayarlayın: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Ardından şu şekilde kaydedin: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Tam Çalışan Örnek (Kopyala‑Yapıştır Hazır) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +`4111111111111111` içeren bir fiş üzerinde bu betiği çalıştırmak şu çıktıyı üretir: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +Bu, ham OCR'dan **veri temizleme**'ye kadar tüm boru hattıdır—birkaç temiz Python satırıyla sarılmıştır. + +--- + +## Sonuç + +AsposeAI’nin post‑processing kancasını, kısa bir regular‑expression rutinini ve **PCI compliance** için bir dizi en iyi uygulama ipucunu kullanarak OCR sonuçlarında **kredi kartı numaralarını nasıl maskeleyebileceğinizi** gösterdik. Çözüm tamamen bağımsızdır, OCR motorunun okuyabildiği herhangi bir görüntüde çalışır ve daha karmaşık kart formatlarını veya günlük gereksinimlerini kapsayacak şekilde genişletilebilir. + +Bir sonraki adıma hazır mısınız? Bu maskeyi yalnızca son dört rakamı saklayan bir **veritabanı ekleme** rutinine bağlamayı deneyin veya bir **toplu işlemci** entegre ederek bir klasördeki tüm fişleri gece boyunca tarayın. Ayrıca adres standartlaştırma veya dil algılama gibi diğer **OCR post‑processing** görevlerini de keşfedebilirsiniz—her biri burada kullandığımız aynı deseni izler. + +Kenar durumları, performans veya kodu farklı bir OCR kütüphanesine uyarlama hakkında sorularınız mı var? Aşağıya bir yorum bırakın, sohbeti devam ettirelim. Mutlu kodlamalar ve güvende kalın! + +![OCR işlem hattında kredi kartı numaralarının nasıl maskelendiğini gösteren diyagram](https://example.com/images/ocr-mask-flow.png "OCR post‑processing maskleme akış diyagramı") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/turkish/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..ab63a8fc9 --- /dev/null +++ b/ocr/turkish/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-04-26 +description: Python'da çıkarım süresini nasıl ölçeceğinizi öğrenin, Hugging Face'ten + bir GGUF modeli yükleyin ve daha hızlı sonuçlar için GPU kullanımını optimize edin. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: tr +og_description: Hugging Face'ten bir GGUF modeli yükleyerek ve GPU katmanlarını en + iyi performans için ayarlayarak Python'da çıkarım süresini ölçün. +og_title: Çıkarım Süresini Ölç – GGUF Modelini Yükle ve GPU'yu Optimize Et +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Çıkarım Süresini Ölç – GGUF Modelini Yükle ve GPU'yu Optimize Et +url: /tr/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Çıkarım Süresini Ölç – GGUF Modelini Yükle & GPU'yu Optimize Et + +Büyük bir dil modeli için **çıkarım süresini ölçmeniz** gerektiğinde nereden başlayacağınızı bilemediniz mi? Tek başınıza değilsiniz—birçok geliştirici, Hugging Face'ten bir GGUF dosyası çekip karışık CPU/GPU ortamında çalıştırmaya çalıştıklarında aynı duvara çarpıyor. + +Bu rehberde **GGUF modelini nasıl yüklersiniz**, Hugging Face için nasıl yapılandırırsınız ve **çıkarım süresini nasıl ölçersiniz** gösteren temiz bir Python kod parçası üzerinden ilerleyeceğiz. Ayrıca **çıkarım GPU'sunu optimize et** nasıl yapılır, böylece çalıştırmalarınız mümkün olduğunca hızlı olur, bunu da göstereceğiz. Gereksiz ayrıntı yok, sadece bugün kopyalayıp yapıştırabileceğiniz pratik, uçtan uca bir çözüm. + +## Öğrenecekleriniz + +- `AsposeAIModelConfig` ile bir **HuggingFace modelini nasıl yapılandırırsınız**. +- Hugging Face hub'ından **GGUF modelini** (`fp16` kuantizasyonu) nasıl yüklersiniz. +- Bir çıkarım çağrısı etrafında **Python kodunu zamanlamak** için yeniden kullanılabilir bir desen. +- `gpu_layers` ayarını değiştirerek **çıkarım GPU'sunu optimize et** ipuçları. +- Beklenen çıktı ve zamanlamanın mantıklı olup olmadığını nasıl doğrularsınız. + +### Önkoşullar + +| Gereksinim | Neden Önemli | +|------------|--------------| +| Python 3.9+ | Modern sözdizimi ve tip ipuçları. | +| `asposeai` paketi (veya eşdeğer SDK) | `AsposeAI` ve `AsposeAIModelConfig` sağlar. | +| `bartowski/Qwen2.5-3B-Instruct-GGUF` Hugging Face deposuna erişim | Yükleyeceğimiz GGUF modeli. | +| En az 8 GB VRAM'lı bir GPU (isteğe bağlı ama önerilir) | **çıkarım GPU'sunu optimize et** adımını etkinleştirir. | + +SDK'yı henüz kurmadıysanız, şu komutu çalıştırın: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![inference süresini ölçme diyagramı](https://example.com/measure-inference-time.png){alt="inference süresini ölçme diyagramı"} + +## Adım 1: GGUF Modelini Yükle – HuggingFace Modelini Yapılandır + +İlk olarak, Aspose AI'nin modeli nereden alacağını ve nasıl işleyeceğini belirten uygun bir yapılandırma nesnesine ihtiyacınız var. İşte **GGUF modelini yüklediğimiz** ve **huggingface model** parametrelerini yapılandırdığımız yer. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Neden Önemli:** +- `hugging_face_repo_id` Hub üzerindeki tam GGUF dosyasına işaret eder. +- `fp16` bellek bant genişliğini azaltırken modelin çoğu doğruluğunu korur. +- `gpu_layers`, **çıkarım GPU'sunu optimize et** performansını ayarladığınız kısımdır; daha fazla katman GPU'da çalıştırıldığında genellikle gecikme azalır, yeterli VRAM'ınız olduğu sürece. + +## Adım 2: Aspose AI Örneğini Oluştur + +Model tanımlandıktan sonra bir `AsposeAI` nesnesi oluşturuyoruz. Bu adım basit olsa da SDK'nın GGUF dosyasını (önbellekte yoksa) indirip GPU için derlediği yerdir. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Profesyonel İpucu:** İlk çalıştırma, model indirildiği ve GPU için derlendiği için birkaç saniye daha uzun sürecektir. Sonraki çalıştırmalar ışık hızında olur. + +## Adım 3: Çıkarım Yap ve **Çıkarım Süresini Ölç** + +İşte öğreticinin kalbi: çıkarım çağrısını `time.time()` ile sararak **çıkarım süresini ölç**. Örneği kendi içinde tutmak için küçük bir OCR sonucu da besliyoruz. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Görmeniz Gereken:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Sayı yüksek geliyorsa, muhtemelen çoğu katmanı CPU'da çalıştırıyorsunuz demektir. Bu bizi bir sonraki adıma götürüyor. + +## Adım 4: **Çıkarım GPU'sunu Optimize Et** – `gpu_layers` Ayarını İncele + +Bazen varsayılan `gpu_layers=40` ya çok agresif (OOM hatası verir) ya da çok temkinli (performans kaybına yol açar). İşte ideal noktayı bulmak için kullanabileceğiniz hızlı bir döngü: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Neden İşe Yarıyor:** +- Her çağrı, farklı bir GPU tahsisiyle çalışma zamanını yeniden oluşturur, böylece gecikme takasını anında görebilirsiniz. +- Döngü aynı zamanda **time python code** örneğini yeniden kullanılabilir bir şekilde gösterir; bunu diğer performans testlerine de uyarlayabilirsiniz. + +16 GB RTX 3080'de tipik bir çıktı şöyle görünebilir: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +Buradan, bu donanım için optimal nokta olarak `gpu_layers=40` seçersiniz. + +## Tam Çalışan Örnek + +Her şeyi bir araya getirerek, bir dosyaya (`measure_inference.py`) koyup çalıştırabileceğiniz tek bir betik: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Şu komutla çalıştırın: + +```bash +python measure_inference.py +``` + +İyi bir GPU'da bir saniyenin altında gecikme görmelisiniz; bu da **çıkarım süresini ölç** ve **çıkarım GPU'sunu optimize et** işlemlerinin başarılı olduğunu gösterir. + +--- + +## Sıkça Sorulan Sorular (SSS) + +**S: Bu diğer kuantizasyon formatlarıyla da çalışır mı?** +C: Kesinlikle. Konfigürasyonda `hugging_face_quantization="int8"` (veya `q4_0` vb.) değiştirip benchmark'ı yeniden çalıştırın. Daha düşük bellek kullanımı karşılığında hafif bir doğruluk kaybı bekleyin. + +**S: GPU'm yoksa ne yapmalıyım?** +C: `gpu_layers=0` olarak ayarlayın. Kod tamamen CPU'ya geçecek ve yine **çıkarım süresini ölç** mümkün olacak; sadece daha yüksek sayılar göreceksiniz. + +**S: Sadece modelin ileri geçişini, post‑processing'i dışarıda bırakıp zamanlamak istiyorum, mümkün mü?** +C: Evet. `ai_engine.run_model(...)` (veya eşdeğer metodu) doğrudan çağırın ve bu çağrıyı `time.time()` ile sarın. **time python code** deseni aynı kalır. + +--- + +## Sonuç + +Artık bir GGUF modeli için **çıkarım süresini ölç**, Hugging Face'ten **gguf modelini yükle** ve **çıkarım GPU'sunu optimize et** ayarlarını ince ayar yapabileceğiniz eksiksiz, kopyala‑yapıştır çözümünüz var. `gpu_layers`'ı ayarlayarak ve kuantizasyonla deney yaparak her milisaniyeyi sıkıştırabilirsiniz. + +Sonraki adımlarınız şunlar olabilir: + +- Bu zamanlama mantığını bir CI pipeline'ına entegre ederek gerilemeleri yakalamak. +- İşlem hacmini artırmak için toplu çıkarım (batch inference) keşfetmek. +- Burada kullandığımız sahte metin yerine gerçek bir OCR hattı ile modeli birleştirmek. + +İyi kodlamalar, ve gecikme sayılarınız daima düşük olsun! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/turkish/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..a60cdfb32 --- /dev/null +++ b/ocr/turkish/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-26 +description: Python'un OCR motorunu kullanarak el yazısı metni tanıyın. Görüntüden + metin nasıl çıkarılır, el yazısı modu nasıl açılır ve el yazısı notları nasıl hızlıca + okunur öğrenin. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: tr +og_description: Python ile el yazısı metni tanıyın. Bu öğreticide, görüntüden metin + nasıl çıkarılır, el yazısı modu nasıl etkinleştirilir ve basit bir OCR motoru kullanarak + el yazısı notlar nasıl okunur gösterilmektedir. +og_title: Python’da el yazısı metni tanıma – Tam OCR Rehberi +tags: +- OCR +- Python +- Handwriting Recognition +title: Python'da el yazısı metni tanıma – OCR Motoru Öğreticisi +url: /tr/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Python'da el yazısı metni tanıma – OCR Motoru Öğreticisi + +Hiç **el yazısı metni tanıma** ihtiyacı hissettiniz ama “nereden başlamalıyım?” sorusunda takıldınız mı? Tek başınıza değilsiniz. Toplantı notlarını dijitalleştiriyor ya da taranmış bir formdan veri çekiyor olun, güvenilir bir OCR sonucu elde etmek bir unicorn peşinde koşmak gibi hissettirebilir. + +İyi haber: sadece birkaç Python satırıyla **extract text from image** dosyalarından metin çıkarabilir, **turn on handwritten mode** özelliğini açabilir ve sonunda **read handwritten notes** yapabilirsiniz, karmaşık kütüphaneler aramadan. Bu rehberde **create OCR engine python** tarzı kurulumdan sonucu ekranda yazdırmaya kadar tüm süreci adım adım göstereceğiz. + +## Öğrenecekleriniz + +- `ocr` paketini kullanarak **create OCR engine python** örneği oluşturmayı. +- Hangi dil ayarının yerleşik el yazısı desteği sağladığını. +- Motorun el yazısı ile çalıştığını bilmesi için **turn on handwritten mode** çağrısının tam şeklini. +- Bir not fotoğrafını nasıl besleyeceğinizi ve **recognize handwritten text** yapmayı. +- Farklı görüntü formatlarıyla başa çıkma, yaygın sorunları giderme ve çözümü genişletme ipuçları. + +Gereksiz şeyler yok, “belgelere bak” gibi çıkmazlar yok—sadece bugün kopyalayıp yapıştırıp test edebileceğiniz tam, çalıştırılabilir bir betik. + +## Önkoşullar + +İlerlemeye başlamadan önce şunların olduğundan emin olun: + +1. Python 3.8+ yüklü (kod f‑string kullanıyor). +2. Hayali `ocr` kütüphanesi (`pip install ocr‑engine` – kullandığınız gerçek paket adıyla değiştirin). +3. El yazısı bir notun net bir görüntü dosyası (JPEG, PNG veya TIFF çalışır). +4. Biraz merak—diğer her şey aşağıda ele alınmıştır. + +> **Pro tip:** Görüntünüz gürültülü ise, OCR motoruna göndermeden önce Pillow ile hızlı bir ön işleme adımı (ör. `Image.open(...).convert('L')`) uygulayın. Bu genellikle doğruluğu artırır. + +## Python ile el yazısı metni nasıl tanımlarsınız + +Aşağıda **creates OCR engine python** nesnelerini oluşturan, el yazısı için yapılandıran ve çıkarılan dizeyi ekrana yazdıran tam betik yer alıyor. Betiği `handwriting_ocr.py` olarak kaydedin ve terminalinizden çalıştırın. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Beklenen Çıktı + +Betik başarıyla çalıştığında, aşağıdakine benzer bir şey göreceksiniz: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +OCR motoru herhangi bir karakter algılayamazsa, `text` alanı boş bir dize olacaktır. Bu durumda, görüntü kalitesini iki kez kontrol edin veya daha yüksek çözünürlüklü bir tarama deneyin. + +## Adım‑Adım Açıklama + +### Adım 1 – **create OCR engine python** örneği + +`OcrEngine` sınıfı giriş noktasıdır. Boş bir not defteri gibi düşünün—hangi dili bekleyeceğini ve el yazısı ile mi çalıştığını söyleyene kadar hiçbir şey gerçekleşmez. + +### Adım 2 – El yazısını destekleyen bir dil seçin + +`ocr.Language.EXTENDED_LATIN` sadece “İngilizce” değildir. Latin temelli bir dizi betiği bir araya getirir ve kritik olarak, el yazısı örnekleriyle eğitilmiş modelleri içerir. Bu adımı atlamak, motorun varsayılan olarak basılı metin modelini kullanması nedeniyle bozuk çıktılara yol açar. + +### Adım 3 – **turn on handwritten mode** + +`enable_handwritten_mode(True)` çağrısı iç bir bayrağı değiştirir. Motor, gerçek dünyadaki notlarda gördüğünüz düzensiz boşluklar ve değişken çizgi kalınlıkları için ayarlanmış sinir ağına geçer. Bu satırı unutmak yaygın bir hatadır; motor notlarınızı gürültü olarak değerlendirir. + +### Adım 4 – Görüntüyü besleyin ve **recognize handwritten text** + +`recognize_image` ağır işi yapar: bitmap'i ön işler, el yazısı modelinden geçirir ve `text` özelliğine sahip bir nesne döndürür. Kalite ölçütüne ihtiyacınız varsa `handwritten_result.confidence` değerini de inceleyebilirsiniz. + +### Adım 5 – Sonucu yazdırın ve **read handwritten notes** + +`print(handwritten_result.text)` başarılı bir şekilde **extract text from image** yaptığınızı doğrulamanın en basit yoludur. Üretimde muhtemelen dizeyi bir veritabanına kaydeder veya başka bir servise iletirsiniz. + +## Kenar Durumları ve Yaygın Varyasyonların Ele Alınması + +| Situation | What to Do | +|-----------|------------| +| **Görüntü döndürülmüş** | `recognize_image` çağırmadan önce Pillow ile döndürün (`Image.rotate(angle)`). | +| **Düşük kontrast** | Gri tonlamaya çevirin ve adaptif eşikleme uygulayın (`Image.point(lambda p: p > 128 and 255)`). | +| **Birden fazla sayfa** | Dosya yolu listesi üzerinde döngü yapın ve sonuçları birleştirin. | +| **Latin dışı betikler** | `EXTENDED_LATIN` yerine `ocr.Language.CHINESE` (veya uygun) kullanın ve `enable_handwritten_mode(True)` satırını koruyun. | +| **Performans endişeleri** | Birçok görüntüde aynı `ocr_engine` örneğini yeniden kullanın; her seferinde başlatmak ek yük getirir. | + +### Bellek kullanımıyla ilgili pro ipucu + +Yüzlerce notu toplu olarak işliyorsanız, işiniz bittiğinde `ocr_engine.dispose()` çağırın. Bu, Python sarmalayıcısının tutabileceği yerel kaynakları serbest bırakır. + +## Hızlı Görsel Özet + +![el yazısı metni tanıma örneği](https://example.com/handwritten-note.png "el yazısı metni tanıma örneği") + +*Yukarıdaki görüntü, betiğimizin düz metne dönüştürebileceği tipik bir el yazısı notu göstermektedir.* + +## Tam Çalışan Örnek (Tek‑Dosya Betiği) + +Kopyala‑yapıştır sadeliğini sevenler için, açıklayıcı yorumlar olmadan tüm betiği tekrar sunuyoruz: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Run it with: + +```bash +python handwriting_ocr.py +``` + +Artık konsolunuzda **recognize handwritten text** çıktısını görmelisiniz. + +## Sonuç + +Python'da **recognize handwritten text** yapmak için ihtiyacınız olan her şeyi ele aldık—yeni bir **create OCR engine python** çağrısı, doğru dili seçmek, **turn on handwritten mode** ve sonunda **extract text from image** yaparak **read handwritten notes**. + +Tek, bağımsız bir betikle toplantı karalama fotoğrafından temiz, aranabilir metne geçebilirsiniz. Sonra, çıktıyı bir doğal dil işleme hattına beslemeyi, aranabilir bir indeksde saklamayı ya da seslendirme üretimi için bir transkripsiyon servisine geri göndermeyi düşünebilirsiniz. + +### Buradan Sonra Nereye Gidilir? + +- **Toplu işleme:** Betiği bir döngü içinde sararak bir klasördeki taramaları işleyin. +- **Güvenilirlik filtresi:** Düşük kaliteli okumaları atmak için `result.confidence` kullanın. +- **Alternatif kütüphaneler:** `ocr` tam uyumlu değilse, el yazısı modu için `--psm 13` parametresiyle `pytesseract`'ı keşfedin. +- **UI entegrasyonu:** Flask veya FastAPI ile birleştirerek web tabanlı bir yükleme hizmeti sunun. + +Belirli bir görüntü formatı hakkında sorularınız mı var ya da modeli ayarlamakta yardıma mı ihtiyacınız var? Aşağıya bir yorum bırakın, iyi kodlamalar! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md b/ocr/vietnamese/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md new file mode 100644 index 000000000..be09540cc --- /dev/null +++ b/ocr/vietnamese/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-04-26 +description: Tìm hiểu cách tải mô hình HuggingFace bằng Python và trích xuất văn bản + từ hình ảnh bằng Python trong khi cải thiện độ chính xác OCR bằng Python với Aspose + OCR Cloud. +draft: false +keywords: +- download huggingface model python +- extract text from image python +- improve ocr accuracy python +- aspose ocr python +- ai post‑processor python +language: vi +og_description: Tải mô hình HuggingFace cho Python và nâng cao pipeline OCR của bạn. + Hãy làm theo hướng dẫn này để trích xuất văn bản từ hình ảnh bằng Python và cải + thiện độ chính xác OCR bằng Python. +og_title: tải mô hình huggingface python – Hướng dẫn hoàn chỉnh nâng cao OCR +tags: +- OCR +- HuggingFace +- Python +- AI +title: tải mô hình huggingface python – Hướng dẫn tăng cường OCR từng bước +url: /vi/python/general/download-huggingface-model-python-step-by-step-ocr-boost-gui/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# tải mô hình huggingface python – Hướng dẫn nâng cao OCR toàn diện + +Bạn đã bao giờ **tải mô hình HuggingFace python** và cảm thấy hơi bối rối chưa? Bạn không phải là người duy nhất. Trong nhiều dự án, khó khăn lớn nhất là đưa một mô hình tốt lên máy của bạn và sau đó làm cho kết quả OCR thực sự hữu ích. + +Trong hướng dẫn này, chúng tôi sẽ đi qua một ví dụ thực tế cho bạn thấy cách **tải mô hình HuggingFace python**, trích xuất văn bản từ hình ảnh bằng **extract text from image python**, và sau đó **improve OCR accuracy python** bằng bộ xử lý hậu kỳ AI của Aspose. Khi kết thúc, bạn sẽ có một script sẵn sàng chạy, biến một ảnh hoá đơn nhiễu thành văn bản sạch, dễ đọc—không có ma thuật, chỉ có các bước rõ ràng. + +## Những gì bạn cần + +- Python 3.9+ (code cũng chạy trên 3.11) +- Kết nối internet để tải mô hình một lần +- Gói `asposeocrcloud` (`pip install asposeocrcloud`) +- Một ảnh mẫu (ví dụ: `sample_invoice.png`) đặt trong thư mục bạn kiểm soát + +Đó là tất cả—không cần framework nặng, không cần driver GPU trừ khi bạn muốn tăng tốc. + +Bây giờ, hãy bắt đầu triển khai thực tế. + +![luồng công việc tải mô hình huggingface python](image.png "sơ đồ tải mô hình huggingface python") + +## Bước 1: Thiết lập Engine OCR và Chọn Ngôn ngữ +*(Đây là nơi chúng ta bắt đầu **extract text from image python**.)* + +```python +import asposeocrcloud as ocr +from asposeocrcloud import AsposeAI, AsposeAIModelConfig + +# Initialise the OCR engine +ocr_engine = ocr.OcrEngine() +# Tell the engine to use the English language pack +ocr_engine.set_language(ocr.Language.ENGLISH) # English language pack +``` + +**Tại sao điều này quan trọng:** +Engine OCR là hàng rào đầu tiên; việc chọn đúng gói ngôn ngữ giảm lỗi nhận dạng ký tự ngay từ đầu, là một phần cốt lõi của **improve OCR accuracy python**. + +## Bước 2: Cấu hình Model AsposeAI – Tải về từ HuggingFace +*(Ở đây chúng ta thực sự **download HuggingFace model python**.)* + +```python +# Create a configuration that points to a HuggingFace repo +ai_config = AsposeAIModelConfig( + allow_auto_download="true", # Let the SDK pull the model if missing + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="int8", # Smaller footprint, still fast + gpu_layers=20, # Use GPU if available; otherwise falls back to CPU + directory_model_path="YOUR_DIRECTORY/models" # Where the model will live locally +) + +# Initialise the AI engine with the above config +ai_engine = AsposeAI(ai_config) +``` + +**Đi gì đang diễn ra phía sau?** +Khi `allow_auto_download` được bật, SDK sẽ kết nối tới HuggingFace, tải mô hình `Qwen2.5‑3B‑Instruct‑GGUF`, và lưu vào thư mục bạn chỉ định. Đây là lõi của **download huggingface model python**—SDK thực hiện phần lớn công việc, vì vậy bạn không cần viết lệnh `git clone` hay `wget` nào. + +*Mẹo:* Giữ `directory_model_path` trên SSD để thời gian tải nhanh hơn; mô hình có kích thước khoảng 3 GB ngay cả ở dạng `int8`. + +## Bước 3: Gắn Engine AI vào Engine OCR +*(Liên kết hai thành phần để chúng ta có thể **improve OCR accuracy python**.)* + +```python +# Bind the AI post‑processor to the OCR engine +ocr_engine.set_ai_engine(ai_engine) +``` + +**Tại sao cần gắn kết?** +Engine OCR cung cấp văn bản thô, có thể chứa lỗi chính tả, dòng bị cắt, hoặc dấu câu sai. Engine AI hoạt động như một trình chỉnh sửa thông minh, làm sạch những vấn đề này—đúng là những gì bạn cần để **improve OCR accuracy python**. + +## Bước 4: Chạy OCR trên Ảnh của Bạn +*(Khoảnh khắc chúng ta cuối cùng **extract text from image python**.)* + +```python +# Perform OCR on a sample invoice image +ocr_result = ocr_engine.recognize_image("YOUR_DIRECTORY/sample_invoice.png") +``` + +`ocr_result` bây giờ chứa thuộc tính `text` với các ký tự thô mà engine đã nhận. Trong thực tế, bạn sẽ thấy một vài lỗi—có thể “Invoice” bị chuyển thành “Inv0ice” hoặc có dấu ngắt dòng giữa câu. + +## Bước 5: Làm sạch bằng AI Post‑Processor +*(Bước này trực tiếp **improve OCR accuracy python**.)* + +```python +# Run the AI‑powered post‑processor to correct spelling, grammar, and layout +corrected_result = ai_engine.run_postprocessor(ocr_result) +``` + +Model AI viết lại văn bản, áp dụng các sửa lỗi dựa trên ngôn ngữ. Vì chúng ta sử dụng mô hình được tinh chỉnh theo chỉ dẫn từ HuggingFace, đầu ra thường trôi chảy và sẵn sàng cho các bước xử lý tiếp theo. + +## Bước 6: Hiển thị Trước và Sau +*(Kiểm tra nhanh để xem chúng ta **extract text from image python** và **improve OCR accuracy python** như thế nào.)* + +```python +print("Original text:\n", ocr_result.text) +print("\nAI‑corrected text:\n", corrected_result.text) +``` + +### Kết quả Mong đợi + +``` +Original text: + Inv0ice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... + +AI‑corrected text: + Invoice #12345 + Date: 2023/07/15 + Total: $1,234.56 + ... +``` + +Chú ý cách AI đã sửa “Inv0ice” thành “Invoice” và loại bỏ các ngắt dòng lẻ. Đó là kết quả thực tế của **improve OCR accuracy python** khi sử dụng mô hình HuggingFace đã tải về. + +## Câu hỏi Thường gặp (FAQ) + +### Tôi có cần GPU để chạy mô hình không? +Không. Cài đặt `gpu_layers=20` báo cho SDK sử dụng tới 20 lớp GPU nếu có GPU tương thích; nếu không, nó sẽ quay lại CPU. Trên laptop hiện đại, chế độ CPU vẫn xử lý vài trăm token mỗi giây—đủ cho việc phân tích hoá đơn thỉnh thoảng. + +### Nếu mô hình không tải được thì sao? +Đảm bảo môi trường của bạn có thể truy cập `https://huggingface.co`. Nếu bạn đang ở sau proxy công ty, hãy đặt biến môi trường `HTTP_PROXY` và `HTTPS_PROXY`. SDK sẽ tự động thử lại, nhưng bạn cũng có thể thủ công `git lfs pull` repo vào `directory_model_path`. + +### Tôi có thể thay mô hình bằng mô hình nhỏ hơn không? +Chắc chắn. Chỉ cần thay `hugging_face_repo_id` bằng repo khác (ví dụ: `TinyLlama/TinyLlama-1.1B-Chat-v0.1`) và điều chỉnh `hugging_face_quantization` cho phù hợp. Mô hình nhỏ hơn tải nhanh hơn và tiêu tốn ít RAM hơn, dù có thể giảm một chút chất lượng chỉnh sửa. + +### Điều này giúp tôi **extract text from image python** trong các lĩnh vực khác như thế nào? +Pipeline tương tự hoạt động cho biên lai, hộ chiếu, hoặc ghi chú viết tay. Thay đổi duy nhất là gói ngôn ngữ (`ocr.Language.FRENCH`, v.v.) và có thể là một mô hình tinh chỉnh chuyên ngành từ HuggingFace. + +## Bonus: Tự động Xử lý Nhiều Tệp + +Nếu bạn có một thư mục chứa nhiều ảnh, hãy bọc lời gọi OCR trong một vòng lặp đơn giản: + +```python +import os + +image_folder = "YOUR_DIRECTORY/invoices" +for filename in os.listdir(image_folder): + if filename.lower().endswith(('.png', '.jpg', '.jpeg')): + path = os.path.join(image_folder, filename) + raw = ocr_engine.recognize_image(path) + clean = ai_engine.run_postprocessor(raw) + print(f"--- {filename} ---") + print(clean.text) + print("\n") +``` + +Thêm nhỏ này cho phép bạn **download huggingface model python** một lần, sau đó xử lý hàng chục tệp đồng thời—rất hữu ích cho việc mở rộng pipeline tự động hoá tài liệu. + +## Kết luận + +Chúng ta vừa đi qua một ví dụ hoàn chỉnh, từ đầu đến cuối, cho thấy cách **download HuggingFace model python**, **extract text from image python**, và **improve OCR accuracy python** bằng Aspose OCR Cloud và bộ xử lý hậu kỳ AI. Script đã sẵn sàng chạy, các khái niệm đã được giải thích, và bạn đã thấy kết quả trước‑và‑sau để biết nó hoạt động. + +Tiếp theo bạn muốn làm gì? Thử thay mô hình HuggingFace khác, khám phá các gói ngôn ngữ khác, hoặc đưa văn bản đã làm sạch vào pipeline NLP tiếp theo (ví dụ: trích xuất thực thể cho các mục hoá đơn). Không giới hạn, và nền tảng bạn vừa xây dựng đã vững chắc. + +Có câu hỏi hoặc ảnh khó mà OCR vẫn gặp khó khăn? Để lại bình luận bên dưới, chúng ta cùng khắc phục. Chúc lập trình vui vẻ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md b/ocr/vietnamese/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md new file mode 100644 index 000000000..a2ea6ee7a --- /dev/null +++ b/ocr/vietnamese/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-04-26 +description: Tải mô hình OCR nhanh chóng bằng Aspose OCR Python. Tìm hiểu cách đặt + thư mục mô hình, cấu hình đường dẫn mô hình và cách tải mô hình trong vài dòng. +draft: false +keywords: +- download ocr model +- how to download model +- set model directory +- configure model path +- aspose ocr python +language: vi +og_description: Tải mô hình OCR trong vài giây với Aspose OCR Python. Hướng dẫn này + cho thấy cách đặt thư mục mô hình, cấu hình đường dẫn mô hình và cách tải mô hình + một cách an toàn. +og_title: tải mô hình OCR – Hướng dẫn đầy đủ Aspose OCR Python +tags: +- OCR +- Python +- Aspose +title: Tải mô hình OCR với Aspose OCR Python – Hướng dẫn từng bước +url: /vi/python/general/download-ocr-model-with-aspose-ocr-python-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# tải mô hình ocr – Hướng dẫn đầy đủ Aspose OCR Python + +Bạn đã bao giờ thắc mắc làm sao **download ocr model** bằng Aspose OCR trong Python mà không phải lục lọi vô số tài liệu? Bạn không phải là người duy nhất. Nhiều nhà phát triển gặp khó khăn khi mô hình không có sẵn cục bộ và SDK ném ra một lỗi khó hiểu. Tin tốt là gì? Giải pháp chỉ cần vài dòng code, và bạn sẽ có mô hình sẵn sàng trong vài phút. + +Trong hướng dẫn này, chúng ta sẽ đi qua mọi thứ bạn cần biết: từ việc nhập các lớp đúng, tới **set model directory**, tới thực tế **how to download model**, và cuối cùng là xác minh đường dẫn. Khi kết thúc, bạn sẽ có thể chạy OCR trên bất kỳ hình ảnh nào chỉ với một lời gọi hàm, và bạn sẽ hiểu các tùy chọn **configure model path** giúp dự án của bạn gọn gàng. Không có phần thừa, chỉ có một ví dụ thực tế, có thể chạy ngay cho người dùng **aspose ocr python**. + +## What You’ll Learn + +- Cách nhập các lớp Aspose OCR Cloud một cách chính xác. +- Các bước chính xác để **download ocr model** tự động. +- Cách **set model directory** và **configure model path** cho các bản dựng có thể tái tạo. +- Cách xác minh mô hình đã được khởi tạo và vị trí của nó trên đĩa. +- Những lỗi thường gặp (quyền truy cập, thư mục thiếu) và cách khắc phục nhanh. + +### Prerequisites + +- Python 3.8+ đã được cài đặt trên máy của bạn. +- Gói `asposeocrcloud` (`pip install asposeocrcloud`). +- Quyền ghi vào một thư mục nơi bạn muốn lưu mô hình (ví dụ: `C:\models` hoặc `~/ocr_models`). + +--- + +## Step 1: Import Aspose OCR Cloud Classes + +Điều đầu tiên bạn cần là câu lệnh import đúng. Điều này sẽ kéo vào các lớp quản lý cấu hình mô hình và các thao tác OCR. + +```python +# Step 1: Import the Aspose OCR Cloud classes +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +``` + +*Why this matters:* `AsposeAI` là engine sẽ thực hiện OCR, trong khi `AsposeAIModelConfig` cho engine biết **where** để tìm mô hình và **whether** nó nên tự động tải về. Bỏ qua bước này hoặc import sai module sẽ gây ra `ModuleNotFoundError` trước khi bạn tới phần tải xuống. + +--- + +## Step 2: Define the Model Configuration (Set Model Directory & Configure Model Path) + +Bây giờ chúng ta cho Aspose biết nơi lưu các tệp mô hình. Đây là nơi bạn **set model directory** và **configure model path**. + +```python +# Step 2: Define the model configuration +# - allow_auto_download enables automatic retrieval of the model if missing +# - hugging_face_repo_id points to the desired model repository (e.g., GPT‑2 for demonstration) +# - directory_model_path specifies where the model files will be stored locally +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=r"YOUR_DIRECTORY" # Replace with an absolute path, e.g., r"C:\ocr_models" +) +``` + +**Tips & Gotchas** + +- **Đường dẫn tuyệt đối** tránh nhầm lẫn khi script chạy từ thư mục làm việc khác. +- Trên Linux/macOS bạn có thể dùng `"/home/you/ocr_models"`; trên Windows, đặt tiền tố `r` để xử lý các dấu gạch chéo ngược một cách nguyên văn. +- Đặt `allow_auto_download="true"` là chìa khóa để **how to download model** mà không cần viết thêm code. + +--- + +## Step 3: Create the AsposeAI Instance Using the Configuration + +Với cấu hình đã sẵn sàng, khởi tạo engine OCR. + +```python +# Step 3: Create an AsposeAI instance using the configuration +ocr_ai = AsposeAI(model_config) +``` + +*Why this matters:* Đối tượng `ocr_ai` hiện chứa cấu hình chúng ta vừa định nghĩa. Nếu mô hình không có, lời gọi tiếp theo sẽ tự động kích hoạt tải xuống—đây là cốt lõi của **how to download model** một cách không cần can thiệp. + +--- + +## Step 4: Trigger the Model Download (If Needed) + +Trước khi bạn có thể chạy OCR, cần chắc chắn mô hình thực sự đã có trên đĩa. Phương thức `is_initialized()` vừa kiểm tra vừa buộc khởi tạo. + +```python +# Step 4: Trigger model download if it hasn't been initialized yet +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # forces initialization +``` + +**What happens under the hood?** + +- Lời gọi `is_initialized()` đầu tiên trả về `False` vì thư mục mô hình trống. +- Lệnh `print` thông báo cho người dùng rằng quá trình tải xuống sắp bắt đầu. +- Lời gọi thứ hai buộc Aspose tải mô hình từ repo Hugging Face mà bạn đã chỉ định trước đó. +- Khi đã tải về, phương thức sẽ trả về `True` trong các lần kiểm tra tiếp theo. + +**Edge case:** Nếu mạng của bạn chặn Hugging Face, bạn sẽ gặp ngoại lệ. Trong trường hợp đó, hãy tải về file zip mô hình thủ công, giải nén vào `directory_model_path`, và chạy lại script. + +--- + +## Step 5: Report the Local Path Where the Model Is Now Available + +Sau khi tải xong, bạn có thể muốn biết các tệp đã được lưu ở đâu. Điều này giúp việc gỡ lỗi và thiết lập pipeline CI. + +```python +# Step 5: Report the local path where the model is now available +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +Kết quả điển hình trông như sau: + +``` +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Bây giờ bạn đã **download ocr model** thành công, đã đặt thư mục và xác nhận đường dẫn. + +--- + +## Visual Overview + +Dưới đây là một sơ đồ đơn giản thể hiện luồng từ cấu hình tới mô hình sẵn sàng sử dụng. + +![lưu đồ tải mô hình ocr hiển thị cấu hình, tải tự động và đường dẫn cục bộ](/images/download-ocr-model-flow.png) + +*Alt text includes the primary keyword for SEO.* + +--- + +## Common Variations & How to Handle Them + +### 1. Using a Different Model Repository + +Nếu bạn cần một mô hình khác ngoài `openai/gpt2`, chỉ cần thay giá trị `hugging_face_repo_id`: + +```python +model_config.hugging_face_repo_id = "microsoft/trocr-base-stage1" +``` + +Đảm bảo repo là công khai hoặc bạn đã thiết lập token cần thiết trong môi trường. + +### 2. Disabling Automatic Download + +Đôi khi bạn muốn tự kiểm soát việc tải xuống (ví dụ, trong môi trường không có internet). Đặt `allow_auto_download` thành `"false"` và gọi script tải tùy chỉnh trước khi khởi tạo: + +```python +model_config.allow_auto_download = "false" +# Manually download the model here... +``` + +### 3. Changing the Model Directory at Runtime + +Bạn có thể cấu hình lại đường dẫn mà không cần tạo lại đối tượng `AsposeAI`: + +```python +ocr_ai.model_config.directory_model_path = r"/new/path/to/models" +ocr_ai.is_initialized() # re‑initialize with the new path +``` + +--- + +## Pro Tips for Production Use + +- **Cache the model**: Giữ thư mục trên một ổ mạng chia sẻ nếu nhiều dịch vụ cần cùng một mô hình. Điều này tránh tải lại không cần thiết. +- **Version pinning**: Repo Hugging Face có thể cập nhật. Để khóa vào một phiên bản cụ thể, thêm `@v1.0.0` vào ID repo (`"openai/gpt2@v1.0.0"`). +- **Permissions**: Đảm bảo người dùng chạy script có quyền đọc/ghi trên `directory_model_path`. Trên Linux, `chmod 755` thường đủ. +- **Logging**: Thay các câu lệnh `print` đơn giản bằng mô-đun `logging` của Python để quan sát tốt hơn trong các ứng dụng lớn. + +--- + +## Full Working Example (Copy‑Paste Ready) + +```python +# Full script: download ocr model, set model directory, and verify path +from asposeocrcloud import AsposeAI, AsposeAIModelConfig +import os + +# ------------------------------------------------------------------ +# 1️⃣ Define where the model should live +# ------------------------------------------------------------------ +model_dir = r"C:\ocr_models" # <-- change to your preferred folder +os.makedirs(model_dir, exist_ok=True) # ensure the folder exists + +# ------------------------------------------------------------------ +# 2️⃣ Configure the model (auto‑download enabled) +# ------------------------------------------------------------------ +model_config = AsposeAIModelConfig( + allow_auto_download="true", + hugging_face_repo_id="openai/gpt2", + directory_model_path=model_dir +) + +# ------------------------------------------------------------------ +# 3️⃣ Instantiate the OCR engine +# ------------------------------------------------------------------ +ocr_ai = AsposeAI(model_config) + +# ------------------------------------------------------------------ +# 4️⃣ Force download if needed +# ------------------------------------------------------------------ +if not ocr_ai.is_initialized(): + print("Downloading model …") + ocr_ai.is_initialized() # triggers the download + +# ------------------------------------------------------------------ +# 5️⃣ Show where the model lives +# ------------------------------------------------------------------ +print("Model is ready at:", ocr_ai.get_local_path()) +``` + +**Expected output** (first run will download, subsequent runs will skip download): + +``` +Downloading model … +Model is ready at: C:\ocr_models\openai_gpt2 +``` + +Chạy script lại; bạn sẽ chỉ thấy dòng đường dẫn vì mô hình đã được lưu trong bộ nhớ cache. + +--- + +## Conclusion + +Chúng ta vừa hoàn thành quy trình đầy đủ để **download ocr model** bằng Aspose OCR Python, đã chỉ ra cách **set model directory**, và giải thích các chi tiết của **configure model path**. Chỉ với vài dòng code, bạn có thể tự động tải mô hình, tránh các bước thủ công, và giữ cho pipeline OCR của mình có thể tái tạo. + +Tiếp theo, bạn có thể khám phá lời gọi OCR thực tế (`ocr_ai.recognize_image(...)`) hoặc thử một mô hình Hugging Face khác để cải thiện độ chính xác. Dù sao, nền tảng bạn đã xây dựng ở đây—cấu hình rõ ràng, tải tự động, và xác minh đường dẫn—sẽ làm cho bất kỳ tích hợp nào trong tương lai trở nên dễ dàng. + +Có câu hỏi về các trường hợp đặc biệt, hoặc muốn chia sẻ cách bạn điều chỉnh thư mục mô hình cho triển khai trên đám mây? Hãy để lại bình luận bên dưới, và chúc bạn lập trình vui vẻ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md b/ocr/vietnamese/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md new file mode 100644 index 000000000..fa83dfd0e --- /dev/null +++ b/ocr/vietnamese/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-04-26 +description: Cách xử lý hậu kỳ kết quả OCR và trích xuất văn bản kèm tọa độ. Tìm hiểu + giải pháp từng bước sử dụng đầu ra có cấu trúc và chỉnh sửa bằng AI. +draft: false +keywords: +- how to post‑process OCR +- extract text with coordinates +- OCR structured output +- AI post‑processing OCR +- bounding box OCR +language: vi +og_description: Cách xử lý hậu kỳ kết quả OCR và trích xuất văn bản kèm tọa độ. Hãy + theo dõi hướng dẫn toàn diện này để có quy trình làm việc đáng tin cậy. +og_title: Cách Xử Lý Hậu OCR – Hướng Dẫn Toàn Diện +tags: +- OCR +- Python +- AI +- Text Extraction +title: Cách xử lý hậu kỳ OCR – Trích xuất văn bản kèm tọa độ trong Python +url: /vi/python/general/how-to-post-process-ocr-extract-text-with-coordinates-in-pyt/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách Tiền Xử Lý OCR – Trích Xuất Văn Bản Kèm Tọa Độ trong Python + +Bạn đã bao giờ cần **cách tiền xử lý OCR** vì kết quả thô bị nhiễu hoặc lệch không? Bạn không phải là người duy nhất. Trong nhiều dự án thực tế—quét hoá đơn, số hoá biên lai, hoặc thậm chí tăng cường trải nghiệm AR—động cơ OCR cung cấp cho bạn các từ thô, nhưng bạn vẫn phải làm sạch chúng và theo dõi vị trí của mỗi từ trên trang. Đó là lúc chế độ đầu ra có cấu trúc kết hợp với bộ xử lý hậu xử lý dựa trên AI tỏa sáng. + +Trong tutorial này chúng ta sẽ đi qua một pipeline Python hoàn chỉnh, có thể chạy được, **trích xuất văn bản kèm tọa độ** từ một hình ảnh, thực hiện bước sửa lỗi dựa trên AI, và in ra mỗi từ cùng với vị trí `(x, y)` của nó. Không thiếu import, không có các shortcut mơ hồ “xem tài liệu”—chỉ có một giải pháp tự chứa mà bạn có thể đưa vào dự án ngay hôm nay. + +> **Pro tip:** Nếu bạn đang dùng một thư viện OCR khác, hãy tìm chế độ “structured” hoặc “layout”; các khái niệm vẫn giữ nguyên. + +--- + +## Yêu Cầu Trước + +| Yêu Cầu | Tại sao quan trọng | +|-------------|----------------| +| Python 3.9+ | Cú pháp hiện đại và hỗ trợ type hints | +| Thư viện `ocr` hỗ trợ `OutputMode.STRUCTURED` (ví dụ: `myocr` giả tưởng) | Cần thiết cho dữ liệu bounding‑box | +| Module hậu xử lý AI (có thể là OpenAI, HuggingFace, hoặc mô hình tùy chỉnh) | Cải thiện độ chính xác sau OCR | +| Tập tin ảnh (`input.png`) trong thư mục làm việc | Nguồn dữ liệu sẽ được đọc | + +Nếu bất kỳ mục nào trên nghe lạ, chỉ cần cài đặt các gói placeholder bằng `pip install myocr ai‑postproc`. Đoạn code dưới đây cũng bao gồm các stub dự phòng để bạn có thể thử luồng mà không cần các thư viện thực. + +--- + +## Bước 1: Kích Hoạt Chế Độ Đầu Ra Có Cấu Trúc cho Động Cơ OCR + +Điều đầu tiên chúng ta làm là yêu cầu động cơ OCR cung cấp nhiều hơn chỉ văn bản thuần. Đầu ra có cấu trúc trả về mỗi từ cùng với bounding box và điểm tin cậy, điều này thiết yếu cho **trích xuất văn bản kèm tọa độ** sau này. + +```python +# step1_structured_output.py +import myocr as ocr # fictional OCR library + +# Initialize the engine (replace with your actual init code) +engine = ocr.Engine() + +# Switch to structured mode – this makes the engine emit word‑level data +engine.set_output_mode(ocr.OutputMode.STRUCTURED) + +print("✅ Structured output mode enabled") +``` + +*Lý do quan trọng:* Nếu không bật chế độ có cấu trúc, bạn sẽ chỉ nhận được một chuỗi dài, và sẽ mất thông tin không gian cần thiết để phủ lên văn bản trên ảnh hoặc đưa vào phân tích layout downstream. + +--- + +## Bước 2: Nhận Dạng Hình Ảnh và Ghi Lại Các Từ, Hộp, và Độ Tin Cậy + +Bây giờ chúng ta đưa ảnh vào engine. Kết quả là một đối tượng chứa danh sách các đối tượng từ, mỗi đối tượng cung cấp `text`, `x`, `y`, `width`, `height`, và `confidence`. + +```python +# step2_recognize.py +from pathlib import Path + +# Path to your image +image_path = Path("YOUR_DIRECTORY/input.png") + +# Perform OCR – returns a StructuredResult with .words collection +structured_result = engine.recognize_image(str(image_path)) + +print(f"🔎 Detected {len(structured_result.words)} words") +``` + +*Trường hợp đặc biệt:* Nếu ảnh rỗng hoặc không đọc được, `structured_result.words` sẽ là một danh sách rỗng. Thực hành tốt là kiểm tra và xử lý một cách nhẹ nhàng. + +--- + +## Bước 3: Chạy Xử Lý Hậu Xử Lý Dựa Trên AI Trong Khi Bảo Quản Vị Trí + +Ngay cả các engine OCR tốt nhất cũng có thể sai—ví dụ “O” vs. “0” hoặc thiếu dấu. Một mô hình AI được huấn luyện trên văn bản chuyên ngành có thể sửa những lỗi này. Điều then chốt là chúng ta giữ nguyên tọa độ gốc để bố cục không gian vẫn nguyên vẹn. + +```python +# step3_ai_postprocess.py +import ai_postproc as ai # placeholder for your AI module + +# The AI post‑processor expects the structured result and returns a new one +corrected_result = ai.run_postprocessor(structured_result) + +print("🤖 AI post‑processing complete") +``` + +*Tại sao chúng ta bảo quản tọa độ:* Nhiều tác vụ downstream (ví dụ: tạo PDF, gán nhãn AR) phụ thuộc vào vị trí chính xác. AI chỉ thay đổi trường `text`, để nguyên `x`, `y`, `width`, `height`. + +--- + +## Bước 4: Lặp Qua Các Từ Đã Được Sửa và Hiển Thị Văn Bản Cùng Tọa Độ + +Cuối cùng, chúng ta duyệt qua các từ đã được sửa và in ra mỗi từ cùng với góc trên‑trái `(x, y)`. Điều này đáp ứng mục tiêu **trích xuất văn bản kèm tọa độ**. + +```python +# step4_display.py +for recognized_word in corrected_result.words: + # Using f‑string for clean formatting + print(f"{recognized_word.text} (x:{recognized_word.x}, y:{recognized_word.y})") +``` + +**Kết quả mong đợi (ví dụ):** + +``` +Invoice (x:45, y:112) +Number (x:120, y:112) +12345 (x:190, y:112) +Total (x:45, y:250) +$ (x:120, y:250) +199.99 (x:130, y:250) +``` + +Mỗi dòng hiển thị từ đã sửa và vị trí chính xác trên ảnh gốc. + +--- + +## Ví Dụ Hoàn Chỉnh Hoạt Động + +Dưới đây là một script duy nhất gắn kết mọi thứ lại với nhau. Bạn có thể sao chép‑dán, điều chỉnh các câu lệnh import cho phù hợp với thư viện thực tế của mình, và chạy trực tiếp. + +```python +# ocr_postprocess_demo.py +""" +Complete demo: how to post‑process OCR and extract text with coordinates. +Works with any OCR library exposing a structured output mode and an AI post‑processor. +""" + +import sys +from pathlib import Path + +# ---------------------------------------------------------------------- +# 1️⃣ Imports – replace these with your real packages +# ---------------------------------------------------------------------- +try: + import myocr as ocr # OCR engine with structured output + import ai_postproc as ai # AI correction module +except ImportError: # Fallback stubs for quick testing + class DummyWord: + def __init__(self, text, x, y, w, h, conf): + self.text = text + self.x = x + self.y = y + self.width = w + self.height = h + self.confidence = conf + + class DummyResult: + def __init__(self, words): + self.words = words + + class StubEngine: + class OutputMode: + STRUCTURED = "structured" + + def set_output_mode(self, mode): + print(f"[Stub] set_output_mode({mode})") + + def recognize_image(self, path): + # Very simple fake OCR output + sample = [ + DummyWord("Invoice", 45, 112, 60, 20, 0.98), + DummyWord("Number", 120, 112, 55, 20, 0.96), + DummyWord("12345", 190, 112, 40, 20, 0.97), + DummyWord("Total", 45, 250, 50, 20, 0.99), + DummyWord("$", 120, 250, 10, 20, 0.95), + DummyWord("199.99", 130, 250, 55, 20, 0.94), + ] + return DummyResult(sample) + + class StubAI: + @staticmethod + def run_postprocessor(structured_result): + # Pretend we corrected "12345" to "12346" + for w in structured_result.words: + if w.text == "12345": + w.text = "12346" + return structured_result + + engine = StubEngine() + ai = StubAI + +# ---------------------------------------------------------------------- +# 2️⃣ Enable structured output +# ---------------------------------------------------------------------- +engine.set_output_mode(ocr.Engine.OutputMode.STRUCTURED) + +# ---------------------------------------------------------------------- +# 3️⃣ Recognize image +# ---------------------------------------------------------------------- +image_path = Path("YOUR_DIRECTORY/input.png") +if not image_path.is_file(): + print(f"⚠️ Image not found at {image_path}. Using stub data.") +structured_result = engine.recognize_image(str(image_path)) + +# ---------------------------------------------------------------------- +# 4️⃣ AI post‑processing +# ---------------------------------------------------------------------- +corrected_result = ai.run_postprocessor(structured_result) + +# ---------------------------------------------------------------------- +# 5️⃣ Display results +# ---------------------------------------------------------------------- +print("\n🗒️ Final OCR output with coordinates:") +for word in corrected_result.words: + print(f"{word.text} (x:{word.x}, y:{word.y})") +``` + +**Chạy script** + +```bash +python ocr_postprocess_demo.py +``` + +Nếu bạn đã cài đặt các thư viện thực, script sẽ xử lý `input.png` của bạn. Nếu không, triển khai stub cho phép bạn thấy luồng và kết quả dự kiến mà không cần phụ thuộc bên ngoài. + +--- + +## Câu Hỏi Thường Gặp (FAQ) + +| Câu Hỏi | Trả Lời | +|----------|--------| +| *Does this work with Tesseract?* | Tesseract không cung cấp chế độ có cấu trúc ngay lập tức, nhưng các wrapper như `pytesseract.image_to_data` trả về bounding boxes mà bạn có thể đưa vào cùng một bộ hậu xử lý AI. | +| *What if I need the bottom‑right corner instead of top‑left?* | Mỗi đối tượng từ cũng cung cấp `width` và `height`. Tính `x2 = x + width` và `y2 = y + height` để có góc đối diện. | +| *Can I batch‑process multiple images?* | Chắc chắn. Đặt các bước trong một vòng lặp `for image_path in Path("folder").glob("*.png"):` và thu thập kết quả cho mỗi file. | +| *How do I choose an AI model for correction?* | Đối với văn bản chung, một GPT‑2 nhỏ được fine‑tuned trên lỗi OCR hoạt động tốt. Đối với dữ liệu chuyên ngành (ví dụ: toa thuốc y tế), hãy huấn luyện mô hình sequence‑to‑sequence trên dữ liệu cặp nhiễu‑sạch. | +| *Is the confidence score useful after AI correction?* | Bạn vẫn có thể giữ điểm tin cậy gốc để debug, nhưng AI có thể trả về điểm tin cậy riêng nếu mô hình hỗ trợ. | + +--- + +## Trường Hợp Cạnh & Thực Hành Tốt Nhất + +1. **Empty or corrupted images** – luôn xác minh `structured_result.words` không rỗng trước khi tiếp tục. +2. **Non‑Latin scripts** – đảm bảo engine OCR được cấu hình cho ngôn ngữ mục tiêu; bộ hậu xử lý AI phải được huấn luyện trên cùng một script. +3. **Performance** – việc sửa lỗi bằng AI có thể tốn kém. Lưu cache kết quả nếu bạn sẽ tái sử dụng cùng một ảnh, hoặc chạy bước AI bất đồng bộ. +4. **Coordinate system** – các thư viện OCR có thể dùng các gốc khác nhau (top‑left vs. bottom‑left). Điều chỉnh cho phù hợp khi phủ lên PDF hoặc canvas. + +--- + +## Kết Luận + +Bạn đã có một công thức toàn diện, đầu‑cuối‑đầu cho **cách tiền xử lý OCR** và **trích xuất văn bản kèm tọa độ** một cách đáng tin cậy. Bằng cách bật đầu ra có cấu trúc, đưa kết quả qua lớp sửa lỗi AI, và bảo quản các bounding box gốc, bạn có thể biến các bản quét OCR nhiễu thành văn bản sạch, có không gian, sẵn sàng cho các tác vụ downstream như tạo PDF, tự động nhập dữ liệu, hoặc phủ lên thực tế tăng cường. + +Sẵn sàng cho bước tiếp theo? Hãy thử thay thế AI stub bằng một lời gọi OpenAI `gpt‑4o‑mini`, hoặc tích hợp pipeline vào FastAPI + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md b/ocr/vietnamese/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md new file mode 100644 index 000000000..648fb8ce7 --- /dev/null +++ b/ocr/vietnamese/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-04-26 +description: Cách nhận dạng hình ảnh nhanh chóng bằng Python. Tìm hiểu quy trình nhận + dạng hình ảnh, xử lý hàng loạt và tự động hoá nhận dạng hình ảnh bằng AI. +draft: false +keywords: +- how to recognize images +- image recognition pipeline +- how to batch images +- automate image recognition +- recognize images with ai +language: vi +og_description: Cách nhận dạng hình ảnh nhanh chóng bằng Python. Hướng dẫn này sẽ + đi qua quy trình nhận dạng hình ảnh, xử lý theo lô và tự động hoá bằng AI. +og_title: Cách Nhận Dạng Hình Ảnh – Tự Động Hóa Quy Trình Nhận Dạng Hình Ảnh +tags: +- image-processing +- python +- ai +title: Cách Nhận Dạng Hình Ảnh – Tự Động Hóa Quy Trình Nhận Dạng Hình Ảnh +url: /vi/python/general/how-to-recognize-images-automate-an-image-recognition-pipeli/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách Nhận Diện Hình Ảnh – Tự Động Hóa Quy Trình Nhận Diện Hình Ảnh + +Bạn đã bao giờ tự hỏi **cách nhận diện hình ảnh** mà không cần viết hàng ngàn dòng code chưa? Bạn không phải là người duy nhất—nhiều nhà phát triển gặp cùng một rào cản khi lần đầu cần xử lý hàng chục hoặc hàng trăm bức ảnh. Tin tốt là gì? Với một vài bước gọn gàng, bạn có thể khởi động một quy trình nhận diện hình ảnh hoàn chỉnh, tự động batch, chạy và dọn dẹp mọi thứ một cách tự động. + +Trong tutorial này, chúng ta sẽ đi qua một ví dụ đầy đủ, có thể chạy ngay, cho thấy **cách batch hình ảnh**, đưa từng ảnh vào một engine AI, xử lý hậu kỳ kết quả, và cuối cùng giải phóng tài nguyên. Khi kết thúc, bạn sẽ có một script tự chứa mà có thể đưa vào bất kỳ dự án nào, dù bạn đang xây dựng một công cụ gắn thẻ ảnh, một hệ thống kiểm soát chất lượng, hay một bộ tạo dữ liệu nghiên cứu. + +## Những Điều Bạn Sẽ Học + +- **Cách nhận diện hình ảnh** bằng một engine AI mô phỏng (mẫu này giống hệt với các dịch vụ thực như TensorFlow, PyTorch, hoặc các API đám mây). +- Cách xây dựng một **pipeline nhận diện hình ảnh** xử lý batch một cách hiệu quả. +- Cách **tự động hoá nhận diện hình ảnh** để bạn không phải lặp lại việc duyệt file thủ công mỗi lần. +- Các mẹo để mở rộng pipeline và giải phóng tài nguyên một cách an toàn. + +> **Yêu cầu trước:** Python 3.8+, kiến thức cơ bản về hàm và vòng lặp, và một vài file ảnh (hoặc đường dẫn) bạn muốn xử lý. Không cần thư viện bên ngoài cho ví dụ cốt lõi, nhưng chúng tôi sẽ đề cập đến nơi bạn có thể tích hợp các SDK AI thực tế. + +![Sơ đồ cách nhận diện hình ảnh trong quy trình xử lý batch](pipeline.png "Sơ đồ cách nhận diện hình ảnh") + +## Bước 1: Batch Hình Ảnh – Cách Batch Hình Ảnh Hiệu Quả + +Trước khi AI thực hiện bất kỳ công việc nặng nào, bạn cần một tập hợp các hình ảnh để đưa vào. Hãy nghĩ đây như danh sách mua sắm; engine sẽ lấy từng mục trong danh sách một cách tuần tự. + +```python +# Step 1 – define the batch of images you want to process +# Replace the placeholder list with real file paths or image objects. +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", + # add as many items as you need +] +``` + +**Tại sao cần batch?** +Batching giảm lượng code lặp lại bạn phải viết và giúp việc thêm song song hoá sau này trở nên đơn giản. Nếu bạn cần xử lý 10 000 bức ảnh, bạn chỉ cần thay đổi nguồn của `image_batch`—phần còn lại của pipeline vẫn không thay đổi. + +## Bước 2: Chạy Pipeline Nhận Diện Hình Ảnh (Recognize Images with AI) + +Bây giờ chúng ta kết nối batch với bộ nhận diện thực tế. Trong môi trường thực, bạn có thể gọi `torchvision.models` hoặc một endpoint đám mây; ở đây chúng tôi mô phỏng hành vi để tutorial tự chứa. + +```python +# Mock classes to simulate an AI engine and post‑processor. +# Replace these with your actual SDK imports, e.g.: +# from my_ai_lib import Engine, PostProcessor + +class MockEngine: + def recognize_image(self, img_path): + # Pretend we run a neural net and return a raw dict. + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + # Simple heuristic: if filename contains a known animal, label it. + name = raw_result["image"].lower() + if "cat" in name: + label = "cat" + confidence = 0.92 + elif "dog" in name: + label = "dog" + confidence = 0.88 + else: + label = "other" + confidence = 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# Initialise the mock services +engine = MockEngine() +postprocessor = MockPostProcessor() +``` + +```python +# Step 2 – recognize each image using the engine +recognized_results = [] # We'll store the final outputs here +for img_path in image_batch: + raw_result = engine.recognize_image(img_path) # <-- image recognition call + corrected = postprocessor.run(raw_result) # <-- post‑process the raw output + recognized_results.append(corrected) +``` + +**Giải thích:** +- `engine.recognize_image` là trái tim của **pipeline nhận diện hình ảnh**; nó có thể là một lời gọi tới mô hình deep‑learning hoặc một REST API. +- `postprocessor.run` minh hoạ **tự động hoá nhận diện hình ảnh** bằng cách chuẩn hoá các dự đoán thô thành một dictionary sạch sẽ mà bạn có thể lưu hoặc stream. +- Chúng ta thu thập mỗi dict `corrected` vào `recognized_results` để các bước tiếp theo (ví dụ: chèn vào cơ sở dữ liệu) trở nên dễ dàng. + +## Bước 3: Xử Lý Hậu Kỳ và Lưu Trữ – Tự Động Hoá Kết Quả Nhận Diện Hình Ảnh + +Sau khi có danh sách dự đoán gọn gàng, bạn thường muốn lưu trữ chúng. Ví dụ dưới đây ghi ra file CSV; bạn có thể thay thế bằng cơ sở dữ liệu hoặc hàng đợi tin nhắn nếu muốn. + +```python +import csv +from pathlib import Path + +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") +``` + +**Tại sao lại dùng CSV?** +CSV có thể đọc được ở mọi nơi—Excel, pandas, thậm chí các trình soạn thảo văn bản thuần cũng mở được. Nếu sau này bạn cần **tự động hoá nhận diện hình ảnh** ở quy mô lớn, hãy thay khối ghi bằng một lệnh bulk insert vào data lake của bạn. + +## Bước 4: Dọn Dẹp – Giải Phóng Tài Nguyên AI Một Cách An Toàn + +Nhiều SDK AI cấp phát bộ nhớ GPU hoặc tạo các worker thread. Quên giải phóng chúng có thể gây rò rỉ bộ nhớ và crash. Mặc dù các đối tượng mô phỏng của chúng tôi không cần điều này, chúng tôi sẽ minh hoạ mẫu đúng cách. + +```python +# Step 4 – release resources after the batch is processed +def free_resources(): + # In real code you might call: + # engine.shutdown() + # postprocessor.close() + print("🧹 Resources have been released.") + +free_resources() +``` + +Chạy script sẽ in ra một thông báo xác nhận thân thiện, cho bạn biết pipeline đã hoàn thành sạch sẽ. + +## Script Hoàn Chỉnh + +Kết hợp mọi thứ lại, đây là chương trình đầy đủ, sẵn sàng copy‑and‑paste: + +```python +# -------------------------------------------------------------- +# How to Recognize Images – Full Image Recognition Pipeline +# -------------------------------------------------------------- + +import csv +from pathlib import Path + +# ---------- Mock AI Engine & Post‑Processor ---------- +class MockEngine: + def recognize_image(self, img_path): + return {"image": img_path, "raw_label": "unknown", "confidence": 0.0} + +class MockPostProcessor: + def run(self, raw_result): + name = raw_result["image"].lower() + if "cat" in name: + label, confidence = "cat", 0.92 + elif "dog" in name: + label, confidence = "dog", 0.88 + else: + label, confidence = "other", 0.65 + return {"image": raw_result["image"], "label": label, "confidence": confidence} + +# ---------- Step 1: Batch Your Images ---------- +image_batch = [ + "photos/cat1.jpg", + "photos/dog2.jpg", + "photos/bird3.png", +] + +# ---------- Step 2: Run the Image Recognition Pipeline ---------- +engine = MockEngine() +postprocessor = MockPostProcessor() + +recognized_results = [] +for img_path in image_batch: + raw = engine.recognize_image(img_path) + corrected = postprocessor.run(raw) + recognized_results.append(corrected) + +# ---------- Step 3: Store the Results ---------- +output_file = Path("recognition_results.csv") +with output_file.open(mode="w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=["image", "label", "confidence"]) + writer.writeheader() + for result in recognized_results: + writer.writerow(result) + +print(f"✅ Results saved to {output_file.resolve()}") + +# ---------- Step 4: Clean Up ---------- +def free_resources(): + # Replace with real SDK cleanup calls if needed. + print("🧹 Resources have been released.") + +free_resources() +``` + +### Kết Quả Dự Kiến + +Khi bạn chạy script (giả sử ba đường dẫn placeholder tồn tại), bạn sẽ thấy một đầu ra giống như: + +``` +✅ Results saved to /your/project/recognition_results.csv +🧹 Resources have been released. +``` + +Và file `recognition_results.csv` được tạo sẽ chứa: + +| hình ảnh | nhãn | độ tin cậy | +|---------------------|--------|------------| +| photos/cat1.jpg | cat | 0.92 | +| photos/dog2.jpg | dog | 0.88 | +| photos/bird3.png | other | 0.65 | + +## Kết Luận + +Bạn đã có một ví dụ toàn diện, đầu‑từ‑đầu về **cách nhận diện hình ảnh** trong Python, bao gồm **pipeline nhận diện hình ảnh**, xử lý batch, và tự động hoá hậu kỳ. Mẫu này có thể mở rộng: thay thế các lớp mô phỏng bằng mô hình thực, đưa vào một `image_batch` lớn hơn, và bạn sẽ có một giải pháp sẵn sàng cho sản xuất. + +Muốn tiến xa hơn? Hãy thử các bước tiếp theo: + +- Thay `MockEngine` bằng mô hình TensorFlow hoặc PyTorch để có dự đoán thực. +- Song song hoá vòng lặp với `concurrent.futures.ThreadPoolExecutor` để tăng tốc các batch lớn. +- Kết nối CSV writer với một bucket lưu trữ đám mây để **tự động hoá nhận diện hình ảnh** trên các worker phân tán. + +Hãy thoải mái thử nghiệm, phá vỡ, và sau đó sửa lại—đó là cách bạn thực sự làm chủ các pipeline nhận diện hình ảnh. Nếu gặp khó khăn hoặc có ý tưởng cải tiến, hãy để lại bình luận bên dưới. Chúc bạn lập trình vui vẻ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md b/ocr/vietnamese/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md new file mode 100644 index 000000000..d6a5d928a --- /dev/null +++ b/ocr/vietnamese/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-04-26 +description: Ẩn nhanh số thẻ tín dụng bằng xử lý hậu kỳ AsposeAI OCR. Tìm hiểu về + tuân thủ PCI, ẩn bằng biểu thức chính quy và làm sạch dữ liệu trong hướng dẫn từng + bước. +draft: false +keywords: +- mask credit card numbers +- PCI compliance +- OCR post‑processing +- AsposeAI +- regular expression masking +- data sanitization +language: vi +og_description: Ẩn số thẻ tín dụng trong kết quả OCR bằng AsposeAI. Hướng dẫn này + bao gồm tuân thủ PCI, việc ẩn bằng biểu thức chính quy và làm sạch dữ liệu. +og_title: Ẩn Số Thẻ Tín Dụng – Hướng Dẫn Xử Lý Hậu Kỳ OCR Python Toàn Diện +tags: +- OCR +- Python +- security +title: Che giấu số thẻ tín dụng trong đầu ra OCR – Hướng dẫn Python toàn diện +url: /vi/python/general/mask-credit-card-numbers-in-ocr-output-complete-python-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ẩn Số Thẻ Tín Dụng – Hướng Dẫn Python Đầy Đủ + +Bạn đã bao giờ cần **ẩn số thẻ tín dụng** trong văn bản lấy trực tiếp từ công cụ OCR chưa? Bạn không phải là người duy nhất. Trong các ngành được quy định, việc để lộ toàn bộ PAN (Primary Account Number) có thể khiến bạn gặp rắc rối với các kiểm toán viên tuân thủ PCI. Tin tốt? Với vài dòng Python và hook post‑processing của AsposeAI, bạn có thể tự động ẩn tám chữ số ở giữa và giữ an toàn. + +Trong tutorial này chúng ta sẽ đi qua một kịch bản thực tế: chạy OCR trên ảnh biên lai, sau đó áp dụng một hàm **OCR post‑processing** tùy chỉnh để làm sạch bất kỳ dữ liệu PCI nào. Khi kết thúc, bạn sẽ có một đoạn mã có thể tái sử dụng, có thể chèn vào bất kỳ workflow nào của AsposeAI, cùng với một vài mẹo thực tiễn để xử lý các trường hợp biên và mở rộng giải pháp. + +## Những Điều Bạn Sẽ Học + +- Cách đăng ký một post‑processor tùy chỉnh với **AsposeAI**. +- Tại sao cách **regular expression masking** vừa nhanh vừa đáng tin cậy. +- Những kiến thức cơ bản về **PCI compliance** liên quan đến việc làm sạch dữ liệu. +- Cách mở rộng mẫu để hỗ trợ nhiều định dạng thẻ hoặc số quốc tế. +- Kết quả mong đợi và cách xác minh rằng việc ẩn đã hoạt động. + +> **Prerequisites** – Bạn nên có môi trường Python 3 hoạt động, gói Aspose.AI for OCR đã được cài đặt (`pip install aspose-ocr`), và một ảnh mẫu (ví dụ: `receipt.png`) chứa số thẻ tín dụng. Không cần dịch vụ bên ngoài nào khác. + +--- + +## Bước 1: Định Nghĩa Post‑Processor Ẩn Số Thẻ Tín Dụng + +Trọng tâm của giải pháp nằm trong một hàm nhỏ nhận kết quả OCR, chạy quy trình **regular expression masking**, và trả về văn bản đã được làm sạch. + +```python +def mask_pci(data, settings): + """ + Replace the middle 8 digits of any 16‑digit card number with asterisks. + Keeps the first and last four digits visible for reference. + """ + import re + # Pattern captures groups: first 4 digits, middle 8, last 4 + pattern = r'(\d{4})\d{8}(\d{4})' + # Replace middle portion with **** + return re.sub(pattern, r'\1****\2', data.text) +``` + +**Tại sao cách này hoạt động:** +- Biểu thức chính quy `(\d{4})\d{8}(\d{4})` khớp chính xác 16 chữ số liên tiếp, định dạng phổ biến cho Visa, MasterCard và nhiều loại thẻ khác. +- Bằng cách bắt nhóm bốn chữ số đầu và bốn chữ số cuối (`\1` và `\2`), chúng ta giữ lại đủ thông tin để gỡ lỗi trong khi tuân thủ các quy tắc **PCI compliance** cấm lưu trữ toàn bộ PAN. +- Thay thế `\1****\2` ẩn tám chữ số nhạy cảm ở giữa, biến `1234567812345678` thành `1234****5678`. + +> **Pro tip:** Nếu bạn cần hỗ trợ số American Express 15 chữ số, hãy thêm một mẫu thứ hai như `r'(\d{4})\d{6}(\d{5})'` và thực hiện cả hai thay thế tuần tự. + +--- + +## Bước 2: Khởi Tạo Engine AsposeAI + +Trước khi chúng ta có thể gắn post‑processor, chúng ta cần một thể hiện của engine OCR. AsposeAI gói sẵn mô hình OCR và một API đơn giản cho việc xử lý tùy chỉnh. + +```python +from aspose.ocr import AsposeAI + +# Initialise the AI engine – it will handle image loading, recognition, and post‑processing +ai = AsposeAI() +``` + +**Tại sao khởi tạo ở đây?** +Tạo đối tượng `AsposeAI` một lần và tái sử dụng nó cho nhiều ảnh giảm thiểu chi phí. Engine cũng lưu cache các mô hình ngôn ngữ, giúp tăng tốc các lần gọi tiếp theo—rất hữu ích khi bạn quét hàng loạt biên lai. + +--- + +## Bước 3: Đăng Ký Hàm Ẩn Tùy Chỉnh + +AsposeAI cung cấp phương thức `set_post_processor` cho phép bạn gắn bất kỳ callable nào. Chúng ta truyền hàm `mask_pci` cùng với một dictionary cài đặt tùy chọn (hiện tại để trống). + +```python +# Register our masking routine; custom_settings can hold flags like "log_masked" if you expand later +ai.set_post_processor(mask_pci, custom_settings={}) +``` + +**Đi gì đang diễn ra phía sau?** +Khi bạn sau này gọi `run_postprocessor`, AsposeAI sẽ chuyển kết quả OCR thô cho `mask_pci`. Hàm nhận một đối tượng nhẹ (`data`) chứa văn bản đã nhận dạng, và bạn trả về một chuỗi mới. Thiết kế này giữ nguyên phần OCR gốc trong khi cho phép bạn thực thi các chính sách **data sanitization** ở một nơi duy nhất. + +--- + +## Bước 4: Chạy OCR Trên Ảnh Biên Lai + +Bây giờ engine đã biết cách làm sạch đầu ra, chúng ta đưa một ảnh vào. Đối với tutorial này, chúng ta giả sử bạn đã có một đối tượng `engine` được cấu hình với ngôn ngữ và độ phân giải phù hợp. + +```python +# Assume `engine` is a pre‑configured OCR object (e.g., with language='en') +ocr_engine = engine +raw_result = ocr_engine.recognize_image("receipt.png") +``` + +**Tip:** Nếu bạn chưa có đối tượng được cấu hình trước, bạn có thể tạo một cái mới bằng: + +```python +from aspose.ocr import OcrEngine +ocr_engine = OcrEngine(language='en') +``` + +Lệnh `recognize_image` trả về một đối tượng có thuộc tính `text` chứa chuỗi thô, chưa được ẩn. + +--- + +## Bước 5: Áp Dụng Post‑Processor Đã Đăng Ký + +Với dữ liệu OCR thô trong tay, chúng ta chuyển nó cho instance AI. Engine tự động chạy hàm `mask_pci` mà chúng ta đã đăng ký trước đó. + +```python +# This triggers the post‑processor and returns a new result object +final_result = ai.run_postprocessor(raw_result) +``` + +**Tại sao dùng `run_postprocessor` thay vì gọi hàm trực tiếp?** +Việc này giữ cho workflow nhất quán, đặc biệt khi bạn có nhiều post‑processor (ví dụ: kiểm tra chính tả, phát hiện ngôn ngữ). AsposeAI xếp chúng theo thứ tự bạn đăng ký, đảm bảo kết quả xác định. + +--- + +## Bước 6: Xác Minh Kết Quả Đã Được Làm Sạch + +Cuối cùng, hãy in ra văn bản đã được làm sạch và xác nhận rằng bất kỳ số thẻ tín dụng nào đã được ẩn đúng cách. + +```python +print(final_result.text) +``` + +**Kết quả mong đợi** (đoạn trích): + +``` +Purchase at Café Latte – Total: $4.75 +Card: 1234****5678 +Date: 2026-04-25 +Thank you! +``` + +Nếu biên lai không chứa số thẻ, văn bản sẽ không thay đổi—không có gì để ẩn, không có gì để lo lắng. + +--- + +## Xử Lý Các Trường Hợp Biên và Các Biến Thể Thông Thường + +### Nhiều Số Thẻ Trong Một Tài Liệu +Nếu biên lai có hơn một PAN (ví dụ: thẻ khách hàng cộng với thẻ thanh toán), biểu thức chính quy sẽ chạy toàn cục, tự động ẩn tất cả các khớp. Không cần thêm mã nào. + +### Định Dạng Không Tiêu Chuẩn +Đôi khi OCR chèn khoảng trắng hoặc dấu gạch ngang (`1234 5678 1234 5678` hoặc `1234-5678-1234-5678`). Mở rộng mẫu để bỏ qua các ký tự này: + +```python +pattern = r'(\d{4})[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}' +``` + +Phần `[ -]?` được thêm vào cho phép có hoặc không có khoảng trắng hoặc dấu gạch ngang giữa các khối chữ số. + +### Thẻ Quốc Tế +Đối với PAN 19 chữ số được sử dụng ở một số khu vực, bạn có thể mở rộng mẫu: + +```python +pattern = r'(\d{4})\d{11,15}(\d{4})' +``` + +Chỉ cần nhớ rằng **PCI compliance** vẫn yêu cầu ẩn các chữ số ở giữa, bất kể độ dài. + +### Ghi Log Các Giá Trị Đã Ẩn (Tùy Chọn) +Nếu bạn cần lưu vết audit, hãy truyền một cờ qua `custom_settings` và điều chỉnh hàm: + +```python +def mask_pci(data, settings): + import re, logging + pattern = r'(\d{4})\d{8}(\d{4})' + def repl(match): + masked = f"{match.group(1)}****{match.group(2)}" + if settings.get('log'): + logging.info(f"Masked PAN: {masked}") + return masked + return re.sub(pattern, repl, data.text) +``` + +Sau đó đăng ký với: + +```python +ai.set_post_processor(mask_pci, custom_settings={'log': True}) +``` + +--- + +## Ví Dụ Hoàn Chỉnh (Sẵn Sàng Sao Chép) + +```python +# ------------------------------------------------------------ +# Mask Credit Card Numbers in OCR Output – Complete Example +# ------------------------------------------------------------ +import re +from aspose.ocr import AsposeAI, OcrEngine + +# 1️⃣ Define the post‑processor +def mask_pci(data, settings): + """ + Hide the middle eight digits of any 16‑digit credit‑card number. + """ + pattern = r'(\d{4})\d{8}(\d{4})' # keep first & last 4 digits + return re.sub(pattern, r'\1****\2', data.text) + +# 2️⃣ Initialise the OCR engine and AsposeAI wrapper +ocr_engine = OcrEngine(language='en') # configure as needed +ai = AsposeAI() + +# 3️⃣ Register the masking function +ai.set_post_processor(mask_pci, custom_settings={}) + +# 4️⃣ Run OCR on a sample receipt +raw_result = ocr_engine.recognize_image("receipt.png") + +# 5️⃣ Apply post‑processing (masking) +final_result = ai.run_postprocessor(raw_result) + +# 6️⃣ Display sanitized text +print("Sanitized OCR output:") +print(final_result.text) +``` + +Chạy script này trên một biên lai chứa `4111111111111111` sẽ tạo ra: + +``` +Sanitized OCR output: +Purchase at Bookstore – $12.99 +Card: 4111****1111 +Date: 2026-04-26 +``` + +Đó là toàn bộ pipeline—từ OCR thô đến **data sanitization**—được gói gọn trong vài dòng Python sạch sẽ. + +--- + +## Kết Luận + +Chúng tôi vừa cho bạn thấy cách **ẩn số thẻ tín dụng** trong kết quả OCR bằng hook post‑processing của AsposeAI, một quy trình regular‑expression ngắn gọn, và một vài mẹo thực hành tốt cho **PCI compliance**. Giải pháp hoàn toàn tự chứa, hoạt động với bất kỳ ảnh nào mà engine OCR có thể đọc, và có thể mở rộng để bao phủ các định dạng thẻ phức tạp hơn hoặc yêu cầu ghi log. + +Sẵn sàng bước tiếp? Hãy thử kết hợp hàm ẩn này với một quy trình **chèn vào cơ sở dữ liệu** chỉ lưu lại bốn chữ số cuối để tham chiếu, hoặc tích hợp một **batch processor** quét toàn bộ thư mục biên lai qua đêm. Bạn cũng có thể khám phá các tác vụ **OCR post‑processing** khác như chuẩn hoá địa chỉ hoặc phát hiện ngôn ngữ—mỗi tác vụ đều theo cùng một mẫu chúng ta đã dùng ở đây. + +Có câu hỏi về các trường hợp biên, hiệu năng, hoặc cách điều chỉnh mã cho thư viện OCR khác? Để lại bình luận bên dưới, và chúng ta sẽ tiếp tục thảo luận. Chúc lập trình vui vẻ và luôn bảo mật! + +![Diagram illustrating how mask credit card numbers works in an OCR pipeline](https://example.com/images/ocr-mask-flow.png "Diagram of OCR post‑processing masking flow") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md b/ocr/vietnamese/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md new file mode 100644 index 000000000..c87258000 --- /dev/null +++ b/ocr/vietnamese/python/general/measure-inference-time-load-gguf-model-optimize-gpu/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-04-26 +description: Học cách đo thời gian suy luận trong Python, tải mô hình GGUF từ Hugging + Face và tối ưu việc sử dụng GPU để đạt kết quả nhanh hơn. +draft: false +keywords: +- measure inference time +- load gguf model +- time python code +- configure huggingface model +- optimize inference gpu +language: vi +og_description: Đo thời gian suy luận trong Python bằng cách tải mô hình GGUF từ Hugging + Face và điều chỉnh các lớp GPU để đạt hiệu năng tối ưu. +og_title: Đo Thời Gian Suy Đoán – Tải Mô Hình GGUF & Tối Ưu GPU +tags: +- Aspose AI +- Python +- HuggingFace +- GPU inference +title: Đo thời gian suy luận – Tải mô hình GGUF & Tối ưu GPU +url: /vi/python/general/measure-inference-time-load-gguf-model-optimize-gpu/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Đo Thời Gian Suy Luận – Tải Mô Hình GGUF & Tối Ưu GPU + +Bạn đã bao giờ cần **đo thời gian suy luận** cho một mô hình ngôn ngữ lớn nhưng không biết bắt đầu từ đâu chưa? Bạn không đơn độc—nhiều nhà phát triển gặp cùng một khó khăn khi lần đầu tải tệp GGUF từ Hugging Face và cố gắng chạy nó trên môi trường hỗn hợp CPU/GPU. + +Trong hướng dẫn này, chúng tôi sẽ hướng dẫn **cách tải một mô hình GGUF**, cấu hình nó cho Hugging Face, và **đo thời gian suy luận** bằng một đoạn mã Python sạch sẽ. Đồng thời, chúng tôi sẽ chỉ cho bạn cách **tối ưu GPU cho suy luận** để các lần chạy của bạn nhanh nhất có thể. Không có phần thừa, chỉ có giải pháp thực tế, từ đầu đến cuối mà bạn có thể sao chép‑dán ngay hôm nay. + +## Những Điều Bạn Sẽ Học + +- Cách **cấu hình một mô hình HuggingFace** với `AsposeAIModelConfig`. +- Các bước chính xác để **tải một mô hình GGUF** (phân lượng `fp16`) từ hub Hugging Face. +- Mẫu có thể tái sử dụng cho **đo thời gian mã Python** quanh một lời gọi suy luận. +- Mẹo để **tối ưu GPU cho suy luận** bằng cách điều chỉnh `gpu_layers`. +- Kết quả mong đợi và cách xác minh thời gian đo được hợp lý. + +### Yêu Cầu Trước + +| Yêu Cầu | Lý do quan trọng | +|-------------|----------------| +| Python 3.9+ | Cú pháp hiện đại và gợi ý kiểu. | +| `asposeai` package (hoặc SDK tương đương) | Cung cấp `AsposeAI` và `AsposeAIModelConfig`. | +| Truy cập repo Hugging Face `bartowski/Qwen2.5-3B-Instruct-GGUF` | Mô hình GGUF mà chúng ta sẽ tải. | +| GPU có ít nhất 8 GB VRAM (tùy chọn nhưng được khuyến nghị) | Cho phép thực hiện bước **tối ưu GPU cho suy luận**. | + +Nếu bạn chưa cài đặt SDK, hãy chạy: + +```bash +pip install asposeai # replace with the actual package name if different +``` + +--- + +![sơ đồ đo thời gian suy luận](https://example.com/measure-inference-time.png){alt="sơ đồ đo thời gian suy luận"} + +## Bước 1: Tải Mô Hình GGUF – Cấu Hình Mô Hình HuggingFace + +Điều đầu tiên bạn cần là một đối tượng cấu hình phù hợp, cho biết Aspose AI nơi lấy mô hình và cách xử lý nó. Đây là nơi chúng ta **tải một mô hình GGUF** và **cấu hình các tham số huggingface model**. + +```python +from asposeai import AsposeAI, AsposeAIModelConfig + +# Define the configuration – note the fp16 quantization and GPU layers +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", # 16‑bit floats – a good speed/accuracy trade‑off + gpu_layers=40 # First 40 layers on GPU, the rest on CPU +) +``` + +**Tại sao điều này quan trọng:** +- `hugging_face_repo_id` chỉ tới tệp GGUF chính xác trên Hub. +- `fp16` giảm băng thông bộ nhớ trong khi vẫn giữ phần lớn độ chính xác của mô hình. +- `gpu_layers` là công tắc bạn điều chỉnh khi muốn **tối ưu GPU cho suy luận**; nhiều lớp hơn trên GPU thường đồng nghĩa với độ trễ nhanh hơn, với điều kiện bạn có đủ VRAM. + +## Bước 2: Tạo Instance Aspose AI + +Bây giờ mô hình đã được mô tả, chúng ta khởi tạo một đối tượng `AsposeAI`. Bước này đơn giản, nhưng ở đây SDK thực sự tải xuống tệp GGUF (nếu chưa được lưu trong bộ nhớ đệm) và chuẩn bị môi trường chạy. + +```python +# Instantiate the engine with the configuration above +ai_engine = AsposeAI(model_config) +``` + +**Mẹo chuyên nghiệp:** Lần chạy đầu tiên sẽ mất vài giây lâu hơn vì mô hình đang được tải xuống và biên dịch cho GPU. Các lần chạy tiếp theo sẽ cực kỳ nhanh. + +## Bước 3: Thực Hiện Suy Luận và **Đo Thời Gian Suy Luận** + +Đây là phần cốt lõi của hướng dẫn: bao quanh lời gọi suy luận bằng `time.time()` để **đo thời gian suy luận**. Chúng tôi cũng cung cấp một kết quả OCR nhỏ để ví dụ tự chứa. + +```python +import time +from asposeai import ocr # assuming the OCR module lives under asposeai + +# Prepare a dummy OCR result – replace with your real data when needed +dummy_input = ocr.OcrResult(text="sample text") + +# Start the timer, run the post‑processor, then stop the timer +start_time = time.time() +inference_result = ai_engine.run_postprocessor(dummy_input) +elapsed = time.time() - start_time + +print("Inference time:", round(elapsed, 4), "seconds") +print("Result preview:", inference_result[:200]) # show first 200 chars +``` + +**Kết quả bạn nên thấy:** +``` +Inference time: 0.8421 seconds +Result preview: +``` + +Nếu con số cao, có thể bạn đang chạy phần lớn các lớp trên CPU. Điều này dẫn chúng ta tới bước tiếp theo. + +## Bước 4: **Tối Ưu GPU cho Suy Luận** – Điều Chỉnh `gpu_layers` + +Đôi khi giá trị mặc định `gpu_layers=40` quá mạnh (gây OOM) hoặc quá thận trọng (làm giảm hiệu năng). Dưới đây là một vòng lặp nhanh bạn có thể dùng để tìm điểm cân bằng: + +```python +def benchmark(gpu_layer_count: int) -> float: + model_config.gpu_layers = gpu_layer_count + engine = AsposeAI(model_config) # re‑initialize with new setting + start = time.time() + engine.run_postprocessor(dummy_input) # warm‑up run + elapsed = time.time() - start + return elapsed + +# Test a few configurations +for layers in [20, 30, 40, 50]: + try: + t = benchmark(layers) + print(f"gpu_layers={layers} → {round(t, 4)} s") + except RuntimeError as e: + print(f"gpu_layers={layers} failed: {e}") +``` + +**Tại sao cách này hiệu quả:** +- Mỗi lần gọi sẽ xây dựng lại môi trường chạy với một phân bổ GPU khác nhau, cho phép bạn thấy ngay sự đánh đổi độ trễ. +- Vòng lặp cũng minh họa **đo thời gian mã python** theo cách có thể tái sử dụng, bạn có thể áp dụng cho các bài kiểm tra hiệu năng khác. + +Kết quả điển hình trên RTX 3080 16 GB có thể trông như sau: + +``` +gpu_layers=20 → 1.1325 s +gpu_layers=30 → 0.9783 s +gpu_layers=40 → 0.8421 s +gpu_layers=50 → RuntimeError: CUDA out of memory +``` + +Từ đó, bạn sẽ chọn `gpu_layers=40` là điểm tối ưu cho phần cứng này. + +## Ví Dụ Hoàn Chỉnh Hoạt Động + +Kết hợp mọi thứ lại, đây là một script duy nhất bạn có thể lưu vào file (`measure_inference.py`) và chạy: + +```python +# measure_inference.py +import time +from asposeai import AsposeAI, AsposeAIModelConfig, ocr + +# 1️⃣ Configure and load the GGUF model +model_config = AsposeAIModelConfig( + hugging_face_repo_id="bartowski/Qwen2.5-3B-Instruct-GGUF", + hugging_face_quantization="fp16", + gpu_layers=40 +) +ai_engine = AsposeAI(model_config) + +# 2️⃣ Prepare dummy OCR input +input_data = ocr.OcrResult(text="sample text") + +# 3️⃣ Measure inference time +start = time.time() +result = ai_engine.run_postprocessor(input_data) +elapsed = time.time() - start + +print(f"Inference time: {round(elapsed, 4)} seconds") +print("Result preview:", result[:200]) +``` + +Chạy nó bằng: + +```bash +python measure_inference.py +``` + +Bạn sẽ thấy độ trễ dưới một giây trên GPU đủ tốt, xác nhận rằng bạn đã thành công **đo thời gian suy luận** và **tối ưu GPU cho suy luận**. + +--- + +## Câu Hỏi Thường Gặp (FAQs) + +**Q: Điều này có hoạt động với các định dạng phân lượng khác không?** +A: Chắc chắn. Thay `hugging_face_quantization="int8"` (hoặc `q4_0`, v.v.) trong cấu hình và chạy lại benchmark. Mong đợi một sự đánh đổi: giảm sử dụng bộ nhớ so với độ chính xác hơi giảm. + +**Q: Nếu tôi không có GPU thì sao?** +A: Đặt `gpu_layers=0`. Mã sẽ hoàn toàn chuyển sang CPU, và bạn vẫn có thể **đo thời gian suy luận**—chỉ cần chờ các con số cao hơn. + +**Q: Tôi có thể đo thời gian chỉ phần forward của mô hình, bỏ qua post‑processing không?** +A: Có. Gọi trực tiếp `ai_engine.run_model(...)` (hoặc phương thức tương đương) và bao quanh lời gọi đó bằng `time.time()`. Mẫu cho **đo thời gian mã python** vẫn giữ nguyên. + +--- + +## Kết Luận + +Bạn giờ đã có một giải pháp hoàn chỉnh, sao chép‑dán để **đo thời gian suy luận** cho mô hình GGUF, **tải mô hình gguf** từ Hugging Face, và tinh chỉnh các cài đặt **tối ưu GPU cho suy luận**. Bằng cách điều chỉnh `gpu_layers` và thử nghiệm các định dạng phân lượng, bạn có thể tối đa hoá từng miligiây hiệu năng. + +Tiếp theo, bạn có thể muốn: + +- Tích hợp logic đo thời gian này vào pipeline CI để phát hiện regressions. +- Khám phá suy luận batch để cải thiện thông lượng hơn nữa. +- Kết hợp mô hình với pipeline OCR thực tế thay vì văn bản giả mà chúng tôi đã dùng ở đây. + +Chúc lập trình vui vẻ, và hy vọng các con số độ trễ của bạn luôn thấp! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md b/ocr/vietnamese/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md new file mode 100644 index 000000000..0da7e7bb7 --- /dev/null +++ b/ocr/vietnamese/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-26 +description: Nhận dạng văn bản viết tay bằng công cụ OCR của Python. Tìm hiểu cách + trích xuất văn bản từ hình ảnh, bật chế độ viết tay và đọc nhanh các ghi chú viết + tay. +draft: false +keywords: +- recognize handwritten text +- extract text from image +- read handwritten notes +- turn on handwritten mode +- create OCR engine python +language: vi +og_description: Nhận dạng văn bản viết tay bằng Python. Hướng dẫn này cho thấy cách + trích xuất văn bản từ hình ảnh, bật chế độ viết tay và đọc các ghi chú viết tay + bằng một công cụ OCR đơn giản. +og_title: Nhận dạng văn bản viết tay trong Python – Hướng dẫn OCR toàn diện +tags: +- OCR +- Python +- Handwriting Recognition +title: Nhận dạng văn bản viết tay trong Python – Hướng dẫn công cụ OCR +url: /vi/python/general/recognize-handwritten-text-in-python-ocr-engine-tutorial/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Nhận dạng văn bản viết tay trong Python – Hướng dẫn Engine OCR + +Bạn đã bao giờ cần **nhận dạng văn bản viết tay** nhưng cảm thấy bế tắc ở câu “bắt đầu từ đâu?”? Bạn không phải là người duy nhất. Dù bạn đang số hoá các ghi chú trong cuộc họp hay trích xuất dữ liệu từ một mẫu quét, việc có được kết quả OCR đáng tin cậy có thể giống như việc săn bắt một con kỳ lân. + +Tin tốt: chỉ với vài dòng Python, bạn có thể **trích xuất văn bản từ hình ảnh**, **bật chế độ viết tay**, và cuối cùng **đọc các ghi chú viết tay** mà không cần tìm kiếm các thư viện khó tìm. Trong hướng dẫn này, chúng tôi sẽ đi qua toàn bộ quy trình, từ việc thiết lập kiểu **create OCR engine python** đến việc in kết quả trên màn hình. + +## Những gì bạn sẽ học + +- Cách tạo một thể hiện **create OCR engine python** bằng cách sử dụng gói `ocr`. +- Cài đặt ngôn ngữ nào cung cấp hỗ trợ viết tay tích hợp sẵn. +- Lệnh chính xác để **bật chế độ viết tay** để engine biết bạn đang xử lý chữ viết nối. +- Cách đưa một bức ảnh ghi chú và **nhận dạng văn bản viết tay** từ đó. +- Mẹo xử lý các định dạng hình ảnh khác nhau, khắc phục các lỗi thường gặp, và mở rộng giải pháp. + +Không có phần thừa, không có “xem tài liệu” dẫn đến bế tắc—chỉ có một script hoàn chỉnh, có thể chạy được mà bạn có thể sao chép‑dán và thử ngay hôm nay. + +## Yêu cầu trước + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có: + +1. Python 3.8+ đã được cài đặt (code sử dụng f‑strings). +2. Thư viện giả định `ocr` (`pip install ocr‑engine` – thay bằng tên gói thực tế bạn đang dùng). +3. Một file ảnh rõ ràng của ghi chú viết tay (JPEG, PNG, hoặc TIFF đều được). +4. Một chút tò mò—mọi thứ còn lại sẽ được đề cập bên dưới. + +> **Pro tip:** Nếu ảnh của bạn có nhiễu, hãy thực hiện một bước tiền xử lý nhanh với Pillow (ví dụ, `Image.open(...).convert('L')`) trước khi gửi tới engine OCR. Điều này thường tăng độ chính xác. + +## Cách nhận dạng văn bản viết tay với Python + +Dưới đây là script đầy đủ mà **creates OCR engine python** các đối tượng, cấu hình chúng cho viết tay, và in chuỗi đã trích xuất. Lưu lại dưới tên `handwriting_ocr.py` và chạy từ terminal của bạn. + +```python +# handwriting_ocr.py +import ocr # The OCR library that provides OcrEngine +import os + +def main(): + # Step 1: Create an OCR engine instance + # This is the core object that will do all the heavy lifting. + ocr_engine = ocr.OcrEngine() + + # Step 2: Choose a language that includes handwritten support. + # EXTENDED_LATIN covers most Western alphabets and knows how to + # handle cursive strokes. + ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) + + # Step 3: Turn on handwritten mode. + # Without this flag the engine assumes printed text and will miss + # most of the nuances in a scribble. + ocr_engine.enable_handwritten_mode(True) + + # Step 4: Define the path to your handwritten image. + # Replace the placeholder with the actual location of your file. + image_path = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") + + # Basic validation – makes debugging easier. + if not os.path.isfile(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + + # Step 5: Recognize text from the image. + # The recognize_image method returns a result object that holds + # both the raw text and confidence scores. + handwritten_result = ocr_engine.recognize_image(image_path) + + # Step 6: Display the extracted text. + # This is where you finally **read handwritten notes** programmatically. + print("=== Extracted Text ===") + print(handwritten_result.text) + +if __name__ == "__main__": + main() +``` + +### Kết quả mong đợi + +Khi script chạy thành công, bạn sẽ thấy điều gì đó như sau: + +``` +=== Extracted Text === +Meeting notes: +- Discuss quarterly targets +- Assign tasks to Alice & Bob +- Follow‑up email by Friday +``` + +Nếu engine OCR không phát hiện được ký tự nào, trường `text` sẽ là một chuỗi rỗng. Trong trường hợp đó, hãy kiểm tra lại chất lượng ảnh hoặc thử quét với độ phân giải cao hơn. + +## Giải thích từng bước + +### Bước 1 – **create OCR engine python** instance + +Lớp `OcrEngine` là điểm vào. Hãy nghĩ nó như một cuốn sổ trống—không có gì xảy ra cho đến khi bạn chỉ định ngôn ngữ mong đợi và liệu bạn đang xử lý viết tay hay không. + +### Bước 2 – Chọn ngôn ngữ hỗ trợ viết tay + +`ocr.Language.EXTENDED_LATIN` không chỉ là “English”. Nó gói một tập hợp các script dựa trên Latin và, quan trọng hơn, bao gồm các mô hình đã được huấn luyện trên mẫu viết nối. Bỏ qua bước này thường dẫn đến đầu ra rối vì engine mặc định sử dụng mô hình văn bản in. + +### Bước 3 – **turn on handwritten mode** + +Gọi `enable_handwritten_mode(True)` sẽ bật một cờ nội bộ. Engine sau đó chuyển sang mạng nơ-ron được tinh chỉnh cho khoảng cách không đều và độ rộng nét biến đổi mà bạn thấy trong các ghi chú thực tế. Quên dòng này là lỗi phổ biến; engine sẽ coi các nét vẽ của bạn là nhiễu. + +### Bước 4 – Đưa ảnh vào và **recognize handwritten text** + +`recognize_image` thực hiện công việc nặng: tiền xử lý bitmap, chạy qua mô hình viết tay, và trả về một đối tượng có thuộc tính `text`. Bạn cũng có thể kiểm tra `handwritten_result.confidence` nếu cần chỉ số chất lượng. + +### Bước 5 – In kết quả và **read handwritten notes** + +`print(handwritten_result.text)` là cách đơn giản nhất để xác nhận rằng bạn đã **extract text from image** thành công. Trong môi trường production, bạn có thể lưu chuỗi này vào cơ sở dữ liệu hoặc truyền cho dịch vụ khác. + +## Xử lý các trường hợp đặc biệt & biến thể phổ biến + +| Tình huống | Cách thực hiện | +|-----------|----------------| +| **Hình ảnh bị xoay** | Sử dụng Pillow để xoay (`Image.rotate(angle)`) trước khi gọi `recognize_image`. | +| **Độ tương phản thấp** | Chuyển sang ảnh xám và áp dụng ngưỡng thích ứng (`Image.point(lambda p: p > 128 and 255)`). | +| **Nhiều trang** | Lặp qua danh sách các đường dẫn file và nối kết quả lại. | +| **Ngôn ngữ không phải Latin** | Thay `EXTENDED_LATIN` bằng `ocr.Language.CHINESE` (hoặc phù hợp) và giữ `enable_handwritten_mode(True)`. | +| **Mối quan ngại về hiệu năng** | Tái sử dụng cùng một thể hiện `ocr_engine` cho nhiều ảnh; khởi tạo mỗi lần sẽ gây tốn tài nguyên. | + +### Pro tip về việc sử dụng bộ nhớ + +Nếu bạn đang xử lý hàng trăm ghi chú trong một lô, hãy gọi `ocr_engine.dispose()` sau khi hoàn thành. Điều này giải phóng các tài nguyên gốc mà wrapper Python có thể đang giữ. + +## Tóm tắt nhanh bằng hình ảnh + +![ví dụ nhận dạng văn bản viết tay](https://example.com/handwritten-note.png "ví dụ nhận dạng văn bản viết tay") + +*Hình ảnh trên cho thấy một ghi chú viết tay điển hình mà script của chúng ta có thể chuyển thành văn bản thuần.* + +## Ví dụ làm việc đầy đủ (Script một file) + +Đối với những ai yêu thích sự đơn giản sao chép‑dán, đây là toàn bộ nội dung một lần nữa mà không có các chú thích giải thích: + +```python +import ocr, os + +ocr_engine = ocr.OcrEngine() +ocr_engine.set_language(ocr.Language.EXTENDED_LATIN) +ocr_engine.enable_handwritten_mode(True) + +img = os.path.join("YOUR_DIRECTORY", "handwritten_note.jpg") +if not os.path.isfile(img): + raise FileNotFoundError(f"Image not found: {img}") + +result = ocr_engine.recognize_image(img) +print("=== Extracted Text ===") +print(result.text) +``` + +Chạy nó với: + +```bash +python handwriting_ocr.py +``` + +Bạn sẽ thấy đầu ra **recognize handwritten text** hiện ra trong console. + +## Kết luận + +Chúng ta vừa bao quát mọi thứ bạn cần để **recognize handwritten text** trong Python—bắt đầu từ một lời gọi **create OCR engine python** mới, chọn ngôn ngữ phù hợp, **turn on handwritten mode**, và cuối cùng **extract text from image** để **read handwritten notes**. + +Trong một script tự chứa duy nhất, bạn có thể chuyển từ một bức ảnh mờ của bản vẽ họp sang văn bản sạch, có thể tìm kiếm được. Tiếp theo, hãy cân nhắc đưa đầu ra vào một pipeline ngôn ngữ tự nhiên, lưu trữ trong chỉ mục có thể tìm kiếm, hoặc thậm chí đưa lại vào dịch vụ chuyển đổi để tạo giọng nói. + +### Bạn có thể tiếp tục ở đâu? + +- **Xử lý hàng loạt:** Đặt script trong một vòng lặp để xử lý một thư mục các file quét. +- **Lọc theo độ tin cậy:** Sử dụng `result.confidence` để loại bỏ các kết quả chất lượng thấp. +- **Thư viện thay thế:** Nếu `ocr` không phù hợp, khám phá `pytesseract` với `--psm 13` cho chế độ viết tay. +- **Tích hợp UI:** Kết hợp với Flask hoặc FastAPI để cung cấp dịch vụ tải lên qua web. + +Có câu hỏi về định dạng ảnh cụ thể hoặc cần trợ giúp tinh chỉnh mô hình? Hãy để lại bình luận bên dưới, và chúc bạn lập trình vui vẻ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file