VoiceVision-AI / app.py
azizmeer40's picture
Update app.py
4be71ed verified
import base64
import numpy as np
import cv2
import sqlite3
import os
from flask import Flask, render_template, request, session, redirect, url_for, flash, jsonify
from utils.object_detection import detect_objects
from flask_cors import CORS
app = Flask(__name__)
app.secret_key = 'voicevision_key_123'
CORS(app)
# Hugging Face iframe session fix
app.config.update(
SESSION_COOKIE_SAMESITE='None',
SESSION_COOKIE_SECURE=True
)
DB_PATH = "/tmp/database.db"
def get_db_connection():
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
return conn
def init_db():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL
)
''')
conn.commit()
conn.close()
# Start DB
init_db()
@app.route('/')
def home():
return redirect(url_for('signup'))
@app.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
username = request.form.get('username', '').strip()
if username:
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("INSERT INTO users (username) VALUES (?)", (username,))
conn.commit()
conn.close()
flash("Signup successful! Now Login.", "success")
return redirect(url_for('login'))
except sqlite3.IntegrityError:
flash("Username exists!", "error")
return redirect(url_for('signup'))
return render_template('signup.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# Login ke waqt session clear karein taake auto-logout na ho
session.clear()
username = request.form.get('username', '').strip()
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
user = cursor.fetchone()
conn.close()
if user:
session.permanent = True
session['user'] = username
return redirect(url_for('dashboard'))
else:
flash("User not found!", "error")
return render_template('login.html')
@app.route('/dashboard')
def dashboard():
if 'user' in session:
return render_template('index.html', user=session['user'])
print("DEBUG: Session not found, redirecting to login.")
return redirect(url_for('login'))
@app.route('/process_frame', methods=['POST'])
def process_frame():
try:
data = request.json['image']
img_data = base64.b64decode(data.split(',')[1])
nparr = np.frombuffer(img_data, np.uint8)
frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
# Confidence thoda kam (0.35) taake cheezein miss na hon
detections = detect_objects(frame, confidence=0.35)
# AREA-BASED SORTING (Zaroori hai VI ke liye)
if detections:
# Sabse bari cheez list mein pehle aayegi
detections = sorted(detections, key=lambda x: x['w'] * x['h'], reverse=True)
# Sirf top 3 cheezein bhejien taake frontend fast rahe
detections = detections[:3]
return jsonify({"detections": detections})
except Exception as e:
return jsonify({"error": "Processing error"}), 400
# @app.route('/logout')
# def logout():
# session.clear()
# return redirect(url_for('login'))
@app.route('/logout')
def logout():
session.clear() # Clear everything
# Browser ko cache saaf karne ka kahein
response = redirect(url_for('login'))
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
return response
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)