Skip to content
This repository was archived by the owner on Sep 4, 2023. It is now read-only.

Commit a451467

Browse files
author
Mohammed Ramli
authored
RESTful API Added
1 parent 3475311 commit a451467

File tree

1 file changed

+67
-23
lines changed

1 file changed

+67
-23
lines changed

server.py

Lines changed: 67 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,56 @@
1+
import glob
12
import os
2-
import numpy as np
3+
34
from PIL import Image
4-
from capgen import CaptionGenerator
5-
from flask import Flask, request, render_template, request, redirect
65
from elasticsearch import Elasticsearch
76
from elasticsearch.helpers import bulk
7+
from flask import Flask, render_template, request, Response
88
from werkzeug.utils import secure_filename
9-
import glob
9+
import json
10+
11+
from capgen import CaptionGenerator
1012

1113
os.environ['CUDA_VISIBLE_DEVICES'] = ''
1214
es = Elasticsearch()
1315
gencap = CaptionGenerator()
1416

17+
1518
def description_search(query):
1619
global es
1720
results = es.search(
1821
index="desearch",
1922
body={
2023
"size": 20,
2124
"query": {
22-
"match": {"description": query}
25+
"match": {"description": query}
2326
}
24-
})
25-
hitCount = results['hits']['total']
27+
})
28+
hitCount = results['hits']['total']['value']
2629
print(results)
2730

2831
if hitCount > 0:
2932
if hitCount is 1:
30-
print(str(hitCount),' result')
33+
print(str(hitCount), ' result')
3134
else:
3235
print(str(hitCount), 'results')
33-
answers =[]
36+
answers = []
3437
max_score = results['hits']['max_score']
3538

3639
if max_score >= 0.35:
3740
for hit in results['hits']['hits']:
3841
if hit['_score'] > 0.5 * max_score:
3942
desc = hit['_source']['description']
4043
imgurl = hit['_source']['imgurl']
41-
answers.append([imgurl,desc])
44+
answers.append([imgurl, desc])
4245
else:
4346
answers = []
4447
return answers
4548

49+
4650
app = Flask(__name__)
47-
app.config['UPLOAD_FOLDER'] = os.path.join('static','database')
48-
app.config['TEMP_UPLOAD_FOLDER'] = os.path.join('static','uploads')
49-
app.config['ALLOWED_EXTENSIONS'] = set(['jpg','jpeg','png'])
51+
app.config['UPLOAD_FOLDER'] = os.path.join('static', 'database')
52+
app.config['TEMP_UPLOAD_FOLDER'] = os.path.join('static', 'uploads')
53+
app.config['ALLOWED_EXTENSIONS'] = set(['jpg', 'jpeg', 'png'])
5054

5155

5256
def allowed_file(filename):
@@ -58,11 +62,13 @@ def allowed_file(filename):
5862
def index():
5963
return render_template('home.html')
6064

65+
6166
@app.route('/search', methods=['GET', 'POST'])
6267
def search():
6368
global gencap
6469
if request.method == 'POST':
65-
if 'query_img' not in request.files or request.files['query_img'].filename == '' or not allowed_file(request.files['query_img'].filename):
70+
if 'query_img' not in request.files or request.files['query_img'].filename == '' or not allowed_file(
71+
request.files['query_img'].filename):
6672
return render_template('search.html')
6773
file = request.files['query_img']
6874
img = Image.open(file.stream) # PIL image
@@ -77,12 +83,32 @@ def search():
7783
else:
7884
return render_template('search.html')
7985

86+
87+
@app.route('/api/search', methods=['POST'])
88+
def api_search():
89+
global gencap
90+
if 'query_img' not in request.files or request.files['query_img'].filename == '' or not allowed_file(
91+
request.files['query_img'].filename):
92+
return Response(response=json.dumps({'success': False, 'message': 'Uploaded image is invalid or not allowed'}),
93+
status=400, mimetype="application/json")
94+
file = request.files['query_img']
95+
img = Image.open(file.stream) # PIL image
96+
uploaded_img_path = os.path.join(app.config['TEMP_UPLOAD_FOLDER'], file.filename)
97+
img.save(uploaded_img_path)
98+
query = gencap.get_caption(uploaded_img_path)
99+
answers = description_search(query)
100+
101+
return Response(response=json.dumps({'success': True, 'answers': answers}),
102+
status=200, mimetype="application/json")
103+
104+
80105
@app.route('/database')
81106
def database():
82-
images = glob.glob(os.path.join(app.config['UPLOAD_FOLDER'],'*'))
83-
return render_template('database.html', database_images = images)
107+
images = glob.glob(os.path.join(app.config['UPLOAD_FOLDER'], '*'))
108+
return render_template('database.html', database_images=images)
109+
84110

85-
@app.route('/upload', methods=['GET','POST'])
111+
@app.route('/upload', methods=['GET', 'POST'])
86112
def upload():
87113
if request.method == 'POST':
88114
if 'photos' not in request.files:
@@ -94,24 +120,42 @@ def upload():
94120
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
95121
file.save(file_path)
96122
cap = gencap.get_caption(file_path)
97-
doc = {'imgurl': file_path, 'description':cap}
123+
doc = {'imgurl': file_path, 'description': cap}
98124
actions.append(doc)
99-
bulk(es,actions,index="desearch",doc_type="json")
125+
bulk(es, actions, index="desearch", doc_type="json")
100126
return render_template('database.html')
101127

102-
@app.route('/caption', methods=['GET','POST'])
128+
129+
@app.route('/caption', methods=['GET', 'POST'])
103130
def caption():
104131
if request.method == 'POST':
105-
if 'query_img' not in request.files or request.files['query_img'].filename == '' or not allowed_file(request.files['query_img'].filename):
132+
if 'query_img' not in request.files or request.files['query_img'].filename == '' or not allowed_file(
133+
request.files['query_img'].filename):
106134
return render_template('caption.html')
107135
file = request.files['query_img']
108136
img = Image.open(file.stream) # PIL image
109137
uploaded_img_path = os.path.join(app.config['TEMP_UPLOAD_FOLDER'], file.filename)
110138
img.save(uploaded_img_path)
111139
cap = gencap.get_caption(uploaded_img_path)
112-
return render_template('caption.html', caption = cap, query_path=uploaded_img_path)
140+
return render_template('caption.html', caption=cap, query_path=uploaded_img_path)
113141
else:
114142
return render_template('caption.html')
115143

116-
if __name__=="__main__":
144+
145+
@app.route('/api/caption', methods=['POST'])
146+
def caption_api():
147+
if 'query_img' not in request.files or request.files['query_img'].filename == '' or not allowed_file(
148+
request.files['query_img'].filename):
149+
return Response(response=json.dumps({'success': False, 'message': 'Uploaded image is invalid or not allowed'}),
150+
status=400, mimetype="application/json")
151+
file = request.files['query_img']
152+
img = Image.open(file.stream) # PIL image
153+
uploaded_img_path = os.path.join(app.config['TEMP_UPLOAD_FOLDER'], file.filename)
154+
img.save(uploaded_img_path)
155+
cap = gencap.get_caption(uploaded_img_path)
156+
return Response(response=json.dumps({'success': True, 'caption': cap}),
157+
status=200, mimetype="application/json")
158+
159+
160+
if __name__ == "__main__":
117161
app.run("127.0.0.1", debug=True)

0 commit comments

Comments
 (0)