from flask import Flask, render_template, request, jsonify
from PIL import Image
import pytesseract
import os

app = Flask(__name__)

# Tesseractのパス（環境に合わせて変更）
pytesseract.pytesseract.tesseract_cmd = \
  r"C:\Program Files\Tesseract-OCR\tesseract.exe"

UPLOAD_FOLDER = "static"
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER

@app.route("/")
def index():
  return render_template("index.html")

@app.route("/ocr", methods=["POST"])
def ocr():
  if "file" not in request.files:
    return jsonify({"text": "ファイルがありません"})

  file = request.files["file"]
  if file.filename == "":
    return jsonify({"text": "ファイルが選択されていません"})

  filepath = os.path.join(app.config["UPLOAD_FOLDER"], file.filename)
  file.save(filepath)

  try:
    image = Image.open(filepath)

    # 日本語 + 英語 OCR
    text = pytesseract.image_to_string(image, lang="jpn+eng")

    return jsonify({"text": text})

  except Exception as e:
    return jsonify({"text": f"エラー: {str(e)}"})

if __name__ == "__main__":
  app.run(debug=True)