|
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 DonutProcessor, 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) |
|
|
|
|
|
processor = DonutProcessor.from_pretrained("microsoft/donut-base") |
|
model = VisionEncoderDecoderModel.from_pretrained("microsoft/donut-base") |
|
|
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
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) |
|
|
|
|
|
task_prompt = "<s_ocr>" |
|
decoder_input_ids = processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").input_ids.to(device) |
|
|
|
outputs = model.generate( |
|
pixel_values, |
|
decoder_input_ids=decoder_input_ids, |
|
max_length=model.decoder.config.max_position_embeddings, |
|
early_stopping=True, |
|
pad_token_id=processor.tokenizer.pad_token_id, |
|
eos_token_id=processor.tokenizer.eos_token_id, |
|
use_cache=True, |
|
num_beams=5, |
|
bad_words_ids=[[processor.tokenizer.unk_token_id]], |
|
return_dict_in_generate=True, |
|
) |
|
|
|
|
|
sequence = processor.batch_decode(outputs.sequences)[0] |
|
sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "") |
|
sequence = sequence.replace("<s>", "").replace("</s>", "").replace("<s_ocr>", "").replace("</s_ocr>", "") |
|
return sequence.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) |
|
|
|
|
|
|
|
|
|
return jsonify({ |
|
'success': True, |
|
'text': extracted_text |
|
}) |
|
except Exception as 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 |