-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
57 lines (42 loc) · 1.83 KB
/
app.py
File metadata and controls
57 lines (42 loc) · 1.83 KB
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
import os, base64
from flask import Flask, render_template, request, flash
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import ComputerVisionErrorException
from msrest.authentication import CognitiveServicesCredentials
# Create a ComputerVisionClient instance for calling the Computer Vision API
vision_credentials = CognitiveServicesCredentials(vision_key)
vision_client = ComputerVisionClient(vision_endpoint, vision_credentials)
app = Flask(__name__)
app.secret_key = os.urandom(24)
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
# Display the image that was uploaded
image = request.files["file"]
uri = "data:image/jpg;base64," + base64.b64encode(image.read()).decode("utf-8")
image.seek(0)
# Use the Computer Vision API to extract text from the image
lines = extract_text_from_image(image, vision_client)
# Flash the extracted text
for line in lines:
flash(line)
else:
# Display a placeholder image
uri = "/static/Place_img.png"
return render_template("index.html", image_uri=uri)
# Function that extracts text from images
def extract_text_from_image(image, client):
try:
result = client.recognize_printed_text_in_stream(image=image)
lines=[]
if len(result.regions) == 0:
lines.append("Photo contains no text to translate")
else:
for line in result.regions[0].lines:
text = " ".join([word.text for word in line.words])
lines.append(text)
return lines
except ComputerVisionErrorException as e:
return ["Computer Vision API error: " + e.message]
except:
return ["Error calling the Computer Vision API"]