Giao diện sentiment với Jinja2 form
Bài theo Python Machine Learning — Jinja2 UI. Kungfutech Chương 9 xây trang web cho người không biết Python: dán review phim → thấy positive/negative — đúng use case đã train ở Ch.8.
Mục tiêu
- Form POST tới route predict, render
result.htmlvới nhãn và thanh xác suất đơn giản. - Escape output (
{{ text }}auto-escape) tránh XSS khi hiển thị input user. - Tái sử dụng logic predict từ module riêng (
inference.py).
Lý thuyết
Tách concerns
| Module | Trách nhiệm |
|---|---|
train_model.py |
Fit + joblib.dump |
inference.py |
def classify(text) -> dict |
app.py |
Flask routes, gọi classify |
Giúp test inference không cần khởi động Flask.
Code Python
inference.py:
def classify(pipe, class_names, text: str) -> dict:
pred = int(pipe.predict([text])[0])
proba = pipe.predict_proba([text])[0]
return {
"label": class_names[pred],
"probabilities": {n: float(p) for n, p in zip(class_names, proba)},
}
app.py (rút gọn):
from flask import Flask, render_template, request
import joblib
from inference import classify
app = Flask(__name__)
bundle = joblib.load("models/pipe_v1.joblib")
PIPE, NAMES = bundle["pipeline"], list(bundle["classes"])
@app.route("/", methods=["GET", "POST"])
def index():
result = None
if request.method == "POST":
text = request.form.get("review", "")
result = classify(PIPE, NAMES, text)
return render_template("index.html", result=result)
templates/index.html:
<form method="post">
<textarea name="review">{{ request.form.review or '' }}</textarea>
<button type="submit">Phân loại</button>
</form>
{% if result %}
<p>Nhãn: <strong>{{ result.label }}</strong></p>
<ul>
{% for name, p in result.probabilities.items() %}
<li>{{ name }}: {{ '%.1f'|format(p * 100) }}%</li>
{% endfor %}
</ul>
{% endif %}
Lỗi thường gặp
|safetrên input user — XSS.- Logic predict copy-paste giữa route JSON và form — refactor vào
inference.py.
Bài tập
- Thêm CSS trong
static/highlight nhãn dự đoán. - Hiển thị thông báo khi textarea trống.
Tóm tắt
Jinja2 sentiment UI — trải nghiệm người dùng cuối cho pipeline Ch.8.
Tiếp tục lộ trình tại khóa Machine Learning cơ bản — bài tiếp theo: Embed pipeline sentiment vào Flask end-to-end.