|
import os |
|
import uuid |
|
from flask import Flask, request, jsonify |
|
from flask_cors import CORS |
|
from werkzeug.utils import secure_filename |
|
import torch |
|
from transformers import TrOCRProcessor, VisionEncoderDecoderModel |
|
from PIL import Image |
|
import cv2 |
|
import numpy as np |
|
|
|
app = Flask(__name__) |
|
CORS(app) |
|
|
|
|
|
UPLOAD_FOLDER = 'uploads' |
|
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'pdf', 'tif', 'tiff'} |
|
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER |
|
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 |
|
|
|
|
|
os.makedirs(UPLOAD_FOLDER, exist_ok=True) |
|
|
|
|
|
print("Loading OCR model...") |
|
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten", cache_dir="/huggingface_cache") |
|
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten", cache_dir="/huggingface_cache") |
|
|
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
print(f"Using device: {device}") |
|
model.to(device) |
|
|
|
def allowed_file(filename): |
|
return '.' in filename and \ |
|
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS |
|
|
|
def preprocess_image(image_path): |
|
|
|
image = Image.open(image_path).convert("RGB") |
|
|
|
|
|
|
|
img = np.array(image) |
|
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) |
|
|
|
|
|
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) |
|
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, |
|
cv2.THRESH_BINARY, 11, 2) |
|
|
|
|
|
enhanced_image = Image.fromarray(cv2.cvtColor(thresh, cv2.COLOR_GRAY2RGB)) |
|
return enhanced_image |
|
|
|
def perform_ocr(image_path): |
|
|
|
image = preprocess_image(image_path) |
|
|
|
|
|
pixel_values = processor(image, return_tensors="pt").pixel_values.to(device) |
|
|
|
|
|
generated_ids = model.generate( |
|
pixel_values, |
|
max_length=64, |
|
num_beams=5, |
|
early_stopping=True |
|
) |
|
|
|
|
|
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] |
|
return generated_text.strip() |
|
|
|
@app.route('/ocr', methods=['POST']) |
|
def ocr(): |
|
|
|
if 'file' not in request.files: |
|
return jsonify({'error': 'No file part'}), 400 |
|
|
|
file = request.files['file'] |
|
|
|
|
|
if file.filename == '': |
|
return jsonify({'error': 'No selected file'}), 400 |
|
|
|
|
|
if file and allowed_file(file.filename): |
|
|
|
filename = str(uuid.uuid4()) + '_' + secure_filename(file.filename) |
|
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) |
|
|
|
|
|
file.save(file_path) |
|
|
|
try: |
|
|
|
extracted_text = perform_ocr(file_path) |
|
|
|
|
|
os.remove(file_path) |
|
|
|
return jsonify({ |
|
'success': True, |
|
'text': extracted_text |
|
}) |
|
except Exception as e: |
|
|
|
print(f"Error processing image: {str(e)}") |
|
return jsonify({ |
|
'success': False, |
|
'error': str(e) |
|
}), 500 |
|
else: |
|
return jsonify({'error': 'File type not allowed'}), 400 |
|
|
|
@app.route('/health', methods=['GET']) |
|
def health_check(): |
|
return jsonify({'status': 'healthy'}), 200 |
|
|
|
if __name__ == '__main__': |
|
app.run(host='0.0.0.0', port=5000, debug=False) |