#Tesseract OCR for Windows: https://tesseract-ocr.github.io/tessdoc/Downloads.html
# tessdata/jpn.traineddata が必要
# pip install Pillow PyMuPDF pytesseract

import os
import sys
from PIL import Image
import pytesseract


image_file = "IMG_8583.jpg"  # 実際の画像ファイル名に置き換えてください

def ocr_from_image(image_path, lang='jpn'):
    """
    画像ファイルから文字認識を行い、抽出されたテキストを返します。

    Args:
        image_path (str): 画像ファイルのパス。
        lang (str): 認識する言語。'jpn' (日本語) や 'eng' (英語) など。
                    複数指定する場合は 'jpn+eng' のように '+' で連結します。

    Returns:
        str: 抽出されたテキスト。
    """
    try:
        img = Image.open(image_path)
        text = pytesseract.image_to_string(img, lang=lang)
        return text
    except FileNotFoundError:
        return f"エラー: ファイル '{image_path}' が見つかりません。"
    except Exception as e:
        return f"OCR処理中にエラーが発生しました: {e}"

if __name__ == "__main__":
    if not os.path.exists(image_file):
    # テスト用のダミー画像ファイルを作成 (実際には既存の画像を使用してください)
        try:
        # Pillowを使って簡単なダミー画像を生成
            from PIL import ImageDraw, ImageFont
            img = Image.new('RGB', (400, 200), color = (255, 255, 255))
            d = ImageDraw.Draw(img)
            try:
            # フォントのパスはシステムによって異なる場合があります
                font = ImageFont.truetype("arial.ttf", 30) # Windowsの場合の例
            except IOError:
                font = ImageFont.load_default() # デフォルトフォントを使用

            d.text((50, 50), "これはテスト画像です。", fill=(0, 0, 0), font=font)
            d.text((50, 100), "Hello, OCR!", fill=(0, 0, 0), font=font)
            img.save(image_file)
            print(f"ダミー画像 '{image_file}' を作成しました。")
        except Exception as e:
            print(f"ダミー画像の作成に失敗しました: {e}")
            print("既存の画像ファイルを使用するか、手動で画像ファイルを作成してください。")

    print(f"\n--- 画像ファイル '{image_file}' のOCR結果 ---")
    extracted_text_image = ocr_from_image(image_file, lang='jpn+eng')
    print(extracted_text_image)