-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
103 lines (76 loc) · 2.51 KB
/
app.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
from flask import Flask, request, jsonify, render_template
from urllib.parse import urlparse
from urllib.parse import unquote
import json
from img_to_text import request_img, preprocess, ocr_img
import requests
import os
app = Flask(__name__)
with open("/etc/config.json") as config_file:
config = json.load(config_file)
app.config["SECRET_KEY"] = config.get("SECRET_KEY")
def validate_url(url):
"""Take url, return True if valid url and contains image, False otherwise.
Keyword arguments:
url -- requies scheme, netloc, and supported image extension to be valid
"""
result = urlparse(url)
supported_image = url.split(".")[-1] in ["jpg", "png"]
print(f"validate_url() \n scheme: {result.scheme} \n netloc: {result.netloc} \n is image: {supported_image}")
return all([result.scheme, result.netloc, supported_image])
def get_img_text(url):
print("get_img_text() requesting...")
img = request_img(url)
if img is None:
return "error: requested resource not available"
print("Request successful.")
preprocessed = preprocess(img)
print("Preprocess successful.")
text = ocr_img(preprocessed)
print("OCR successful.")
print(text)
return text
@app.route("/cs469/api", methods=["GET"])
def api():
response = None
url = ""
# get headers
print(request.headers)
# check if passed url
url = request.args["url"]
# validate passed url
if not validate_url(url):
response = "error: url invalid"
else:
response = get_img_text(url)
# return response in json
return jsonify({"response": response})
@app.route("/cs469/gui", methods=["GET"])
def gui():
response = None
url = ""
# check if passed url
# url = request.args['url']
# check headers
print(request.headers)
# GUI main without query
if request.method == "GET" and len(request.args) == 0:
return render_template("gui.j2")
# query submitted
else:
url = unquote(request.args["url"])
print("**URL", url)
# validate passed url
if not validate_url(url):
response = "error: url invalid"
else:
response = get_img_text(url)
# return response in text
return render_template("response.j2", response=response)
if __name__ == "__main__":
# former configuration
# host = '10.0.0.1' #'localhost.'
# port = int(os.environ.get('PORT', 5000))
# app.run(host=host, port=port, debug=True)
# new config
app.run(host="0.0.0.0")