I am trying to put together a flask api endpoint that can take an image, drop it in a an 'uploads' folder and then perform an operation on it. The image will be sent from a reactjs front end. I have the beginnings of a python script that I know allows me to upload a photo via flask. But I want to alter it to:
- lose the front end upload option instead giving me just the endpoint to upload the image
- set it up to run a python script on that image once it lands in the uploads folder that extracts text
I've put below some of the pieces I have so far:
reactjs
#just the piece where i am sending an image to flask
fileUploadHandler =() => {
const fd = new FormData();
fd.append('image', this.state.selectedFile, this.state.selectedFile.name)
console.log('file is uploaded')
//axios.post('my_endpoint');
}
app.py
#from https://stackoverflow.com/questions/52152464/convert-normal-python-script-to-reset-api
import sumTwoNumbers
from flask import Flask, request
from flask_restful import Resource, Api
import os
from werkzeug.utils import secure_filename
import cv2
PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER = '{}/uploads/'.format(PROJECT_HOME)
app = Flask(__name__)
api = Api(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = set(['jpg','png'])
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
_path = os.path.abspath("<FILE PATH>")
#uf = str(uuid.uuid4())
return redirect(url_for('index'))
return """
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
<p>%s</p>
""" % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],))
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000, debug=True)
imageToText.py
#script to run on the image that pulls text
import cv2
import pytesseract
import imutils
img = cv2.imread('note.PNG')
#use tesseract to convert image into strinf
text = pytesseract.image_to_string(img, lang='eng')
print(text)