Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import uuid
|
3 |
+
from flask import Flask, request, jsonify
|
4 |
+
from flask_cors import CORS
|
5 |
+
from werkzeug.utils import secure_filename
|
6 |
+
import torch
|
7 |
+
from transformers import DonutProcessor, VisionEncoderDecoderModel
|
8 |
+
from PIL import Image
|
9 |
+
import cv2
|
10 |
+
import numpy as np
|
11 |
+
|
12 |
+
app = Flask(__name__)
|
13 |
+
CORS(app)
|
14 |
+
|
15 |
+
# Configure upload folder
|
16 |
+
UPLOAD_FOLDER = 'uploads'
|
17 |
+
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'pdf', 'tif', 'tiff'}
|
18 |
+
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
19 |
+
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max upload
|
20 |
+
|
21 |
+
# Create uploads directory if it doesn't exist
|
22 |
+
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
23 |
+
|
24 |
+
# Load OCR model - Microsoft's Donut model
|
25 |
+
processor = DonutProcessor.from_pretrained("microsoft/donut-base")
|
26 |
+
model = VisionEncoderDecoderModel.from_pretrained("microsoft/donut-base")
|
27 |
+
|
28 |
+
# Move model to GPU if available
|
29 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
30 |
+
model.to(device)
|
31 |
+
|
32 |
+
def allowed_file(filename):
|
33 |
+
return '.' in filename and \
|
34 |
+
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
35 |
+
|
36 |
+
def preprocess_image(image_path):
|
37 |
+
# Open image with PIL
|
38 |
+
image = Image.open(image_path).convert("RGB")
|
39 |
+
|
40 |
+
# Basic enhancement for better OCR results
|
41 |
+
# Convert to OpenCV format for preprocessing
|
42 |
+
img = np.array(image)
|
43 |
+
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
|
44 |
+
|
45 |
+
# Apply adaptive thresholding to handle varying lighting conditions
|
46 |
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
47 |
+
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
48 |
+
cv2.THRESH_BINARY, 11, 2)
|
49 |
+
|
50 |
+
# Convert back to PIL
|
51 |
+
enhanced_image = Image.fromarray(cv2.cvtColor(thresh, cv2.COLOR_GRAY2RGB))
|
52 |
+
return enhanced_image
|
53 |
+
|
54 |
+
def perform_ocr(image_path):
|
55 |
+
# Preprocess the image
|
56 |
+
image = preprocess_image(image_path)
|
57 |
+
|
58 |
+
# Prepare image for the model
|
59 |
+
pixel_values = processor(image, return_tensors="pt").pixel_values.to(device)
|
60 |
+
|
61 |
+
# Generate text
|
62 |
+
task_prompt = "<s_ocr>"
|
63 |
+
decoder_input_ids = processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").input_ids.to(device)
|
64 |
+
|
65 |
+
outputs = model.generate(
|
66 |
+
pixel_values,
|
67 |
+
decoder_input_ids=decoder_input_ids,
|
68 |
+
max_length=model.decoder.config.max_position_embeddings,
|
69 |
+
early_stopping=True,
|
70 |
+
pad_token_id=processor.tokenizer.pad_token_id,
|
71 |
+
eos_token_id=processor.tokenizer.eos_token_id,
|
72 |
+
use_cache=True,
|
73 |
+
num_beams=5,
|
74 |
+
bad_words_ids=[[processor.tokenizer.unk_token_id]],
|
75 |
+
return_dict_in_generate=True,
|
76 |
+
)
|
77 |
+
|
78 |
+
# Decode generated text
|
79 |
+
sequence = processor.batch_decode(outputs.sequences)[0]
|
80 |
+
sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "")
|
81 |
+
sequence = sequence.replace("<s>", "").replace("</s>", "").replace("<s_ocr>", "").replace("</s_ocr>", "")
|
82 |
+
return sequence.strip()
|
83 |
+
|
84 |
+
@app.route('/ocr', methods=['POST'])
|
85 |
+
def ocr():
|
86 |
+
# Check if a file was uploaded
|
87 |
+
if 'file' not in request.files:
|
88 |
+
return jsonify({'error': 'No file part'}), 400
|
89 |
+
|
90 |
+
file = request.files['file']
|
91 |
+
|
92 |
+
# Check if filename is empty
|
93 |
+
if file.filename == '':
|
94 |
+
return jsonify({'error': 'No selected file'}), 400
|
95 |
+
|
96 |
+
# Check if file type is allowed
|
97 |
+
if file and allowed_file(file.filename):
|
98 |
+
# Create a unique filename
|
99 |
+
filename = str(uuid.uuid4()) + '_' + secure_filename(file.filename)
|
100 |
+
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
101 |
+
|
102 |
+
# Save the file
|
103 |
+
file.save(file_path)
|
104 |
+
|
105 |
+
try:
|
106 |
+
# Perform OCR
|
107 |
+
extracted_text = perform_ocr(file_path)
|
108 |
+
|
109 |
+
# Clean up the file if needed
|
110 |
+
# os.remove(file_path)
|
111 |
+
|
112 |
+
return jsonify({
|
113 |
+
'success': True,
|
114 |
+
'text': extracted_text
|
115 |
+
})
|
116 |
+
except Exception as e:
|
117 |
+
return jsonify({
|
118 |
+
'success': False,
|
119 |
+
'error': str(e)
|
120 |
+
}), 500
|
121 |
+
else:
|
122 |
+
return jsonify({'error': 'File type not allowed'}), 400
|
123 |
+
|
124 |
+
@app.route('/health', methods=['GET'])
|
125 |
+
def health_check():
|
126 |
+
return jsonify({'status': 'healthy'}), 200
|
127 |
+
|
128 |
+
if __name__ == '__main__':
|
129 |
+
app.run(host='0.0.0.0', port=5000, debug=False
|