Spaces:
Sleeping
Sleeping
Daniel Idanan commited on
Commit ·
6471df5
1
Parent(s): 6a6fcbb
fixing login
Browse filesFiles changed (6)
8 unmodified lines910111213141516171819202145 unmodified lines67686970717273747576775 unmodified lines83848586878889903 unmodified lines94959697989910026 unmodified lines12712812913013113213313413513613713813914014114293 unmodified lines2362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942955 unmodified lines30130230330430530630725 unmodified lines3333343353363373383393403413423433443453463473483493507 unmodified lines3583593603613623633648 unmodified linesfrom tensorflow.keras.preprocessing import image as keras_imageapp = Flask(__name__)app.secret_key = "ecosort_secret_key"app.config["SESSION_TYPE"] = "filesystem"app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(minutes=10)app.config["SESSION_COOKIE_SECURE"] = False # Set to True when using HTTPSapp.config["SESSION_COOKIE_HTTPONLY"] = Trueapp.config["SESSION_COOKIE_SAMESITE"] = "Lax"@app.before_requestdef make_session_permanent():45 unmodified linesprediction TEXT NOT NULL,confidence TEXT NOT NULL,tip TEXT NOT NULL,scanned_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,FOREIGN KEY(user_id) REFERENCES users(id))""")conn.commit()conn.close()5 unmodified linesimg_array = np.expand_dims(img_array, axis=0) / 255.0predictions = model.predict(img_array, verbose=0)predicted_index = np.argmax(predictions[0])confidence = float(np.max(predictions[0])) * 100label_map = {"biodegradable": ("Biodegradable", "Place this item in the biodegradable waste bin."),3 unmodified linesraw_label = class_names[predicted_index]prediction, tip = label_map[raw_label]return prediction, f"{confidence:.2f}%", tipdef login_user(user):26 unmodified linesgoogle = oauth.register(name="google",client_id=os.environ.get("GOOGLE_CLIENT_ID"),client_secret=os.environ.get("GOOGLE_CLIENT_SECRET"),server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",client_kwargs={"scope": "openid email profile"},)facebook = oauth.register(name="facebook",client_id=os.environ.get("FACEBOOK_CLIENT_ID"),client_secret=os.environ.get("FACEBOOK_CLIENT_SECRET"),access_token_url="https://graph.facebook.com/oauth/access_token",authorize_url="https://www.facebook.com/dialog/oauth",api_base_url="https://graph.facebook.com/",93 unmodified lines@app.route("/login/google")def google_login():if not os.environ.get("GOOGLE_CLIENT_ID") or not os.environ.get("GOOGLE_CLIENT_SECRET"):flash("Google OAuth credentials are missing.", "error")return redirect(url_for("login"))redirect_uri = url_for("google_callback", _external=True)state = os.urandom(16).hex()session["oauth_state"] = statesession.modified = Truereturn google.authorize_redirect(redirect_uri, state=state)@app.route("/login/google/callback")def google_callback():try:session.pop("oauth_state", None)token = google.authorize_access_token()resp = google.get("https://www.googleapis.com/oauth2/v3/userinfo", token=token)user_info = resp.json()email = user_info.get("email")name = user_info.get("name", "Google User")user = find_or_create_oauth_user(name, email)login_user(user)flash(f"Welcome, {name}!", "success")return redirect(url_for("index"))except Exception as e:flash(f"Google login failed: {e}", "error")return redirect(url_for("login"))# ===================== FACEBOOK OAUTH =====================@app.route("/login/facebook")def facebook_login():if not os.environ.get("FACEBOOK_CLIENT_ID") or not os.environ.get("FACEBOOK_CLIENT_SECRET"):flash("Facebook OAuth credentials are missing.", "error")return redirect(url_for("login"))redirect_uri = url_for("facebook_callback", _external=True)session["oauth_state"] = os.urandom(16).hex()return facebook.authorize_redirect(redirect_uri)@app.route("/login/facebook/callback")def facebook_callback():try:session.pop("oauth_state", None)token = facebook.authorize_access_token()resp = facebook.get("me?fields=id,name,email", token=token)profile = resp.json()if not profile or "email" not in profile:flash("Facebook login failed — email not provided.", "error")return redirect(url_for("login"))email = profile.get("email")5 unmodified linesreturn redirect(url_for("index"))except Exception as e:flash(f"Facebook login failed: {e}", "error")return redirect(url_for("login"))# ===================== MAIN ROUTES =====================25 unmodified linesimage.save(saved_file_path)db_image_path = f"uploads/{unique_filename}"prediction, confidence, tip = predict_waste(saved_file_path)conn = get_db_connection()cursor = conn.cursor()cursor.execute("INSERT INTO scans (user_id, image_path, prediction, confidence, tip) VALUES (?, ?, ?, ?, ?)",(session["user_id"], db_image_path, prediction, confidence, tip))conn.commit()conn.close()return render_template("result.html", prediction=prediction, confidence=confidence, tip=tip, image=db_image_path)return render_template("index.html", user_name=session["user_name"])7 unmodified linesconn = get_db_connection()cursor = conn.cursor()base_query = "SELECT id, image_path, prediction, confidence, tip, scanned_at FROM scans WHERE user_id = ? {condition} ORDER BY id DESC"if filter_type == "reduce":condition = "AND (prediction LIKE '%non_recyclable%' OR prediction LIKE '%non-recyclable%' OR prediction LIKE '%Non-recyclable%')"8 unmodified lines9101112131415161718192021222324252645 unmodified lines727374757677787980818283848586878889905 unmodified lines969798991001011021031043 unmodified lines10810911011111211311411511611711811912012126 unmodified lines14814915015115215315415515615715815916016116216393 unmodified lines2572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083095 unmodified lines31531631731831932032125 unmodified lines3473483493503513523533543553563573583593603613623633647 unmodified lines3723733743753763773788 unmodified linesfrom tensorflow.keras.preprocessing import image as keras_imageapp = Flask(__name__)app.secret_key = os.environ.get("SECRET_KEY", "ecosort_secret_key_change_in_prod")# Fix redirect URIs when behind a proxy (Render uses HTTPS)from werkzeug.middleware.proxy_fix import ProxyFixapp.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)app.config["SESSION_TYPE"] = "filesystem"app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(minutes=10)app.config["SESSION_COOKIE_SECURE"] = False # Set to True when using HTTPSapp.config["SESSION_COOKIE_HTTPONLY"] = Trueapp.config["SESSION_COOKIE_SAMESITE"] = "Lax"app.config["PREFERRED_URL_SCHEME"] = "https"@app.before_requestdef make_session_permanent():45 unmodified linesprediction TEXT NOT NULL,confidence TEXT NOT NULL,tip TEXT NOT NULL,probs TEXT NOT NULL DEFAULT '0|0|0',scanned_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,FOREIGN KEY(user_id) REFERENCES users(id))""")# Migration: add probs column if it doesn't exist (for existing databases)try:cursor.execute("ALTER TABLE scans ADD COLUMN probs TEXT NOT NULL DEFAULT '0|0|0'")conn.commit()except Exception:pass # Column already existsconn.commit()conn.close()5 unmodified linesimg_array = np.expand_dims(img_array, axis=0) / 255.0predictions = model.predict(img_array, verbose=0)probs = predictions[0] # shape: (3,) — one prob per classpredicted_index = int(np.argmax(probs))confidence = float(np.max(probs)) * 100label_map = {"biodegradable": ("Biodegradable", "Place this item in the biodegradable waste bin."),3 unmodified linesraw_label = class_names[predicted_index]prediction, tip = label_map[raw_label]# Build a name→prob dict aligned to our fixed class order# class_names order from training: ["biodegradable", "non_recyclable", "recyclable"]# We store as "biodegradable|non_recyclable|recyclable" probabilities (0-100, rounded)prob_dict = {class_names[i]: round(float(probs[i]) * 100, 2) for i in range(len(class_names))}prob_str = f"{prob_dict.get('biodegradable', 0):.2f}|{prob_dict.get('non_recyclable', 0):.2f}|{prob_dict.get('recyclable', 0):.2f}"return prediction, f"{confidence:.2f}%", tip, prob_strdef login_user(user):26 unmodified linesgoogle = oauth.register(name="google",client_id=os.environ.get("GOOGLE_CLIENT_ID", "99512363553-c6vpqhkhitvt2cn8ralo9h04gkk474uk.apps.googleusercontent.com"),client_secret=os.environ.get("GOOGLE_CLIENT_SECRET", "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"),server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",client_kwargs={"scope": "openid email profile"},)facebook = oauth.register(name="facebook",client_id=os.environ.get("FACEBOOK_CLIENT_ID", "2133400210781599"),client_secret=os.environ.get("FACEBOOK_CLIENT_SECRET", "c14a167529f2c2d332731790d1344f5d"),access_token_url="https://graph.facebook.com/oauth/access_token",authorize_url="https://www.facebook.com/dialog/oauth",api_base_url="https://graph.facebook.com/",93 unmodified lines@app.route("/login/google")def google_login():if not (os.environ.get("GOOGLE_CLIENT_ID") or "99512363553" in "99512363553-c6vpqhkhitvt2cn8ralo9h04gkk474uk.apps.googleusercontent.com"):flash("Google OAuth credentials are missing.", "error")return redirect(url_for("login"))redirect_uri = url_for("google_callback", _external=True)return google.authorize_redirect(redirect_uri)@app.route("/login/google/callback")def google_callback():try:token = google.authorize_access_token()user_info = token.get("userinfo") or google.get("https://www.googleapis.com/oauth2/v3/userinfo", token=token).json()email = user_info.get("email")name = user_info.get("name", "Google User")if not email:flash("Google login failed — email not provided.", "error")return redirect(url_for("login"))user = find_or_create_oauth_user(name, email)login_user(user)flash(f"Welcome, {name}!", "success")return redirect(url_for("index"))except Exception as e:flash(f"Google login failed: {str(e)}", "error")return redirect(url_for("login"))# ===================== FACEBOOK OAUTH =====================@app.route("/login/facebook")def facebook_login():redirect_uri = url_for("facebook_callback", _external=True)return facebook.authorize_redirect(redirect_uri)@app.route("/login/facebook/callback")def facebook_callback():try:token = facebook.authorize_access_token()resp = facebook.get("me?fields=id,name,email", token=token)profile = resp.json()if not profile or "email" not in profile:flash("Facebook login failed — email not provided. Make sure your Facebook account has a verified email.", "error")return redirect(url_for("login"))email = profile.get("email")5 unmodified linesreturn redirect(url_for("index"))except Exception as e:flash(f"Facebook login failed: {str(e)}", "error")return redirect(url_for("login"))# ===================== MAIN ROUTES =====================25 unmodified linesimage.save(saved_file_path)db_image_path = f"uploads/{unique_filename}"prediction, confidence, tip, prob_str = predict_waste(saved_file_path)conn = get_db_connection()cursor = conn.cursor()cursor.execute("INSERT INTO scans (user_id, image_path, prediction, confidence, tip, probs) VALUES (?, ?, ?, ?, ?, ?)",(session["user_id"], db_image_path, prediction, confidence, tip, prob_str))conn.commit()conn.close()return render_template("result.html", prediction=prediction, confidence=confidence, tip=tip, image=db_image_path, probs=prob_str)return render_template("index.html", user_name=session["user_name"])7 unmodified linesconn = get_db_connection()cursor = conn.cursor()base_query = "SELECT id, image_path, prediction, confidence, tip, scanned_at, COALESCE(probs,'0|0|0') FROM scans WHERE user_id = ? {condition} ORDER BY id DESC"if filter_type == "reduce":condition = "AND (prediction LIKE '%non_recyclable%' OR prediction LIKE '%non-recyclable%' OR prediction LIKE '%Non-recyclable%')"
20 unmodified lines21222324252627283 unmodified lines3233343536373839404142434445464748495020 unmodified lines* @param {string} confidence - Confidence percentage* @param {string} tip - Waste disposal tip* @param {string} date - Scan date*/function openModal(imagePath, prediction, confidence, tip, date) {const modal = document.getElementById("analysisModal");document.getElementById("modalImage").src = "/static/" + imagePath;3 unmodified linesdocument.getElementById("modalTip").textContent = tip;let reduce, reuse, recycle;const predLower = prediction.toLowerCase();if (predLower.includes("non_recyclable") || predLower.includes("non-recyclable")) {reduce = 70; reuse = 20; recycle = 10;highlightCard("reduceCard");} else if (predLower.includes("recyclable")) {reduce = 20; reuse = 30; recycle = 50;highlightCard("recycleCard");} else if (predLower.includes("biodegradable")) {reduce = 30; reuse = 40; recycle = 30;highlightCard("reuseCard");} else {reduce = 33; reuse = 33; recycle = 34;highlightCard("recycleCard");}20 unmodified lines2122232425262728293 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757620 unmodified lines* @param {string} confidence - Confidence percentage* @param {string} tip - Waste disposal tip* @param {string} date - Scan date* @param {string} probs - Pipe-separated AI probabilities: "biodegradable|non_recyclable|recyclable"*/function openModal(imagePath, prediction, confidence, tip, date, probs) {const modal = document.getElementById("analysisModal");document.getElementById("modalImage").src = "/static/" + imagePath;3 unmodified linesdocument.getElementById("modalTip").textContent = tip;let reduce, reuse, recycle;// Try to use real AI probabilities firstif (probs && probs !== "0|0|0" && probs.includes("|")) {const parts = probs.split("|").map(Number);// probs are stored as: biodegradable | non_recyclable | recyclableconst bioProb = parts[0] || 0;const nonProb = parts[1] || 0;const recProb = parts[2] || 0;// Map AI probabilities to RRR framework:// Reduce ← non_recyclable probability (minimize waste that can't be processed)// Reuse ← biodegradable probability (compost / organic reuse)// Recycle ← recyclable probability (send to recycling)const total = bioProb + nonProb + recProb || 100;reduce = Math.round((nonProb / total) * 100);reuse = Math.round((bioProb / total) * 100);recycle = 100 - reduce - reuse; // ensure they sum to 100} else {// Fallback to heuristics if probs not stored (old records)const predLower = prediction.toLowerCase();if (predLower.includes("non_recyclable") || predLower.includes("non-recyclable")) {reduce = 70; reuse = 20; recycle = 10;} else if (predLower.includes("recyclable")) {reduce = 10; reuse = 15; recycle = 75;} else if (predLower.includes("biodegradable")) {reduce = 15; reuse = 70; recycle = 15;} else {reduce = 33; reuse = 33; recycle = 34;}}// Highlight the dominant action cardconst predLower = prediction.toLowerCase();if (predLower.includes("non_recyclable") || predLower.includes("non-recyclable")) {highlightCard("reduceCard");} else if (predLower.includes("biodegradable")) {highlightCard("reuseCard");} else {highlightCard("recycleCard");}
59 unmodified lines60616263646566676830 unmodified lines9910010110210310410510610710810911059 unmodified lines<div class="history-list">{% if scans %}{% for scan in scans %}<div class="history-item" onclick="openModal('{{ scan[1] }}', '{{ scan[2] }}', '{{ scan[3] }}', '{{ scan[4] }}', '{{ scan[5] }}')"><div class="history-top"><img src="{{ url_for('static', filename=scan[1]) }}" alt="Scanned Waste"><span class="click-hint"><i class="fa-solid fa-expand"></i> Click to analyze</span></div><div class="history-details">30 unmodified lines<!-- Modal for RRR Analysis --><div id="analysisModal" class="modal"><div class="modal-content"><div class="modal-header"><h3><i class="fa-solid fa-chart-pie"></i> Waste Analysis</h3><button class="close-btn" onclick="closeModal()"><i class="fa-solid fa-xmark"></i></button></div><img id="modalImage" class="modal-image" src="" alt="Waste Item"><div class="history-details" style="margin-bottom: 15px;"><p><strong>AI Prediction:</strong> <span id="modalPrediction"></span></p><p><strong>Confidence:</strong> <span id="modalConfidence"></span></p>59 unmodified lines60616263646566676830 unmodified lines9910010110210310410510610710810911059 unmodified lines<div class="history-list">{% if scans %}{% for scan in scans %}<div class="history-item" onclick="openModal('{{ scan[1] }}', '{{ scan[2] }}', '{{ scan[3] }}', '{{ scan[4] }}', '{{ scan[5] }}', '{{ scan[6] }}')" data-probs="{{ scan[6] }}"><div class="history-top"><img src="{{ url_for('static', filename=scan[1]) }}" alt="Scanned Waste" style="width:100%;height:160px;object-fit:contain;background:rgba(0,0,0,0.2);display:block;"><span class="click-hint"><i class="fa-solid fa-expand"></i> Click to analyze</span></div><div class="history-details">30 unmodified lines<!-- Modal for RRR Analysis --><div id="analysisModal" class="modal"><div class="modal-content" style="max-height:90vh;overflow-y:auto;"><div class="modal-header"><h3><i class="fa-solid fa-chart-pie"></i> Waste Analysis</h3><button class="close-btn" onclick="closeModal()"><i class="fa-solid fa-xmark"></i></button></div><img id="modalImage" class="modal-image" src="" alt="Waste Item" style="width:100%;height:220px;object-fit:contain;background:rgba(0,0,0,0.25);border-radius:16px;margin-bottom:16px;display:block;"><div class="history-details" style="margin-bottom: 15px;"><p><strong>AI Prediction:</strong> <span id="modalPrediction"></span></p><p><strong>Confidence:</strong> <span id="modalConfidence"></span></p>
app.py+44-30
.python-version → info/.python-versionRenamed
requirements.txt → info/requirements.txtRenamed
runtime.txt → info/runtime.txtRenamed
static/js/app.js+34-8
templates/history.html+4-4