Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
+
import pytesseract
|
3 |
+
from pytesseract import Output
|
4 |
+
import difflib
|
5 |
+
from PIL import Image
|
6 |
+
|
7 |
+
app = Flask(__name__)
|
8 |
+
|
9 |
+
def find_text_coordinates(image_file, search_text):
|
10 |
+
image = Image.open(image_file)
|
11 |
+
d = pytesseract.image_to_data(image, output_type=Output.DICT)
|
12 |
+
n_boxes = len(d['level'])
|
13 |
+
|
14 |
+
result = []
|
15 |
+
for i in range(n_boxes):
|
16 |
+
(x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i])
|
17 |
+
if d["text"][i]:
|
18 |
+
result.append(((x, y, w, h), d["text"][i]))
|
19 |
+
|
20 |
+
arr_of_words = [i[1].lower() for i in result]
|
21 |
+
closest_match = difflib.get_close_matches(search_text, arr_of_words, n=1)
|
22 |
+
if closest_match:
|
23 |
+
for i in result:
|
24 |
+
if i[1].lower() == closest_match[0].lower():
|
25 |
+
return {"text": closest_match[0], "coordinates": {"x": i[0][0], "y": i[0][1], "width": i[0][2], "height": i[0][3]}}
|
26 |
+
return None
|
27 |
+
|
28 |
+
@app.route('/ocr', methods=['POST'])
|
29 |
+
def ocr():
|
30 |
+
if 'image' not in request.files:
|
31 |
+
return jsonify({"error": "No image file provided"}), 400
|
32 |
+
if 'text' not in request.form:
|
33 |
+
return jsonify({"error": "No text provided"}), 400
|
34 |
+
|
35 |
+
image_file = request.files['image']
|
36 |
+
search_text = request.form['text'].lower()
|
37 |
+
|
38 |
+
# Find text coordinates directly from memory
|
39 |
+
result = find_text_coordinates(image_file, search_text)
|
40 |
+
|
41 |
+
if result:
|
42 |
+
return jsonify(result)
|
43 |
+
else:
|
44 |
+
return jsonify({"error": "Text not found"}), 404
|
45 |
+
|
46 |
+
if __name__ == '__main__':
|
47 |
+
app.run()
|