-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImageToFormat_API.py
86 lines (71 loc) · 2.89 KB
/
ImageToFormat_API.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import os
import sys
import logging
from PIL import Image
from flask import Blueprint, Flask, jsonify, request
from backend.ImageToFormat import ImageToFormat
# Configure Logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Add the Backend Directory to the System Path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
class ImageToFormat_Prep:
def __init__(self) -> None:
"""Initialize the ImageToFormat_Prep class."""
pass
def run(self, image: Image) -> str:
"""
Process the given Image and convert it to Text Format.
"""
try:
return ImageToFormat(image).ImageToFormat()
except Exception as e:
logging.error('An Error Occurred during Image Processing.', exc_info=True)
raise e
class ImageToFormat_Prep_API:
"""
A Flask API class to handle Image Uploading and Format Conversion.
"""
def __init__(self):
"""Initialize the Flask API and define routes."""
self.app = Flask(__name__)
self.ImageToFormat_blueprint = Blueprint('ImageToFormat', __name__)
self.ImageToFormat_blueprint.add_url_rule('/', 'SERVER_STARTED', self.SERVER_STARTED, methods=['GET'])
self.ImageToFormat_blueprint.add_url_rule('/UploadedImage', 'UploadedImage', self.UploadedImage, methods=['POST'])
self.ImageToFormat = ImageToFormat_Prep()
def SERVER_STARTED(self) -> tuple:
"""
Handles GET requests and confirms if the Server has Started.
"""
try:
return jsonify({'response': 200, 'SERVER STARTED': True}), 200
except Exception as e:
logging.error('An Error Occurred while Server Startup.', exc_info=True)
raise e
def UploadedImage(self) -> tuple:
"""
Handles POST requests for uploading an Image and processes it to Extract Text.
"""
try:
# Retrieve Image from request and open it using PIL
image = request.files['file']
image = Image.open(image)
# Process the Image to get the Text Format
text = self.ImageToFormat.run(image)
return jsonify({'response': text}), 200
except Exception as e:
logging.error('An Error Occurred while processing the Uploaded Image.', exc_info=True)
return jsonify({'Error': str(e)}), 400
def run(self) -> None:
"""
Start the Flask Application and run the Server.
"""
try:
self.app.register_blueprint(self.ImageToFormat_blueprint)
self.app.run(debug=True)
except Exception as e:
logging.error('An Error Occurred while starting the Flask Application.', exc_info=True)
raise e
if __name__ == '__main__':
server = ImageToFormat_Prep_API()
server.run()