프로그래밍/Developer Student Clubs

[Back-end] Flask 공부 및 Yolo v3 web streaming 구현

지누; 2020. 2. 18. 16:32

[Flask 공부]

https://github.com/Turtlefromocean/Flask_01

 

Turtlefromocean/Flask_01

Contribute to Turtlefromocean/Flask_01 development by creating an account on GitHub.

github.com

1. 기본 틀

from flask import Flask

# init app
app = Flask(__name__)


# Route
@app.route('/')
def index():
	return 'Hello Data Science Optimizers'

if __name__ == '__main__':
	app.run(debug=True)

2. route & html 파일 render_template

from flask import Flask, render_template

# Route
@app.route('/')
def index():
	return 'Hello Data Science Optimizers'

# HTML 파일 추가
@app.route('/home')
def home():
	return render_template('home.html')

if __name__ == '__main__':
	app.run(debug=True)

3. GET, POST & Jinja

 

- home.html (index.html)

 👉<form> 태그: POST , action -> /predict

<!DOCTYPE html>
<html>
<head>
	<title>Home Page</title>
</head>
<body>
	<div>
		<h2>Home Page for ML Apps</h2>
	</div>

	<div>
		<form method="POST" action="{{ url_for('predict') }}"> <!-- action= "/preict" -->
			<input type="text" name="firstname" placeholder="FirstName">
			<input type="text" name="lastname" placeholder="LastName">
			<button type="reset">Clear</button>
			<button type="submit">Submit</button>

		</form>
	</div>

	<div>
		<p>당신의 이름은 {{firstname}} 이고 성은 {{lastname}} 입니다</p>
	</div>
</body>
</html>

- app.py

from flask import Flask, render_template, request, url_for

# init app
app = Flask(__name__)

# Route
@app.route('/')
def index():
	return 'Hello Data Science Optimizers'

# HTML 파일 추가
@app.route('/home')
def home():
	return render_template('home.html')


# 
@app.route('/predict', methods=['GET', 'POST'])
def predict():
	if request.method == 'POST':
		firstname = request.form['firstname']
		lastname = request.form['lastname']
		single_user = User(firstname=firstname, lastname=lastname)
		db.session.add(single_user)
		db.session.commit()

	return render_template('home.html', firstname=firstname.upper(), lastname=lastname)

# Templating , Jinja
@app.route('/about')
def about():
	mission = "Optimizing Data and ML Models with Python"
	return render_template('about.html', mission_frontend=mission)

if __name__ == '__main__':
	app.run(debug=True)

- about. html

 👉Jinja: {{ }}  또는 {% %}

<!DOCTYPE html>
<html>
<head>
	<title>About Page</title>
</head>
<body>
	<h2>About Us</h2>
	<div>
		{{mission_frontend}}
	</div>
</body>
</html>

4. Database => flask_sqlalchemy

- db 설정

- sql types of columns

https://flask-sqlalchemy.palletsprojects.com/en/2.x/models/

from flask import Flask, render_template, request, url_for
from flask_sqlalchemy import SQLAlchemy 

# init app
app = Flask(__name__)

# DB
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///static/database/users.db' # /// 3개 !!


# model schema
class User(db.Model):
	id = db.Column(db.Integer, primary_key=True)
	firstname = db.Column(db.String(50))
	lastname = db.Column(db.String(50))


# Route
@app.route('/')
def index():
	return 'Hello Data Science Optimizers'

# HTML 파일 추가
@app.route('/home')
def home():
	return render_template('home.html')


# 
@app.route('/predict', methods=['GET', 'POST'])
def predict():
	if request.method == 'POST':
		firstname = request.form['firstname']
		lastname = request.form['lastname']
		single_user = User(firstname=firstname, lastname=lastname)
		db.session.add(single_user)
		db.session.commit()

	return render_template('home.html', firstname=firstname.upper(), lastname=lastname)

@app.route('/allusers')
def allusers():
	userslist = User.query.all()
	print(userslist)
	return render_template('results.html', userslist=userslist)

@app.route('/profile/<firstname>')
def profile(firstname):
	user = User.query.filter_by(firstname=firstname).first()
	return render_template('profile.html', user=user)

# Templating , Jinja
@app.route('/about')
def about():
	mission = "Optimizing Data and ML Models with Python"
	return render_template('about.html', mission_frontend=mission)

if __name__ == '__main__':
	app.run(debug=True)

[YOLO v3 Webcam with Flask] 성공🥳

 

Github 🔗: https://github.com/Turtlefromocean/flask-yolo-web

 

Turtlefromocean/flask-yolo-web

Contribute to Turtlefromocean/flask-yolo-web development by creating an account on GitHub.

github.com

*requirements.txt 가 없어서 만들었다

$ pipenv shell
$ pip install -r requirements.txt

*yolo.weights는 크기가 커서 따로 다운받은 후 h5 파일로 변환

$ wget https://pjreddie.com/media/files/yolov3-tiny.weights
$ python convert.py yolov3-tiny.cfg yolov3-tiny.weights model_data/yolo.h5

*실행

$ python3 server.py

 

* 페이지가 너무 허전해서 bootstrap 적용

* 물체인식해주는 상자가 너무 별로여서 색이랑 두께 조정

* 기분탓인지 모르겠지만 뭔가,, predict 값이 잘 안나온다

업그레이드!@!

참조) https://github.com/zxqcreations/YOLOv3-withWebServer 

 

[모델 배포]

https://bcho.tistory.com/1191?category=555440

 

얼굴 인식 모델을 만들어보자 #6 - CloudML을 이용하여 예측하기

CloudML을 이용하여 예측하기 조대협 (http://bcho.tistory.com) 지난글 (http://bcho.tistory.com/1189) 에서 학습된 모델을 *.pb 파일 포맷으로 Export 하였다. 그러면 이 Export 된 모델을 이용하여 예측 (pred..

bcho.tistory.com

ML 프레임 워크

https://www.streamlit.io/

 

Streamlit — The fastest way to build custom ML tools

Streamlit is an open-source app framework for Machine Learning and Data Science teams. Create beautiful data apps in hours, not weeks. All in pure Python. All for free.

www.streamlit.io