Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
srahnama committed Jan 29, 2022
0 parents commit fe02b42
Show file tree
Hide file tree
Showing 12 changed files with 246 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
__pycache__
engine/__pycache__
routes/__pycache__
.vscode
venv
38 changes: 38 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""A Python Flask App for DanaXA Test By Shahab Rahnama"""

import argparse
import os
from flask import Flask
from flask_cors import CORS
from routes import request_api


APP = Flask(__name__)

UPLOAD_FOLDER = 'static/uploads/'

APP.secret_key = "secret key"
APP.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
APP.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024



APP.register_blueprint(request_api.get_blueprint())

if __name__ == '__main__':

PARSER = argparse.ArgumentParser(description="Python Flask Danaxa Test By Shahab Rahnama")

PARSER.add_argument('--debug',
action='store_true',
help="Use flask debug/dev mode with file change reloading")
ARGS = PARSER.parse_args()

PORT = int(os.environ.get('PORT', 5000))

if ARGS.debug:
print("Running in debug mode")
CORS = CORS(APP)
APP.run(host='0.0.0.0', port=PORT, debug=True)
else:
APP.run(host='0.0.0.0', port=PORT, debug=False)
Binary file added engine/1.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Empty file added engine/__init__.py
Empty file.
60 changes: 60 additions & 0 deletions engine/spline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from distutils.command.upload import upload
import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt
import matplotlib as mpl
from PIL import Image
import os


# def spline(image_name,
# t=[0., 0. , 0., 0., 0.25, 0.5, 0.75, 1., 1., 1., 1. ],
# ctr=[(839 , 216), (588, 205), (427, 8), (304, 159),(265, 100), (203, 175),(0,135)],
# k=3):
def spline(image_name, t, ctr, k):
# ctr =np.array( [(839 , 216), (588, 205), (427, 8), (304, 159),(265, 100), (203, 175),(0,135)])
ctr = np.array(ctr)
x=ctr[:,0]
y=ctr[:,1]
im = Image.open(os.getcwd()+ "/static/uploads/"+image_name)
print(os.getcwd())
# uncomment both lines for a closed curve
#x=np.append(x,[x[0]])
#y=np.append(y,[y[0]])

l=len(x)

# t=np.linspace(0,1,l-2,endpoint=True)
# t=np.append([0,0,0],t)
# t=np.append(t,[1,1,1])
# print(t)
# [0. 0. 0. 0. 0.25 0.5 0.75 1. 1. 1. 1. ]
tck=[t,[x,y],k]
u3=np.linspace(0,1,(max(l*2,70)),endpoint=True)
out = interpolate.splev(u3,tck)

dpi = mpl.rcParams['figure.dpi']
height = im.height
width = im.width


# What size does the figure need to be in inches to fit the image?
figsize = width / float(dpi), height / float(dpi)

fig, ax = plt.subplots(figsize=figsize)
im = ax.imshow(im)
# plt.imshow(im)
ax.plot(x,y,'k--',label='Control polygon',marker='o',markerfacecolor='yellow')
#plt.plot(x,y,'ro',label='Control points only')
ax.plot(out[0],out[1],'r',linewidth=2.0,label='B-spline curve')
# ax.legend(loc='best')
# plt.axis([min(x)-1, max(x)+1, min(y)-1, max(y)+1])
# plt.title('Cubic B-spline curve evaluation')
plt.axis('off')
plt.savefig('static/uploads/'+image_name, bbox_inches='tight', pad_inches=0)
# plt.show()



# if __name__ == "__main__":
# spline()
5 changes: 5 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## A Python Flask App for DanaXA Test By Shahab Rahnama

### Setup
`Python3 app.py`

28 changes: 28 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
astroid==2.9.3
click==8.0.3
cycler==0.11.0
Flask==2.0.2
Flask-Cors==3.0.10
flask-swagger-ui==3.36.0
fonttools==4.29.0
isort==5.10.1
itsdangerous==2.0.1
Jinja2==3.0.3
kiwisolver==1.3.2
lazy-object-proxy==1.7.1
MarkupSafe==2.0.1
matplotlib==3.5.1
mccabe==0.6.1
numpy==1.22.1
packaging==21.3
Pillow==9.0.0
platformdirs==2.4.1
pylint==2.12.2
pyparsing==3.0.7
python-dateutil==2.8.2
scipy==1.7.3
six==1.16.0
toml==0.10.2
typing-extensions==4.0.1
Werkzeug==2.0.2
wrapt==1.13.3
Empty file added routes/__init__.py
Empty file.
57 changes: 57 additions & 0 deletions routes/request_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""The Endpoints to manage the DanaXA test"""
import uuid
from flask import Blueprint, flash, request, redirect, url_for, render_template
import ast
import os
from werkzeug.utils import secure_filename
from engine.spline import spline


REQUEST_API = Blueprint('request_api', __name__)


ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
UPLOAD_FOLDER = 'static/uploads/'

def get_blueprint():
"""Return the blueprint for the main app module"""
return REQUEST_API


def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@REQUEST_API.route('/')
def home():
return render_template('index.html')

@REQUEST_API.route('/', methods=['POST'])
def upload_image():
req = request.form.to_dict()
# print(req['cparam'])
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No image selected for uploading')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(UPLOAD_FOLDER, filename))
spline(filename,ast.literal_eval(req['tparam']),ast.literal_eval(req['cparam']), int(req['kparam']))

#print('upload_image filename: ' + filename)
flash('Image successfully uploaded and displayed below')
return render_template('index.html', filename=filename)
else:
flash('Allowed image types are - png, jpg, jpeg, gif')
return redirect(request.url)

@REQUEST_API.route('/display/<filename>')
def display_image(filename):
#print('display_image filename: ' + filename)
return redirect(url_for('static', filename='uploads/' + filename), code=301)


Binary file added static/uploads/1.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
53 changes: 53 additions & 0 deletions templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//templates/index.html
<html>
<head>
<title>Python Flask Danaxa test By Shahab Rahnama</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<p><h1 align="center">Python Flask Danaxa Test By Shahab Rahnama</h1></p>
<div class="container">
<div class="row">
<h2>Please Complete Form Precisely</h2>
<p>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</p>
{% if filename %}
<div>
<img src="{{ url_for('request_api.display_image', filename=filename) }}">
</div>
{% endif %}
<form method="post" action="/" enctype="multipart/form-data">
<dl>
<p>
<input type="text" placeholder="t = [0., 0. , 0., 0., 0.25, 0.5, 0.75, 1., 1., 1., 1. ]" name="tparam" class="form-control" autocomplete="off" required>
</p>
<p>
<input type="text" placeholder="ctr = [(839 , 216), (588, 205), (427, 8), (304, 159),(265, 100), (203, 175),(0,135)]" name="cparam" class="form-control" autocomplete="off" required>
</p>
<p>
<input type="text" placeholder="k = 3" name="kparam" class="form-control" autocomplete="off" required>
</p>
</dl>
<dl>
<p>
<input type="file" name="file" class="form-control" autocomplete="off" required>
</p>
</dl>
<p>
<input type="submit" value="Submit" class="btn btn-info">
</p>
</form>
</div>
</div>
</body>
</html>
Binary file added to.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit fe02b42

Please sign in to comment.