Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import torch
|
| 4 |
+
from torchvision.transforms import functional as F
|
| 5 |
+
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 6 |
+
|
| 7 |
+
app = Flask(__name__)
|
| 8 |
+
|
| 9 |
+
# Load the trained model and processor
|
| 10 |
+
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-small-printed")
|
| 11 |
+
model = VisionEncoderDecoderModel.from_pretrained("trocrnew.pth")
|
| 12 |
+
|
| 13 |
+
# Set the model in evaluation mode
|
| 14 |
+
model.eval()
|
| 15 |
+
|
| 16 |
+
def ocr(image):
|
| 17 |
+
# Preprocess the image
|
| 18 |
+
image = F.to_tensor(image).unsqueeze(0)
|
| 19 |
+
|
| 20 |
+
# Perform OCR
|
| 21 |
+
with torch.no_grad():
|
| 22 |
+
generated_ids = model.generate(image)
|
| 23 |
+
|
| 24 |
+
# Decode the generated text
|
| 25 |
+
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 26 |
+
|
| 27 |
+
return generated_text
|
| 28 |
+
|
| 29 |
+
@app.route('/ocr', methods=['POST'])
|
| 30 |
+
def ocr_endpoint():
|
| 31 |
+
# Check if the POST request contains a file
|
| 32 |
+
if 'file' not in request.files:
|
| 33 |
+
return jsonify({'error': 'No file provided'}), 400
|
| 34 |
+
|
| 35 |
+
file = request.files['file']
|
| 36 |
+
|
| 37 |
+
# Check if the file has an allowed extension
|
| 38 |
+
allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'}
|
| 39 |
+
if '.' not in file.filename or file.filename.split('.')[-1].lower() not in allowed_extensions:
|
| 40 |
+
return jsonify({'error': 'Invalid file type'}), 400
|
| 41 |
+
|
| 42 |
+
# Read the image and perform OCR
|
| 43 |
+
try:
|
| 44 |
+
image = Image.open(file).convert('RGB')
|
| 45 |
+
text = ocr(image)
|
| 46 |
+
return jsonify({'text': text}), 200
|
| 47 |
+
except Exception as e:
|
| 48 |
+
return jsonify({'error': str(e)}), 500
|
| 49 |
+
|
| 50 |
+
if __name__ == '__main__':
|
| 51 |
+
app.run(debug=True)
|