iris-ml / app.py
simran40's picture
Update app.py
c0b60a4 verified
from flask import Flask, request, render_template, redirect, url_for, session, flash
import seaborn as sns
from sklearn.linear_model import LogisticRegression
import sqlite3, os
app = Flask(__name__)
app.secret_key = "supersecretkey" # change in production!
# ------------------- Database Setup -------------------
def init_db():
if not os.path.exists("users.db"):
conn = sqlite3.connect("users.db")
c = conn.cursor()
c.execute("""
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
)
""")
conn.commit()
conn.close()
init_db()
# ------------------- ML Model -------------------
df = sns.load_dataset("iris")
X = df.iloc[:, :4].values
y = df.iloc[:, 4].values
model = LogisticRegression(max_iter=200, multi_class="auto")
model.fit(X, y)
# ------------------- Routes -------------------
@app.route("/")
def home():
if "user" in session:
return redirect(url_for("predict"))
return redirect(url_for("login"))
@app.route("/signup", methods=["GET", "POST"])
def signup():
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
try:
conn = sqlite3.connect("users.db")
c = conn.cursor()
c.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, password))
conn.commit()
conn.close()
flash("Signup successful! Please login.", "success")
return redirect(url_for("login"))
except sqlite3.IntegrityError:
flash("Username already taken!", "danger")
return render_template("signup.html")
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
conn = sqlite3.connect("users.db")
c = conn.cursor()
c.execute("SELECT * FROM users WHERE username=? AND password=?", (username, password))
user = c.fetchone()
conn.close()
if user:
session["user"] = username
flash("Login successful!", "success")
return redirect(url_for("predict"))
else:
flash("Invalid credentials!", "danger")
return render_template("login.html")
@app.route("/predict", methods=["GET", "POST"])
def predict():
if "user" not in session:
return redirect(url_for("login"))
prediction_text = ""
if request.method == "POST":
try:
sepal_length = float(request.form["sepal_length"])
sepal_width = float(request.form["sepal_width"])
petal_length = float(request.form["petal_length"])
petal_width = float(request.form["petal_width"])
prediction = model.predict(
[[sepal_length, sepal_width, petal_length, petal_width]]
)[0]
prediction_text = f"Predicted Flower: {prediction}"
except Exception as e:
prediction_text = f"Error: {e}"
return render_template("index.html", prediction_text=prediction_text)
@app.route("/logout")
def logout():
session.pop("user", None)
flash("Logged out successfully.", "info")
return redirect(url_for("login"))
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860, debug=True)
# from flask import Flask, request, render_template
# import pandas as pd
# from sklearn.linear_model import LogisticRegression
# # Load dataset
# url = "https://raw.githubusercontent.com/sarwansingh/Python/master/ClassExamples/data/iris.csv"
# df = pd.read_csv(url, header=None)
# X = df.iloc[:, :4].values
# y = df.iloc[:, 4].values
# # Train model
# model = LogisticRegression(max_iter=200)
# model.fit(X, y)
# # Flask app
# app = Flask(__name__)
# @app.route("/", methods=["GET", "POST"])
# def home():
# if request.method == "POST":
# try:
# sepal_length = float(request.form["sepal_length"])
# sepal_width = float(request.form["sepal_width"])
# petal_length = float(request.form["petal_length"])
# petal_width = float(request.form["petal_width"])
# prediction = model.predict([[sepal_length, sepal_width, petal_length, petal_width]])[0]
# return render_template("index.html", prediction_text=f"Predicted Flower: {prediction}")
# except Exception as e:
# return render_template("index.html", prediction_text=f"Error: {e}")
# return render_template("index.html", prediction_text="")
# if __name__ == "__main__":
# app.run(host="0.0.0.0", port=7860, debug=True)