# -*- coding: utf-8 -*-
# Set matplotlib config directory to avoid permission issues
import os
os.environ['MPLCONFIGDIR'] = '/tmp/matplotlib'
from flask import Flask, request, jsonify, send_from_directory, redirect, url_for, session, render_template_string, make_response, Response, stream_with_context
from datetime import timedelta
import torch
from PIL import Image
import numpy as np
import io
from io import BytesIO
import base64
import uuid
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import time
from flask_cors import CORS
import json
import sys
import requests
import asyncio
from threading import Thread
import tempfile
try:
from openai import OpenAI
except Exception as _e:
OpenAI = None
try:
# LangChain for RAG answering
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
except Exception as _e:
ChatOpenAI = None
ChatPromptTemplate = None
StrOutputParser = None
from flask_login import (
LoginManager,
UserMixin,
login_user,
logout_user,
login_required,
current_user,
fresh_login_required,
login_fresh,
)
try:
# PEFT for LoRA adapters (optional)
from peft import PeftModel
except Exception as _e:
PeftModel = None
# Fix for SQLite3 version compatibility with ChromaDB
try:
import pysqlite3
sys.modules['sqlite3'] = pysqlite3
except ImportError:
print("Warning: pysqlite3 not found, using built-in sqlite3")
import chromadb
from chromadb.utils import embedding_functions
app = Flask(__name__, static_folder='static')
# Import product comparison coordinator with detailed debugging
print("=" * 80)
print("[STARTUP DEBUG] ๐ Testing product_comparison import at startup...")
print("=" * 80)
try:
print("[DEBUG] Attempting to import product_comparison module...")
from product_comparison import get_product_comparison_coordinator, decode_base64_image
print("[DEBUG] โ Product comparison module imported successfully!")
print(f"[DEBUG] โ get_product_comparison_coordinator: {get_product_comparison_coordinator}")
print(f"[DEBUG] โ decode_base64_image: {decode_base64_image}")
# Test coordinator creation
print("[DEBUG] Testing coordinator creation...")
test_coordinator = get_product_comparison_coordinator()
print(f"[DEBUG] โ Test coordinator created: {type(test_coordinator).__name__}")
except ImportError as e:
print(f"[DEBUG] โ Product comparison import failed: {e}")
print(f"[DEBUG] โ Import error type: {type(e).__name__}")
print(f"[DEBUG] โ Import error args: {e.args}")
import traceback
print("[DEBUG] โ Full import traceback:")
traceback.print_exc()
print("Warning: Product comparison module not available")
get_product_comparison_coordinator = None
decode_base64_image = None
except Exception as e:
print(f"[DEBUG] โ Unexpected error during import: {e}")
print(f"[DEBUG] โ Error type: {type(e).__name__}")
import traceback
print("[DEBUG] โ Full traceback:")
traceback.print_exc()
get_product_comparison_coordinator = None
decode_base64_image = None
print("=" * 80)
print(f"[STARTUP DEBUG] ๐ Import test completed. Coordinator available: {get_product_comparison_coordinator is not None}")
print(f"[STARTUP DEBUG] ๐ Current working directory: {os.getcwd()}")
print(f"[STARTUP DEBUG] ๐ Files in current directory: {os.listdir('.')}")
print("=" * 80)
# ํ๊ฒฝ ๋ณ์์์ ๋น๋ฐ ํค๋ฅผ ๊ฐ์ ธ์ค๊ฑฐ๋, ์์ผ๋ฉด ์์ ํ ๋๋ค ํค ์์ฑ
secret_key = os.environ.get('FLASK_SECRET_KEY')
if not secret_key:
import secrets
secret_key = secrets.token_hex(16) # 32์ ๊ธธ์ด์ ๋๋ค 16์ง์ ๋ฌธ์์ด ์์ฑ
print("WARNING: FLASK_SECRET_KEY ํ๊ฒฝ ๋ณ์๊ฐ ์ค์ ๋์ง ์์์ต๋๋ค. ๋๋ค ํค๋ฅผ ์์ฑํ์ต๋๋ค.")
print("์๋ฒ ์ฌ์์ ์ ์ธ์
์ด ๋ชจ๋ ๋ง๋ฃ๋ฉ๋๋ค. ํ๋ก๋์
ํ๊ฒฝ์์๋ ํ๊ฒฝ ๋ณ์๋ฅผ ์ค์ ํ์ธ์.")
app.secret_key = secret_key # ์ธ์
์ํธํ๋ฅผ ์ํ ๋น๋ฐ ํค
app.config['CORS_HEADERS'] = 'Content-Type'
# Remember cookie (Flask-Login) โ minimize duration to prevent auto re-login
app.config['REMEMBER_COOKIE_DURATION'] = timedelta(seconds=1)
# Cookie settings for Hugging Face Spaces compatibility
app.config['REMEMBER_COOKIE_SECURE'] = False
app.config['REMEMBER_COOKIE_HTTPONLY'] = False # Allow JS access for debugging
app.config['REMEMBER_COOKIE_SAMESITE'] = None # Most permissive for iframe
# Session cookie settings - most permissive for HF Spaces
app.config['SESSION_COOKIE_SECURE'] = False
app.config['SESSION_COOKIE_HTTPONLY'] = False # Allow JS access
app.config['SESSION_COOKIE_SAMESITE'] = None # Most permissive for iframe
app.config['SESSION_COOKIE_PATH'] = '/'
app.config['SESSION_COOKIE_DOMAIN'] = None
CORS(app, supports_credentials=True) # Enable CORS for all routes with credentials
# Dynamic HTTPS detection and cookie security settings
@app.before_request
def configure_cookies_for_https():
"""Dynamically configure cookie security based on HTTPS detection"""
is_https = (
request.is_secure or
request.headers.get('X-Forwarded-Proto') == 'https' or
request.headers.get('X-Forwarded-Ssl') == 'on' or
os.environ.get('HTTPS', '').lower() == 'true'
)
if is_https:
app.config['SESSION_COOKIE_SECURE'] = True
app.config['REMEMBER_COOKIE_SECURE'] = True
# ์ํฌ๋ฆฟ ํค ์ค์ (์ธ์
์ํธํ์ ์ฌ์ฉ)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'vision_llm_agent_secret_key')
app.config['SESSION_TYPE'] = 'filesystem'
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(seconds=120) # ์ธ์
์ ํจ ์๊ฐ (2๋ถ)
app.config['SESSION_REFRESH_EACH_REQUEST'] = False # ์ ๋ ๋ง๋ฃ(๋ก๊ทธ์ธ ๊ธฐ์ค 2๋ถ ํ ๋ง๋ฃ)
# Fix session cookie issues in Hugging Face Spaces
app.config['SESSION_COOKIE_NAME'] = 'session'
app.config['SESSION_COOKIE_DOMAIN'] = None # Allow any domain
app.config['SESSION_KEY_PREFIX'] = 'session:'
# Flask-Login ์ค์
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
login_manager.session_protection = 'strong'
# When authentication is required or session is not fresh, redirect to login instead of 401
login_manager.refresh_view = 'login'
@login_manager.unauthorized_handler
def handle_unauthorized():
# For non-authenticated access, send user to login
return redirect(url_for('login'))
@login_manager.needs_refresh_handler
def handle_needs_refresh():
# For non-fresh sessions (e.g., after expiry or only remember-cookie), send to login
return redirect(url_for('login'))
# ์ธ์
์ค์
import tempfile
from flask_session import Session
# ์์ ๋๋ ํ ๋ฆฌ๋ฅผ ์ฌ์ฉํ์ฌ ๊ถํ ๋ฌธ์ ํด๊ฒฐ
session_dir = tempfile.gettempdir()
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_PERMANENT'] = True
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_FILE_DIR'] = session_dir
print(f"Using session directory: {session_dir}")
Session(app)
# ์ฌ์ฉ์ ํด๋์ค ์ ์
class User(UserMixin):
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
def get_id(self):
return str(self.id) # Flask-Login์ ๋ฌธ์์ด ID๋ฅผ ์๊ตฌํจ
# ํ
์คํธ์ฉ ์ฌ์ฉ์ (์ค์ ํ๊ฒฝ์์๋ ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ฌ์ฉ ๊ถ์ฅ)
# ํ๊ฒฝ ๋ณ์์์ ์ฌ์ฉ์ ๊ณ์ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๊ธฐ (๊ธฐ๋ณธ๊ฐ ์์)
admin_username = os.environ.get('ADMIN_USERNAME', 'admin')
admin_password = os.environ.get('ADMIN_PASSWORD')
user_username = os.environ.get('USER_USERNAME', 'user')
user_password = os.environ.get('USER_PASSWORD')
# ํ๊ฒฝ ๋ณ์๊ฐ ์ค์ ๋์ง ์์์ ๊ฒฝ์ฐ ๊ฒฝ๊ณ ๋ฉ์์ง ์ถ๋ ฅ
if not admin_password or not user_password:
print("ERROR: ํ๊ฒฝ ๋ณ์ ADMIN_PASSWORD ๋๋ USER_PASSWORD๊ฐ ์ค์ ๋์ง ์์์ต๋๋ค.")
print("Hugging Face Spaces์์ ๋ฐ๋์ ํ๊ฒฝ ๋ณ์๋ฅผ ์ค์ ํด์ผ ํฉ๋๋ค.")
print("Settings > Repository secrets์์ ํ๊ฒฝ ๋ณ์๋ฅผ ์ถ๊ฐํ์ธ์.")
# ํ๊ฒฝ ๋ณ์๊ฐ ์์ ๊ฒฝ์ฐ ์์ ๋น๋ฐ๋ฒํธ ์์ฑ (๊ฐ๋ฐ์ฉ)
import secrets
if not admin_password:
admin_password = secrets.token_hex(8) # ์์ ๋น๋ฐ๋ฒํธ ์์ฑ
print(f"WARNING: ์์ admin ๋น๋ฐ๋ฒํธ๊ฐ ์์ฑ๋์์ต๋๋ค: {admin_password}")
if not user_password:
user_password = secrets.token_hex(8) # ์์ ๋น๋ฐ๋ฒํธ ์์ฑ
print(f"WARNING: ์์ user ๋น๋ฐ๋ฒํธ๊ฐ ์์ฑ๋์์ต๋๋ค: {user_password}")
users = {
admin_username: User('1', admin_username, admin_password),
user_username: User('2', user_username, user_password)
}
# Manual authentication check function
def check_authentication():
"""Check authentication via session, cookies, or headers. Returns (user_id, username) or (None, None)"""
# Check session first
user_id = session.get('user_id')
username = session.get('username')
# Fallback to cookies if session is empty
if not user_id or not username:
user_id = request.cookies.get('auth_user_id')
username = request.cookies.get('auth_username')
# Fallback to headers (for localStorage-based auth)
if not user_id or not username:
user_id = request.headers.get('X-Auth-User-ID')
username = request.headers.get('X-Auth-Username')
print(f"[DEBUG] Auth from headers: user_id={user_id}, username={username}")
# Fallback to query params (for SSE/EventSource where custom headers aren't supported)
if not user_id or not username:
user_id = request.args.get('uid')
username = request.args.get('uname')
if user_id or username:
print(f"[DEBUG] Auth from query params: user_id={user_id}, username={username}")
if not user_id or not username:
return None, None
# Verify user exists
for stored_username, user_obj in users.items():
# users maps username -> User instance; compare using attributes
if str(getattr(user_obj, 'id', None)) == str(user_id) and stored_username == username:
return user_id, username
return None, None
def require_auth():
"""Decorator replacement for @login_required that supports cookie fallback"""
def decorator(f):
def decorated_function(*args, **kwargs):
user_id, username = check_authentication()
if not user_id:
return jsonify({"error": "Authentication required"}), 401
return f(*args, **kwargs)
decorated_function.__name__ = f.__name__
return decorated_function
return decorator
# ์ฌ์ฉ์ ๋ก๋ ํจ์
@login_manager.user_loader
def load_user(user_id):
print(f"Loading user with ID: {user_id}")
# ์ธ์
๋๋ฒ๊ทธ ์ ๋ณด ์ถ๋ ฅ
print(f"Session data in user_loader: {dict(session)}")
print(f"Current request cookies: {request.cookies}")
# Check session first, then fallback to cookies
session_user_id = session.get('user_id')
if not session_user_id:
# Try to get from cookies
cookie_user_id = request.cookies.get('auth_user_id')
cookie_username = request.cookies.get('auth_username')
print(f"Session empty, checking cookies: user_id={cookie_user_id}, username={cookie_username}")
if cookie_user_id and cookie_username:
# Verify cookie user exists
for username, user in users.items():
if str(user.id) == str(cookie_user_id) and username == cookie_username:
print(f"User found via cookies: {username}, ID: {user.id}")
# Restore session from cookies
session['user_id'] = user.id
session['username'] = username
session.modified = True
return user
# Original session-based lookup
for username, user in users.items():
if str(user.id) == str(user_id): # ํ์คํ ๋ฌธ์์ด ๋น๊ต
print(f"User found: {username}, ID: {user.id}")
# ์ธ์
์ ๋ณด ์
๋ฐ์ดํธ
session['user_id'] = user.id
session['username'] = username
session.modified = True
return user
print(f"User not found with ID: {user_id}")
return None
# Model initialization
print("Loading models... This may take a moment.")
# Image embedding model (CLIP) for vector search
clip_model = None
clip_processor = None
try:
from transformers import CLIPProcessor, CLIPModel
# ์์ ๋๋ ํ ๋ฆฌ ์ฌ์ฉ
import tempfile
temp_dir = tempfile.gettempdir()
os.environ["TRANSFORMERS_CACHE"] = temp_dir
# CLIP ๋ชจ๋ธ ๋ก๋ (์ด๋ฏธ์ง ์๋ฒ ๋ฉ์ฉ)
clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
print("CLIP model loaded successfully")
except Exception as e:
print("Error loading CLIP model:", e)
clip_model = None
clip_processor = None
# Vector DB ์ด๊ธฐํ
vector_db = None
image_collection = None
object_collection = None
try:
# ChromaDB ํด๋ผ์ด์ธํธ ์ด๊ธฐํ (์ธ๋ฉ๋ชจ๋ฆฌ DB)
vector_db = chromadb.Client()
# ์๋ฒ ๋ฉ ํจ์ ์ค์
ef = embedding_functions.DefaultEmbeddingFunction()
# ์ด๋ฏธ์ง ์ปฌ๋ ์
์์ฑ
image_collection = vector_db.create_collection(
name="image_collection",
embedding_function=ef,
get_or_create=True
)
# ๊ฐ์ฒด ์ธ์ ๊ฒฐ๊ณผ ์ปฌ๋ ์
์์ฑ
object_collection = vector_db.create_collection(
name="object_collection",
embedding_function=ef,
get_or_create=True
)
print("Vector DB initialized successfully")
except Exception as e:
print("Error initializing Vector DB:", e)
vector_db = None
image_collection = None
object_collection = None
# YOLOv8 model
yolo_model = None
try:
import os
from ultralytics import YOLO
# ๋ชจ๋ธ ํ์ผ ๊ฒฝ๋ก - ์์ ๋๋ ํ ๋ฆฌ ์ฌ์ฉ
import tempfile
temp_dir = tempfile.gettempdir()
model_path = os.path.join(temp_dir, "yolov8n.pt")
# ๋ชจ๋ธ ํ์ผ์ด ์์ผ๋ฉด ์ง์ ๋ค์ด๋ก๋
if not os.path.exists(model_path):
print(f"Downloading YOLOv8 model to {model_path}...")
try:
os.system(f"wget -q https://ultralytics.com/assets/yolov8n.pt -O {model_path}")
print("YOLOv8 model downloaded successfully")
except Exception as e:
print(f"Error downloading YOLOv8 model: {e}")
# ๋ค์ด๋ก๋ ์คํจ ์ ๋์ฒด URL ์๋
try:
os.system(f"wget -q https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt -O {model_path}")
print("YOLOv8 model downloaded from alternative source")
except Exception as e2:
print(f"Error downloading from alternative source: {e2}")
# ๋ง์ง๋ง ๋์์ผ๋ก ์ง์ ๋ชจ๋ธ URL ์ฌ์ฉ
try:
os.system(f"curl -L https://ultralytics.com/assets/yolov8n.pt --output {model_path}")
print("YOLOv8 model downloaded using curl")
except Exception as e3:
print(f"All download attempts failed: {e3}")
# ํ๊ฒฝ ๋ณ์ ์ค์ - ์ค์ ํ์ผ ๊ฒฝ๋ก ์ง์
os.environ["YOLO_CONFIG_DIR"] = temp_dir
os.environ["MPLCONFIGDIR"] = temp_dir
yolo_model = YOLO(model_path) # Using the nano model for faster inference
print("YOLOv8 model loaded successfully")
except Exception as e:
print("Error loading YOLOv8 model:", e)
yolo_model = None
# DETR model (DEtection TRansformer)
detr_processor = None
detr_model = None
try:
from transformers import DetrImageProcessor, DetrForObjectDetection
detr_processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
detr_model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
print("DETR model loaded successfully")
except Exception as e:
print("Error loading DETR model:", e)
detr_processor = None
detr_model = None
# ViT model
vit_processor = None
vit_model = None
try:
from transformers import ViTImageProcessor, ViTForImageClassification
vit_processor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224")
vit_model = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224")
print("ViT model loaded successfully")
except Exception as e:
print("Error loading ViT model:", e)
vit_processor = None
vit_model = None
# Get device information
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# llama.cpp (GGUF) support
llama_cpp = None
llama_cpp_model = None
gguf_model_path = None
try:
import llama_cpp as llama_cpp
def ensure_q4_gguf_model():
"""Download a TinyLlama Q4 GGUF model if not present and return the local path."""
global gguf_model_path
cache_dir = os.path.join(tempfile.gettempdir(), "gguf_models")
os.makedirs(cache_dir, exist_ok=True)
# Use a small, permissively accessible TinyLlama GGUF
filename = "TinyLlama-1.1B-Chat-v1.0.Q4_K_M.gguf"
gguf_model_path = os.path.join(cache_dir, filename)
if not os.path.exists(gguf_model_path):
try:
url = (
"https://huggingface.co/TinyLlama/"
"TinyLlama-1.1B-Chat-v1.0-GGUF/resolve/main/"
+ filename
)
print(f"[GGUF] Downloading model from {url} -> {gguf_model_path}")
with requests.get(url, stream=True, timeout=60) as r:
r.raise_for_status()
with open(gguf_model_path, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
print("[GGUF] Download complete")
except Exception as e:
print(f"[GGUF] Failed to download GGUF model: {e}")
return None
return gguf_model_path
def get_llama_cpp_model():
"""Lazy-load llama.cpp model from local GGUF path."""
global llama_cpp_model
if llama_cpp_model is not None:
return llama_cpp_model
model_path = ensure_q4_gguf_model()
if not model_path:
return None
try:
print(f"[GGUF] Loading llama.cpp model: {model_path}")
llama_cpp_model = llama_cpp.Llama(
model_path=model_path,
n_ctx=4096,
n_threads=max(1, os.cpu_count() or 1),
n_gpu_layers=0, # CPU-friendly default; adjust if GPU offload available
verbose=False,
)
print("[GGUF] llama.cpp model loaded")
except Exception as e:
print(f"[GGUF] Failed to load llama.cpp model: {e}")
llama_cpp_model = None
return llama_cpp_model
except Exception as _e:
llama_cpp = None
llama_cpp_model = None
gguf_model_path = None
# LLM model (using an open-access model instead of Llama 4 which requires authentication)
llm_model = None
llm_tokenizer = None
try:
from transformers import AutoModelForCausalLM, AutoTokenizer
print("Loading LLM model... This may take a moment.")
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" # Using TinyLlama as an open-access alternative
llm_tokenizer = AutoTokenizer.from_pretrained(model_name)
llm_model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float16,
use_safetensors=True,
# Removing options that require accelerate package
# device_map="auto",
# load_in_8bit=True
).to(device)
print("LLM model loaded successfully")
except Exception as e:
print(f"Error loading LLM model: {e}")
llm_model = None
llm_tokenizer = None
def process_llm_query(vision_results, user_query):
"""Process a query with the LLM model using vision results and user text"""
if llm_model is None or llm_tokenizer is None:
return {"error": "LLM model not available"}
# ๊ฒฐ๊ณผ ๋ฐ์ดํฐ ์์ฝ (ํ ํฐ ๊ธธ์ด ์ ํ์ ์ํด)
summarized_results = []
# ๊ฐ์ฒด ํ์ง ๊ฒฐ๊ณผ ์์ฝ
if isinstance(vision_results, list):
# ์ต๋ 10๊ฐ ๊ฐ์ฒด๋ง ํฌํจ
for i, obj in enumerate(vision_results[:10]):
if isinstance(obj, dict):
# ํ์ํ ์ ๋ณด๋ง ์ถ์ถ
summary = {
"label": obj.get("label", "unknown"),
"confidence": obj.get("confidence", 0),
}
summarized_results.append(summary)
# Create a prompt combining vision results and user query
prompt = f"""You are an AI assistant analyzing image detection results.
Here are the objects detected in the image: {json.dumps(summarized_results, indent=2)}
User question: {user_query}
Please provide a detailed analysis based on the detected objects and the user's question.
"""
# Tokenize and generate response
try:
start_time = time.time()
# ํ ํฐ ๊ธธ์ด ํ์ธ ๋ฐ ์ ํ
tokens = llm_tokenizer.encode(prompt)
if len(tokens) > 1500: # ์์ ๋ง์ง ์ค์
prompt = f"""You are an AI assistant analyzing image detection results.
The image contains {len(summarized_results)} detected objects.
User question: {user_query}
Please provide a general analysis based on the user's question.
"""
inputs = llm_tokenizer(prompt, return_tensors="pt").to(device)
with torch.no_grad():
output = llm_model.generate(
**inputs,
max_new_tokens=512,
temperature=0.7,
top_p=0.9,
do_sample=True
)
response_text = llm_tokenizer.decode(output[0], skip_special_tokens=True)
# Remove the prompt from the response
if response_text.startswith(prompt):
response_text = response_text[len(prompt):].strip()
inference_time = time.time() - start_time
return {
"response": response_text,
"performance": {
"inference_time": round(inference_time, 3),
"device": "GPU" if torch.cuda.is_available() else "CPU"
}
}
except Exception as e:
return {"error": f"Error processing LLM query: {str(e)}"}
def image_to_base64(img):
"""Convert PIL Image to base64 string"""
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
return img_str
def process_yolo(image):
if yolo_model is None:
return {"error": "YOLOv8 model not loaded"}
# Measure inference time
start_time = time.time()
# Convert to numpy if it's a PIL image
if isinstance(image, Image.Image):
image_np = np.array(image)
else:
image_np = image
# Run inference
results = yolo_model(image_np)
# Process results
result_image = results[0].plot()
result_image = Image.fromarray(result_image)
# Get detection information
boxes = results[0].boxes
class_names = results[0].names
# Format detection results
detections = []
for box in boxes:
class_id = int(box.cls[0].item())
class_name = class_names[class_id]
confidence = round(box.conf[0].item(), 2)
bbox = box.xyxy[0].tolist()
bbox = [round(x) for x in bbox]
detections.append({
"class": class_name,
"confidence": confidence,
"bbox": bbox
})
# Calculate inference time
inference_time = time.time() - start_time
# Add inference time and device info
device_info = "GPU" if torch.cuda.is_available() else "CPU"
return {
"image": image_to_base64(result_image),
"detections": detections,
"performance": {
"inference_time": round(inference_time, 3),
"device": device_info
}
}
def process_detr(image):
if detr_model is None or detr_processor is None:
return {"error": "DETR model not loaded"}
# Measure inference time
start_time = time.time()
# Prepare image for the model
inputs = detr_processor(images=image, return_tensors="pt")
# Run inference
with torch.no_grad():
outputs = detr_model(**inputs)
# Process results
target_sizes = torch.tensor([image.size[::-1]])
results = detr_processor.post_process_object_detection(
outputs, target_sizes=target_sizes, threshold=0.9
)[0]
# Create a copy of the image to draw on
result_image = image.copy()
fig, ax = plt.subplots(1)
ax.imshow(result_image)
# Format detection results
detections = []
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
box = [round(i) for i in box.tolist()]
class_name = detr_model.config.id2label[label.item()]
confidence = round(score.item(), 2)
# Draw rectangle
rect = Rectangle((box[0], box[1]), box[2] - box[0], box[3] - box[1],
linewidth=2, edgecolor='r', facecolor='none')
ax.add_patch(rect)
# Add label
plt.text(box[0], box[1], "{}: {}".format(class_name, confidence),
bbox=dict(facecolor='white', alpha=0.8))
detections.append({
"class": class_name,
"confidence": confidence,
"bbox": box
})
# Save figure to image
buf = io.BytesIO()
plt.tight_layout()
plt.axis('off')
plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0)
buf.seek(0)
result_image = Image.open(buf)
plt.close(fig)
# Calculate inference time
inference_time = time.time() - start_time
# Add inference time and device info
device_info = "GPU" if torch.cuda.is_available() else "CPU"
return {
"image": image_to_base64(result_image),
"detections": detections,
"performance": {
"inference_time": round(inference_time, 3),
"device": device_info
}
}
def process_vit(image):
if vit_model is None or vit_processor is None:
return {"error": "ViT model not loaded"}
# Measure inference time
start_time = time.time()
# Prepare image for the model
inputs = vit_processor(images=image, return_tensors="pt")
# Run inference
with torch.no_grad():
outputs = vit_model(**inputs)
logits = outputs.logits
# Get the predicted class
predicted_class_idx = logits.argmax(-1).item()
prediction = vit_model.config.id2label[predicted_class_idx]
# Get top 5 predictions
probs = torch.nn.functional.softmax(logits, dim=-1)[0]
top5_prob, top5_indices = torch.topk(probs, 5)
results = []
for i, (prob, idx) in enumerate(zip(top5_prob, top5_indices)):
class_name = vit_model.config.id2label[idx.item()]
results.append({
"rank": i+1,
"class": class_name,
"probability": round(prob.item(), 3)
})
# Calculate inference time
inference_time = time.time() - start_time
# Add inference time and device info
device_info = "GPU" if torch.cuda.is_available() else "CPU"
return {
"top_predictions": results,
"performance": {
"inference_time": round(inference_time, 3),
"device": device_info
}
}
@app.route('/api/detect/yolo', methods=['POST'])
@require_auth()
def yolo_detect():
if 'image' not in request.files:
return jsonify({"error": "No image provided"}), 400
file = request.files['image']
image = Image.open(file.stream)
result = process_yolo(image)
return jsonify(result)
# --- HF CausalLM + LoRA helper caches ---
hf_tokenizers = {}
hf_base_models = {}
hf_lora_models = {}
def _preferred_dtype():
try:
return torch.float16 if torch.cuda.is_available() else torch.float32
except Exception:
return torch.float32
def load_hf_base_and_tokenizer(base_id: str, tok_id: str = None):
"""Load and cache base CausalLM and tokenizer. tok_id can point to adapter repo to use its tokenizer."""
global hf_tokenizers, hf_base_models
tok_key = tok_id or base_id
if tok_key not in hf_tokenizers:
hf_tokenizers[tok_key] = AutoTokenizer.from_pretrained(tok_key, use_fast=True)
if base_id not in hf_base_models:
hf_base_models[base_id] = AutoModelForCausalLM.from_pretrained(
base_id,
torch_dtype=_preferred_dtype(),
use_safetensors=True,
).to(device)
return hf_tokenizers[tok_key], hf_base_models[base_id]
def load_hf_lora_model(base_id: str, adapter_id: str):
"""Load and cache a PEFT-wrapped LoRA model from base + adapter. Returns model or raises if PEFT unavailable."""
if PeftModel is None:
raise RuntimeError("PEFT (peft) is not installed; cannot load LoRA adapter")
key = f"{base_id}::{adapter_id}"
if key in hf_lora_models:
return hf_lora_models[key]
# Create a fresh base to avoid mutating the cached base used for non-LoRA runs
base = AutoModelForCausalLM.from_pretrained(
base_id,
torch_dtype=_preferred_dtype(),
use_safetensors=True,
).to(device)
# Prefer safetensors for adapter weights to avoid torch.load vulnerability
try:
lora_model = PeftModel.from_pretrained(base, adapter_id, use_safetensors=True)
except TypeError:
# Older PEFT versions may not support use_safetensors flag
lora_model = PeftModel.from_pretrained(base, adapter_id)
lora_model = lora_model.eval().to(device)
hf_lora_models[key] = lora_model
return lora_model
@app.route('/api/detect/detr', methods=['POST'])
@require_auth()
def detr_detect():
if 'image' not in request.files:
return jsonify({"error": "No image provided"}), 400
file = request.files['image']
image = Image.open(file.stream)
result = process_detr(image)
return jsonify(result)
@app.route('/api/classify/vit', methods=['POST'])
@require_auth()
def vit_classify():
if 'image' not in request.files:
return jsonify({"error": "No image provided"}), 400
file = request.files['image']
image = Image.open(file.stream)
result = process_vit(image)
return jsonify(result)
@app.route('/api/analyze', methods=['POST'])
@require_auth()
def analyze_with_llm():
# Check if required data is in the request
if not request.json:
return jsonify({"error": "No JSON data provided"}), 400
# Extract vision results and user query from request
data = request.json
if 'visionResults' not in data or 'userQuery' not in data:
return jsonify({"error": "Missing required fields: visionResults or userQuery"}), 400
vision_results = data['visionResults']
user_query = data['userQuery']
# Process the query with LLM
result = process_llm_query(vision_results, user_query)
return jsonify(result)
def generate_image_embedding(image):
"""CLIP ๋ชจ๋ธ์ ์ฌ์ฉํ์ฌ ์ด๋ฏธ์ง ์๋ฒ ๋ฉ ์์ฑ"""
if clip_model is None or clip_processor is None:
return None
try:
# ์ด๋ฏธ์ง ์ ์ฒ๋ฆฌ
inputs = clip_processor(images=image, return_tensors="pt")
# ์ด๋ฏธ์ง ์๋ฒ ๋ฉ ์์ฑ
with torch.no_grad():
image_features = clip_model.get_image_features(**inputs)
# ์๋ฒ ๋ฉ ์ ๊ทํ ๋ฐ numpy ๋ฐฐ์ด๋ก ๋ณํ
image_embedding = image_features.squeeze().cpu().numpy()
normalized_embedding = image_embedding / np.linalg.norm(image_embedding)
return normalized_embedding.tolist()
except Exception as e:
print(f"Error generating image embedding: {e}")
return None
@app.route('/api/similar-images', methods=['POST'])
@require_auth()
def find_similar_images():
"""์ ์ฌ ์ด๋ฏธ์ง ๊ฒ์ API"""
if clip_model is None or clip_processor is None or image_collection is None:
return jsonify({"error": "Image embedding model or vector DB not available"})
try:
# ์์ฒญ์์ ์ด๋ฏธ์ง ๋ฐ์ดํฐ ์ถ์ถ
if 'image' not in request.files and 'image' not in request.form:
return jsonify({"error": "No image provided"})
if 'image' in request.files:
# ํ์ผ๋ก ์
๋ก๋๋ ๊ฒฝ์ฐ
image_file = request.files['image']
image = Image.open(image_file).convert('RGB')
else:
# base64๋ก ์ธ์ฝ๋ฉ๋ ๊ฒฝ์ฐ
image_data = request.form['image']
if image_data.startswith('data:image'):
# Remove the data URL prefix if present
image_data = image_data.split(',')[1]
image = Image.open(BytesIO(base64.b64decode(image_data))).convert('RGB')
# ์ด๋ฏธ์ง ID ์์ฑ (์์)
image_id = str(uuid.uuid4())
# ์ด๋ฏธ์ง ์๋ฒ ๋ฉ ์์ฑ
embedding = generate_image_embedding(image)
if embedding is None:
return jsonify({"error": "Failed to generate image embedding"})
# ํ์ฌ ์ด๋ฏธ์ง๋ฅผ DB์ ์ถ๊ฐ (์ ํ์ )
# image_collection.add(
# ids=[image_id],
# embeddings=[embedding]
# )
# ์ ์ฌ ์ด๋ฏธ์ง ๊ฒ์
results = image_collection.query(
query_embeddings=[embedding],
n_results=5 # ์์ 5๊ฐ ๊ฒฐ๊ณผ ๋ฐํ
)
# ๊ฒฐ๊ณผ ํฌ๋งทํ
similar_images = []
if len(results['ids'][0]) > 0:
for i, img_id in enumerate(results['ids'][0]):
similar_images.append({
"id": img_id,
"distance": float(results['distances'][0][i]) if 'distances' in results else 0.0,
"metadata": results['metadatas'][0][i] if 'metadatas' in results else {}
})
return jsonify({
"query_image_id": image_id,
"similar_images": similar_images
})
except Exception as e:
print(f"Error in similar-images API: {e}")
return jsonify({"error": str(e)}), 500
@app.route('/api/add-to-collection', methods=['POST'])
@require_auth()
def add_to_collection():
"""์ด๋ฏธ์ง๋ฅผ ๋ฒกํฐ DB์ ์ถ๊ฐํ๋ API"""
if clip_model is None or clip_processor is None or image_collection is None:
return jsonify({"error": "Image embedding model or vector DB not available"})
try:
# ์์ฒญ์์ ์ด๋ฏธ์ง ๋ฐ์ดํฐ ์ถ์ถ
if 'image' not in request.files and 'image' not in request.form:
return jsonify({"error": "No image provided"})
# ๋ฉํ๋ฐ์ดํฐ ์ถ์ถ
metadata = {}
if 'metadata' in request.form:
metadata = json.loads(request.form['metadata'])
# ์ด๋ฏธ์ง ID (์ ๊ณต๋์ง ์์ ๊ฒฝ์ฐ ์๋ ์์ฑ)
image_id = request.form.get('id', str(uuid.uuid4()))
if 'image' in request.files:
# ํ์ผ๋ก ์
๋ก๋๋ ๊ฒฝ์ฐ
image_file = request.files['image']
image = Image.open(image_file).convert('RGB')
else:
# base64๋ก ์ธ์ฝ๋ฉ๋ ๊ฒฝ์ฐ
image_data = request.form['image']
if image_data.startswith('data:image'):
# Remove the data URL prefix if present
image_data = image_data.split(',')[1]
image = Image.open(BytesIO(base64.b64decode(image_data))).convert('RGB')
# ์ด๋ฏธ์ง ์๋ฒ ๋ฉ ์์ฑ
embedding = generate_image_embedding(image)
if embedding is None:
return jsonify({"error": "Failed to generate image embedding"})
# ์ด๋ฏธ์ง ๋ฐ์ดํฐ๋ฅผ base64๋ก ์ธ์ฝ๋ฉํ์ฌ ๋ฉํ๋ฐ์ดํฐ์ ์ถ๊ฐ
buffered = BytesIO()
image.save(buffered, format="JPEG")
img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
metadata['image_data'] = img_str
# ์ด๋ฏธ์ง๋ฅผ DB์ ์ถ๊ฐ
image_collection.add(
ids=[image_id],
embeddings=[embedding],
metadatas=[metadata]
)
return jsonify({
"success": True,
"image_id": image_id,
"message": "Image added to collection"
})
except Exception as e:
print(f"Error in add-to-collection API: {e}")
return jsonify({"error": str(e)}), 500
@app.route('/api/add-detected-objects', methods=['POST'])
@require_auth()
def add_detected_objects():
"""๊ฐ์ฒด ์ธ์ ๊ฒฐ๊ณผ๋ฅผ ๋ฒกํฐ DB์ ์ถ๊ฐํ๋ API"""
if clip_model is None or object_collection is None:
return jsonify({"error": "Image embedding model or vector DB not available"})
try:
# ๋๋ฒ๊น
: ์์ฒญ ๋ฐ์ดํฐ ๋ก๊น
print("[DEBUG] Received request in add-detected-objects")
# ์์ฒญ์์ ์ด๋ฏธ์ง์ ๊ฐ์ฒด ๊ฒ์ถ ๊ฒฐ๊ณผ ๋ฐ์ดํฐ ์ถ์ถ
data = request.json
print(f"[DEBUG] Request data keys: {list(data.keys()) if data else 'None'}")
if not data:
print("[DEBUG] Error: No data received in request")
return jsonify({"error": "No data received"})
if 'image' not in data:
print("[DEBUG] Error: 'image' key not found in request data")
return jsonify({"error": "Missing image data"})
if 'objects' not in data:
print("[DEBUG] Error: 'objects' key not found in request data")
return jsonify({"error": "Missing objects data"})
# ์ด๋ฏธ์ง ๋ฐ์ดํฐ ๋๋ฒ๊น
print(f"[DEBUG] Image data type: {type(data['image'])}")
print(f"[DEBUG] Image data starts with: {data['image'][:50]}...") # ์ฒ์ 50์๋ง ์ถ๋ ฅ
# ๊ฐ์ฒด ๋ฐ์ดํฐ ๋๋ฒ๊น
print(f"[DEBUG] Objects data type: {type(data['objects'])}")
print(f"[DEBUG] Objects count: {len(data['objects']) if isinstance(data['objects'], list) else 'Not a list'}")
if isinstance(data['objects'], list) and len(data['objects']) > 0:
print(f"[DEBUG] First object keys: {list(data['objects'][0].keys()) if isinstance(data['objects'][0], dict) else 'Not a dict'}")
# ์ด๋ฏธ์ง ๋ฐ์ดํฐ ์ฒ๋ฆฌ
image_data = data['image']
if image_data.startswith('data:image'):
image_data = image_data.split(',')[1]
image = Image.open(BytesIO(base64.b64decode(image_data))).convert('RGB')
image_width, image_height = image.size
# ์ด๋ฏธ์ง ID
image_id = data.get('imageId', str(uuid.uuid4()))
# ๊ฐ์ฒด ๋ฐ์ดํฐ ์ฒ๋ฆฌ
objects = data['objects']
object_ids = []
object_embeddings = []
object_metadatas = []
for obj in objects:
# ๊ฐ์ฒด ID ์์ฑ
object_id = f"{image_id}_{str(uuid.uuid4())[:8]}"
# ๋ฐ์ด๋ฉ ๋ฐ์ค ์ ๋ณด ์ถ์ถ
bbox = obj.get('bbox', [])
# ๋ฆฌ์คํธ ํํ์ bbox [x1, y1, x2, y2] ์ฒ๋ฆฌ
if isinstance(bbox, list) and len(bbox) >= 4:
x1 = bbox[0] / image_width # ์ ๊ทํ๋ ์ขํ๋ก ๋ณํ
y1 = bbox[1] / image_height
x2 = bbox[2] / image_width
y2 = bbox[3] / image_height
width = x2 - x1
height = y2 - y1
# ๋์
๋๋ฆฌ ํํ์ bbox {'x': x, 'y': y, 'width': width, 'height': height} ์ฒ๋ฆฌ
elif isinstance(bbox, dict):
x1 = bbox.get('x', 0)
y1 = bbox.get('y', 0)
width = bbox.get('width', 0)
height = bbox.get('height', 0)
else:
# ๊ธฐ๋ณธ๊ฐ ์ค์
x1, y1, width, height = 0, 0, 0, 0
# ๋ฐ์ด๋ฉ ๋ฐ์ค๋ฅผ ์ด๋ฏธ์ง ์ขํ๋ก ๋ณํ
x1_px = int(x1 * image_width)
y1_px = int(y1 * image_height)
width_px = int(width * image_width)
height_px = int(height * image_height)
# ๊ฐ์ฒด ์ด๋ฏธ์ง ์๋ฅด๊ธฐ
try:
object_image = image.crop((x1_px, y1_px, x1_px + width_px, y1_px + height_px))
# ์๋ฒ ๋ฉ ์์ฑ
embedding = generate_image_embedding(object_image)
if embedding is None:
continue
# ๋ฉํ๋ฐ์ดํฐ ๊ตฌ์ฑ
# bbox๋ฅผ JSON ๋ฌธ์์ด๋ก ์ง๋ ฌํํ์ฌ ChromaDB ๋ฉํ๋ฐ์ดํฐ ์ ํ ์ฐํ
bbox_json = json.dumps({
"x": x1,
"y": y1,
"width": width,
"height": height
})
# ๊ฐ์ฒด ์ด๋ฏธ์ง๋ฅผ base64๋ก ์ธ์ฝ๋ฉ
buffered = BytesIO()
object_image.save(buffered, format="JPEG")
img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
metadata = {
"image_id": image_id,
"class": obj.get('class', ''),
"confidence": obj.get('confidence', 0),
"bbox": bbox_json, # JSON ๋ฌธ์์ด๋ก ์ ์ฅ
"image_data": img_str # ์ด๋ฏธ์ง ๋ฐ์ดํฐ ์ถ๊ฐ
}
object_ids.append(object_id)
object_embeddings.append(embedding)
object_metadatas.append(metadata)
except Exception as e:
print(f"Error processing object: {e}")
continue
# Add to vector DB
if object_ids and object_embeddings and object_metadatas:
object_collection.add(
ids=object_ids,
embeddings=object_embeddings,
metadatas=object_metadatas
)
return jsonify({
"success": True,
"message": f"Added {len(object_ids)} objects to collection",
"object_ids": object_ids
})
else:
return jsonify({
"warning": "No valid objects to add"
})
except Exception as e:
print(f"Error in add-detected-objects API: {e}")
return jsonify({"error": str(e)}), 500
# Product Comparison API Endpoints
@app.route('/api/product/compare/start', methods=['POST'])
@require_auth()
def start_product_comparison():
"""Start a new product comparison session"""
print(f"[DEBUG] ๐ start_product_comparison endpoint called")
print(f"[DEBUG] ๐ get_product_comparison_coordinator: {get_product_comparison_coordinator}")
if get_product_comparison_coordinator is None:
print(f"[DEBUG] โ Product comparison coordinator is None - returning 500")
# Try to import again and show the error
print(f"[DEBUG] ๐ Attempting emergency import test...")
try:
from product_comparison import get_product_comparison_coordinator as test_coordinator
print(f"[DEBUG] ๐ฏ Emergency import succeeded: {test_coordinator}")
except Exception as e:
print(f"[DEBUG] โ Emergency import failed: {e}")
import traceback
traceback.print_exc()
return jsonify({"error": "Product comparison module not available"}), 500
try:
print(f"[DEBUG] ๐ Processing request data...")
# Generate session ID if provided in form or query params, otherwise create new one
session_id = request.form.get('session_id') or request.args.get('session_id') or str(uuid.uuid4())
print(f"[DEBUG] ๐ Session ID: {session_id}")
# Get analysis type if provided (info, compare, value, recommend)
analysis_type = request.form.get('analysisType') or request.args.get('analysisType', 'info')
print(f"[DEBUG] ๐ Analysis type: {analysis_type}")
# Process images from FormData or JSON
images = []
print(f"[DEBUG] ๐ผ๏ธ Processing images...")
print(f"[DEBUG] ๐ Request files: {list(request.files.keys())}")
print(f"[DEBUG] ๐ Request form: {dict(request.form)}")
# Check if request is multipart form data
if request.files:
print(f"[DEBUG] ๐ Processing multipart form data...")
# Handle FormData with file uploads (from frontend)
if 'image1' in request.files and request.files['image1']:
img1 = request.files['image1']
print(f"[DEBUG] ๐ผ๏ธ Processing image1: {img1.filename}")
try:
# Load image and convert to RGB to ensure it's fully loaded in memory
image = Image.open(img1.stream).convert('RGB')
images.append(image)
print(f"[DEBUG] โ
Image1 processed successfully")
except Exception as e:
print(f"[DEBUG] โ Error processing image1: {e}")
if 'image2' in request.files and request.files['image2']:
img2 = request.files['image2']
print(f"[DEBUG] ๐ผ๏ธ Processing image2: {img2.filename}")
try:
# Load image and convert to RGB to ensure it's fully loaded in memory
image = Image.open(img2.stream).convert('RGB')
images.append(image)
print(f"[DEBUG] โ
Image2 processed successfully")
except Exception as e:
print(f"[DEBUG] โ Error processing image2: {e}")
# Fallback to JSON with base64 images (for API testing)
elif request.json and 'images' in request.json:
print(f"[DEBUG] ๐ Processing JSON with base64 images...")
image_data_list = request.json.get('images', [])
for i, image_data in enumerate(image_data_list):
print(f"[DEBUG] ๐ผ๏ธ Processing base64 image {i+1}")
img = decode_base64_image(image_data)
if img is not None:
images.append(img)
print(f"[DEBUG] โ
Base64 image {i+1} processed successfully")
else:
print(f"[DEBUG] โ Failed to decode base64 image {i+1}")
print(f"[DEBUG] ๐ Total images processed: {len(images)}")
if not images:
print(f"[DEBUG] โ No valid images provided - returning 400")
return jsonify({"error": "No valid images provided"}), 400
# Get coordinator instance
print(f"[DEBUG] ๐ฏ Getting coordinator instance...")
coordinator = get_product_comparison_coordinator()
print(f"[DEBUG] โ
Coordinator obtained: {type(coordinator).__name__}")
# Pass the analysis type and session metadata to the coordinator
session_metadata = {
'analysis_type': analysis_type,
'timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
}
print(f"[DEBUG] ๐ Session metadata: {session_metadata}")
# Start processing in a background thread
print(f"[DEBUG] ๐งต Starting background processing thread...")
def run_async_task(loop):
try:
print(f"[DEBUG] ๐ Setting event loop and starting coordinator.process_images...")
asyncio.set_event_loop(loop)
loop.run_until_complete(coordinator.process_images(session_id, images, session_metadata))
print(f"[DEBUG] โ
coordinator.process_images completed successfully")
except Exception as e:
print(f"[DEBUG] โ Error in async task: {e}")
import traceback
traceback.print_exc()
loop = asyncio.new_event_loop()
thread = Thread(target=run_async_task, args=(loop,))
thread.daemon = True
thread.start()
print(f"[DEBUG] ๐ Background thread started")
# Return session ID for client to use with streaming endpoint
response_data = {
"session_id": session_id,
"message": "Product comparison started",
"status": "processing"
}
print(f"[DEBUG] โ
Returning success response: {response_data}")
return jsonify(response_data)
except Exception as e:
print(f"[DEBUG] โ Exception in start_product_comparison: {e}")
print(f"[DEBUG] โ Exception type: {type(e).__name__}")
import traceback
print(f"[DEBUG] โ Full traceback:")
traceback.print_exc()
return jsonify({"error": str(e)}), 500
@app.route('/api/product/compare/stream/Vision LLM Agent
if '' in html: html = html.replace('', auth_script + '\n') else: html += auth_script response = make_response(html) response.headers['Content-Type'] = 'text/html; charset=utf-8' # Set cookies in response headers with maximum compatibility response.set_cookie('auth_user_id', str(user.id), max_age=7200, # 2 hours secure=False, # Force insecure for HF Spaces httponly=False, # Allow JavaScript access samesite=None, # Most permissive path='/') # Ensure path is set response.set_cookie('auth_username', username, max_age=7200, # 2 hours secure=False, # Force insecure for HF Spaces httponly=False, # Allow JavaScript access samesite=None, # Most permissive path='/') # Ensure path is set print(f"[DEBUG] Set cookies: auth_user_id={user.id}, auth_username={username}") print(f"[DEBUG] Cookie settings: secure=False, httponly=False, samesite=None, path=/") response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate' response.headers['Pragma'] = 'no-cache' response.headers['Expires'] = '0' return response else: error = 'Invalid username or password' print(f"Login failed: {error}") return render_template_string(LOGIN_TEMPLATE, error=error) @app.route('/logout') def logout(): # Clear server-side session logout_user() session.clear() # Return a small HTML that clears client-side localStorage and expires cookies, then redirects html = """