Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
accounts and admin
Murtaza Nasir8547f2389671
diff --git a/app.py b/app.pyindex e8f17f61..65d593dd 100644--- a/app.py+++ b/app.py@@ -1,7 +1,7 @@# Speakr - Audio Transcription and Summarization Appimport osimport sys-from flask import Flask, render_template, request, jsonify, send_file, Markup+from flask import Flask, render_template, request, jsonify, send_file, Markup, redirect, url_for, flashfrom flask_sqlalchemy import SQLAlchemyfrom datetime import datetimefrom openai import OpenAI # Keep using the OpenAI library@@ -14,10 +14,18 @@ from dotenv import load_dotenv # Import load_dotenvimport httpximport reimport markdown+from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user+from flask_bcrypt import Bcrypt+from flask_wtf import FlaskForm+from wtforms import StringField, PasswordField, SubmitField, BooleanField+from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError# Load environment variables from .env fileload_dotenv()+# Initialize Flask-Bcrypt+bcrypt = Bcrypt()+# Helper function to convert markdown to HTMLdef md_to_html(text):if not text:@@ -38,17 +46,48 @@ app = Flask(__name__)app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////opt/transcription-app/instance/transcriptions.db'app.config['UPLOAD_FOLDER'] = '/opt/transcription-app/uploads' # Use absolute path based on setupapp.config['MAX_CONTENT_LENGTH'] = 250 * 1024 * 1024 # 250MB max file size+# Set a secret key for session management and CSRF protection+app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'default-dev-key-change-in-production')db = SQLAlchemy()db.init_app(app)+# Initialize Flask-Login+login_manager = LoginManager()+login_manager.init_app(app)+login_manager.login_view = 'login'+login_manager.login_message_category = 'info'+bcrypt.init_app(app)++# Add context processor to make 'now' available to all templates[email protected]_processor+def inject_now():+ return {'now': datetime.now()}+# Ensure upload and instance directories existos.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)# Assuming the instance folder is handled correctly by Flask or created by setup.sh# os.makedirs(os.path.dirname(app.config['SQLALCHEMY_DATABASE_URI'].replace('sqlite:///', '/')), exist_ok=True)+# --- User loader for Flask-Login ---+@login_manager.user_loader+def load_user(user_id):+ return db.session.get(User, int(user_id))+# --- Database Models ---+class User(db.Model, UserMixin):+ id = db.Column(db.Integer, primary_key=True)+ username = db.Column(db.String(20), unique=True, nullable=False)+ email = db.Column(db.String(120), unique=True, nullable=False)+ password = db.Column(db.String(60), nullable=False)+ is_admin = db.Column(db.Boolean, default=False)+ recordings = db.relationship('Recording', backref='owner', lazy=True)++ def __repr__(self):+ return f"User('{self.username}', '{self.email}')"class Recording(db.Model):+ # Add user_id foreign key to associate recordings with users+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)id = db.Column(db.Integer, primary_key=True)# Title will now often be AI-generated, maybe start with filename?title = db.Column(db.String(200), nullable=True) # Allow Null initially@@ -75,9 +114,34 @@ class Recording(db.Model):'status': self.status,'created_at': self.created_at.isoformat() if self.created_at else None,'meeting_date': self.meeting_date.isoformat() if self.meeting_date else None, # <-- ADDED: Include meeting_date- 'file_size': self.file_size+ 'file_size': self.file_size,+ 'user_id': self.user_id}+# --- Forms for Authentication ---+class RegistrationForm(FlaskForm):+ username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])+ email = StringField('Email', validators=[DataRequired(), Email()])+ password = PasswordField('Password', validators=[DataRequired(), Length(min=8)])+ confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])+ submit = SubmitField('Sign Up')++ def validate_username(self, username):+ user = User.query.filter_by(username=username.data).first()+ if user:+ raise ValidationError('That username is already taken. Please choose a different one.')++ def validate_email(self, email):+ user = User.query.filter_by(email=email.data).first()+ if user:+ raise ValidationError('That email is already registered. Please use a different one.')++class LoginForm(FlaskForm):+ email = StringField('Email', validators=[DataRequired(), Email()])+ password = PasswordField('Password', validators=[DataRequired()])+ remember = BooleanField('Remember Me')+ submit = SubmitField('Login')+with app.app_context():db.create_all()@@ -260,6 +324,7 @@ JSON Response:""" # The prompt guides the model towards the desired output# --- Chat with Transcription ---@app.route('/chat', methods=['POST'])+@login_requireddef chat_with_transcription():try:data = request.json@@ -280,6 +345,10 @@ def chat_with_transcription():if not recording:return jsonify({'error': 'Recording not found'}), 404+ # Check if the recording belongs to the current user+ if recording.user_id and recording.user_id != current_user.id:+ return jsonify({'error': 'You do not have permission to chat with this recording'}), 403+# Check if OpenRouter client is availableif client is None:return jsonify({'error': 'Chat service is not available (OpenRouter client not configured)'}), 503@@ -338,15 +407,299 @@ Additional context and notes about the meeting:return jsonify({'error': str(e)}), 500+# --- Authentication Routes ---[email protected]('/register', methods=['GET', 'POST'])+def register():+ if current_user.is_authenticated:+ return redirect(url_for('index'))++ form = RegistrationForm()+ if form.validate_on_submit():+ hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')+ user = User(username=form.username.data, email=form.email.data, password=hashed_password)+ db.session.add(user)+ db.session.commit()+ flash('Your account has been created! You can now log in.', 'success')+ return redirect(url_for('login'))++ return render_template('register.html', title='Register', form=form)+[email protected]('/login', methods=['GET', 'POST'])+def login():+ if current_user.is_authenticated:+ return redirect(url_for('index'))++ form = LoginForm()+ if form.validate_on_submit():+ user = User.query.filter_by(email=form.email.data).first()+ if user and bcrypt.check_password_hash(user.password, form.password.data):+ login_user(user, remember=form.remember.data)+ next_page = request.args.get('next')+ return redirect(next_page) if next_page else redirect(url_for('index'))+ else:+ flash('Login unsuccessful. Please check email and password.', 'danger')++ return render_template('login.html', title='Login', form=form)+[email protected]('/logout')+def logout():+ logout_user()+ return redirect(url_for('index'))+[email protected]('/account', methods=['GET'])+@login_required+def account():+ return render_template('account.html', title='Account')++# --- Admin Routes ---[email protected]('/admin', methods=['GET'])+@login_required+def admin():+ # Check if user is admin+ if not current_user.is_admin:+ flash('You do not have permission to access the admin page.', 'danger')+ return redirect(url_for('index'))+ return render_template('admin.html', title='Admin Dashboard')+[email protected]('/admin/users', methods=['GET'])+@login_required+def admin_get_users():+ # Check if user is admin+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ users = User.query.all()+ user_data = []++ for user in users:+ # Get recordings count and storage used+ recordings_count = len(user.recordings)+ storage_used = sum(r.file_size for r in user.recordings if r.file_size) or 0++ user_data.append({+ 'id': user.id,+ 'username': user.username,+ 'email': user.email,+ 'is_admin': user.is_admin,+ 'recordings_count': recordings_count,+ 'storage_used': storage_used+ })++ return jsonify(user_data)+[email protected]('/admin/users', methods=['POST'])+@login_required+def admin_add_user():+ # Check if user is admin+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ data = request.json+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ # Validate required fields+ required_fields = ['username', 'email', 'password']+ for field in required_fields:+ if field not in data:+ return jsonify({'error': f'Missing required field: {field}'}), 400++ # Check if username or email already exists+ if User.query.filter_by(username=data['username']).first():+ return jsonify({'error': 'Username already exists'}), 400++ if User.query.filter_by(email=data['email']).first():+ return jsonify({'error': 'Email already exists'}), 400++ # Create new user+ hashed_password = bcrypt.generate_password_hash(data['password']).decode('utf-8')+ new_user = User(+ username=data['username'],+ email=data['email'],+ password=hashed_password,+ is_admin=data.get('is_admin', False)+ )++ db.session.add(new_user)+ db.session.commit()++ return jsonify({+ 'id': new_user.id,+ 'username': new_user.username,+ 'email': new_user.email,+ 'is_admin': new_user.is_admin,+ 'recordings_count': 0,+ 'storage_used': 0+ }), 201+[email protected]('/admin/users/<int:user_id>', methods=['PUT'])+@login_required+def admin_update_user(user_id):+ # Check if user is admin+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ user = db.session.get(User, user_id)+ if not user:+ return jsonify({'error': 'User not found'}), 404++ data = request.json+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ # Update user fields+ if 'username' in data and data['username'] != user.username:+ # Check if username already exists+ if User.query.filter_by(username=data['username']).first():+ return jsonify({'error': 'Username already exists'}), 400+ user.username = data['username']++ if 'email' in data and data['email'] != user.email:+ # Check if email already exists+ if User.query.filter_by(email=data['email']).first():+ return jsonify({'error': 'Email already exists'}), 400+ user.email = data['email']++ if 'password' in data and data['password']:+ user.password = bcrypt.generate_password_hash(data['password']).decode('utf-8')++ if 'is_admin' in data:+ user.is_admin = data['is_admin']++ db.session.commit()++ # Get recordings count and storage used+ recordings_count = len(user.recordings)+ storage_used = sum(r.file_size for r in user.recordings if r.file_size) or 0++ return jsonify({+ 'id': user.id,+ 'username': user.username,+ 'email': user.email,+ 'is_admin': user.is_admin,+ 'recordings_count': recordings_count,+ 'storage_used': storage_used+ })+[email protected]('/admin/users/<int:user_id>', methods=['DELETE'])+@login_required+def admin_delete_user(user_id):+ # Check if user is admin+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ # Prevent deleting self+ if user_id == current_user.id:+ return jsonify({'error': 'Cannot delete your own account'}), 400++ user = db.session.get(User, user_id)+ if not user:+ return jsonify({'error': 'User not found'}), 404++ # Delete user's recordings and audio files+ for recording in user.recordings:+ try:+ if recording.audio_path and os.path.exists(recording.audio_path):+ os.remove(recording.audio_path)+ except Exception as e:+ app.logger.error(f"Error deleting audio file {recording.audio_path}: {e}")++ # Delete user+ db.session.delete(user)+ db.session.commit()++ return jsonify({'success': True})+[email protected]('/admin/users/<int:user_id>/toggle-admin', methods=['POST'])+@login_required+def admin_toggle_admin(user_id):+ # Check if user is admin+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ # Prevent changing own admin status+ if user_id == current_user.id:+ return jsonify({'error': 'Cannot change your own admin status'}), 400++ user = db.session.get(User, user_id)+ if not user:+ return jsonify({'error': 'User not found'}), 404++ # Toggle admin status+ user.is_admin = not user.is_admin+ db.session.commit()++ return jsonify({'success': True, 'is_admin': user.is_admin})+[email protected]('/admin/stats', methods=['GET'])+@login_required+def admin_get_stats():+ # Check if user is admin+ if not current_user.is_admin:+ return jsonify({'error': 'Unauthorized'}), 403++ # Get total users+ total_users = User.query.count()++ # Get total recordings+ total_recordings = Recording.query.count()++ # Get recordings by status+ completed_recordings = Recording.query.filter_by(status='COMPLETED').count()+ processing_recordings = Recording.query.filter(Recording.status.in_(['PROCESSING', 'SUMMARIZING'])).count()+ pending_recordings = Recording.query.filter_by(status='PENDING').count()+ failed_recordings = Recording.query.filter_by(status='FAILED').count()++ # Get total storage used+ total_storage = db.session.query(db.func.sum(Recording.file_size)).scalar() or 0++ # Get top users by storage+ top_users_query = db.session.query(+ User.id,+ User.username,+ db.func.count(Recording.id).label('recordings_count'),+ db.func.sum(Recording.file_size).label('storage_used')+ ).join(Recording, User.id == Recording.user_id, isouter=True) \+ .group_by(User.id) \+ .order_by(db.func.sum(Recording.file_size).desc()) \+ .limit(5)++ top_users = []+ for user_id, username, recordings_count, storage_used in top_users_query:+ top_users.append({+ 'id': user_id,+ 'username': username,+ 'recordings_count': recordings_count or 0,+ 'storage_used': storage_used or 0+ })++ # Get total queries (chat requests)+ # This is a placeholder - you would need to track this in your database+ total_queries = 0++ return jsonify({+ 'total_users': total_users,+ 'total_recordings': total_recordings,+ 'completed_recordings': completed_recordings,+ 'processing_recordings': processing_recordings,+ 'pending_recordings': pending_recordings,+ 'failed_recordings': failed_recordings,+ 'total_storage': total_storage,+ 'top_users': top_users,+ 'total_queries': total_queries+ })+# --- Flask Routes ---@app.route('/')def index():return render_template('index.html')@app.route('/recordings', methods=['GET'])+@login_requireddef get_recordings():try:- stmt = select(Recording).order_by(Recording.created_at.desc())+ # Filter recordings by the current user+ stmt = select(Recording).where(Recording.user_id == current_user.id).order_by(Recording.created_at.desc())recordings = db.session.execute(stmt).scalars().all()return jsonify([recording.to_dict() for recording in recordings])except Exception as e:@@ -354,6 +707,7 @@ def get_recordings():return jsonify({'error': str(e)}), 500@app.route('/save', methods=['POST'])+@login_requireddef save_metadata():try:data = request.json@@ -363,6 +717,10 @@ def save_metadata():recording = db.session.get(Recording, recording_id)if not recording: return jsonify({'error': 'Recording not found'}), 404++ # Check if the recording belongs to the current user+ if recording.user_id and recording.user_id != current_user.id:+ return jsonify({'error': 'You do not have permission to edit this recording'}), 403# Update fields if providedif 'title' in data: recording.title = data['title']@@ -393,6 +751,7 @@ def save_metadata():@app.route('/upload', methods=['POST'])+@login_requireddef upload_file():try:if 'file' not in request.files:@@ -425,7 +784,8 @@ def upload_file():title=f"Recording - {filename}",file_size=file_size,status='PENDING', # Explicitly set status- meeting_date=datetime.utcnow().date() # <-- ADDED: Default meeting_date to today+ meeting_date=datetime.utcnow().date(), # <-- ADDED: Default meeting_date to today+ user_id=current_user.id # Associate with the current user)db.session.add(recording)db.session.commit()@@ -456,26 +816,37 @@ def upload_file():return jsonify({'error': str(e)}), 500-# Status Endpoint (no changes needed, it returns the full recording dict)+# Status Endpoint@app.route('/status/<int:recording_id>', methods=['GET'])+@login_requireddef get_status(recording_id):"""Endpoint to check the transcription/summarization status."""try:recording = db.session.get(Recording, recording_id)if not recording:return jsonify({'error': 'Recording not found'}), 404++ # Check if the recording belongs to the current user+ if recording.user_id and recording.user_id != current_user.id:+ return jsonify({'error': 'You do not have permission to view this recording'}), 403+return jsonify(recording.to_dict())except Exception as e:app.logger.error(f"Error fetching status for recording {recording_id}: {e}")return jsonify({'error': str(e)}), 500-# Get Audio Endpoint (no changes needed)+# Get Audio Endpoint@app.route('/audio/<int:recording_id>')+@login_requireddef get_audio(recording_id):try:recording = db.session.get(Recording, recording_id)if not recording or not recording.audio_path:return jsonify({'error': 'Recording or audio file not found'}), 404++ # Check if the recording belongs to the current user+ if recording.user_id and recording.user_id != current_user.id:+ return jsonify({'error': 'You do not have permission to access this audio file'}), 403if not os.path.exists(recording.audio_path):app.logger.error(f"Audio file missing from server: {recording.audio_path}")return jsonify({'error': 'Audio file missing from server'}), 404@@ -484,13 +855,18 @@ def get_audio(recording_id):app.logger.error(f"Error serving audio for recording {recording_id}: {e}")return jsonify({'error': str(e)}), 500-# Delete Recording Endpoint (no changes needed functionally)+# Delete Recording Endpoint@app.route('/recording/<int:recording_id>', methods=['DELETE'])+@login_requireddef delete_recording(recording_id):try:recording = db.session.get(Recording, recording_id)if not recording:return jsonify({'error': 'Recording not found'}), 404++ # Check if the recording belongs to the current user+ if recording.user_id and recording.user_id != current_user.id:+ return jsonify({'error': 'You do not have permission to delete this recording'}), 403# Delete the audio file firsttry:diff --git a/app.py.bak b/app.py.baknew file mode 100644index 00000000..e8f17f61--- /dev/null+++ b/app.py.bak@@ -0,0 +1,519 @@+# Speakr - Audio Transcription and Summarization App+import os+import sys+from flask import Flask, render_template, request, jsonify, send_file, Markup+from flask_sqlalchemy import SQLAlchemy+from datetime import datetime+from openai import OpenAI # Keep using the OpenAI library+import json+from werkzeug.utils import secure_filename+from werkzeug.exceptions import RequestEntityTooLarge+from sqlalchemy import select+import threading+from dotenv import load_dotenv # Import load_dotenv+import httpx+import re+import markdown++# Load environment variables from .env file+load_dotenv()++# Helper function to convert markdown to HTML+def md_to_html(text):+ if not text:+ return ""+ # Convert markdown to HTML with extensions for tables, code highlighting, etc.+ html = markdown.markdown(text, extensions=[+ 'tables', # Support for tables+ 'fenced_code', # Support for ```code blocks```+ 'codehilite', # Syntax highlighting for code blocks+ 'nl2br', # Convert newlines to <br> tags+ 'sane_lists', # Better list handling+ 'smarty' # Smart quotes, dashes, etc.+ ])+ return html++app = Flask(__name__)+# Ensure the path uses the directory structure from your setup script+app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////opt/transcription-app/instance/transcriptions.db'+app.config['UPLOAD_FOLDER'] = '/opt/transcription-app/uploads' # Use absolute path based on setup+app.config['MAX_CONTENT_LENGTH'] = 250 * 1024 * 1024 # 250MB max file size+db = SQLAlchemy()+db.init_app(app)++# Ensure upload and instance directories exist+os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)+# Assuming the instance folder is handled correctly by Flask or created by setup.sh+# os.makedirs(os.path.dirname(app.config['SQLALCHEMY_DATABASE_URI'].replace('sqlite:///', '/')), exist_ok=True)+++# --- Database Models ---+class Recording(db.Model):+ id = db.Column(db.Integer, primary_key=True)+ # Title will now often be AI-generated, maybe start with filename?+ title = db.Column(db.String(200), nullable=True) # Allow Null initially+ participants = db.Column(db.String(500))+ notes = db.Column(db.Text)+ transcription = db.Column(db.Text, nullable=True)+ summary = db.Column(db.Text, nullable=True) # <-- ADDED: Summary field+ status = db.Column(db.String(50), default='PENDING') # PENDING, PROCESSING, SUMMARIZING, COMPLETED, FAILED+ audio_path = db.Column(db.String(500))+ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ meeting_date = db.Column(db.Date, nullable=True) # <-- ADDED: Meeting Date field+ file_size = db.Column(db.Integer) # Store file size in bytes++ def to_dict(self):+ return {+ 'id': self.id,+ 'title': self.title,+ 'participants': self.participants,+ 'notes': self.notes,+ 'notes_html': md_to_html(self.notes) if self.notes else "",+ 'transcription': self.transcription,+ 'summary': self.summary,+ 'summary_html': md_to_html(self.summary) if self.summary else "",+ 'status': self.status,+ 'created_at': self.created_at.isoformat() if self.created_at else None,+ 'meeting_date': self.meeting_date.isoformat() if self.meeting_date else None, # <-- ADDED: Include meeting_date+ 'file_size': self.file_size+ }++with app.app_context():+ db.create_all()++# --- API client setup for OpenRouter ---+# Use environment variables from .env+openrouter_api_key = os.environ.get("OPENROUTER_API_KEY")+openrouter_base_url = os.environ.get("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1")+openrouter_model_name = os.environ.get("OPENROUTER_MODEL_NAME", "openai/gpt-3.5-turbo") # Default if not set++http_client_no_proxy = httpx.Client(verify=True) # verify=True is default, but good to be explicit++if not openrouter_api_key:+ app.logger.warning("OPENROUTER_API_KEY not found. Title/Summary generation DISABLED.")+else:+ try:+ # ---> Pass the custom httpx_client <---+ client = OpenAI(+ api_key=openrouter_api_key,+ base_url=openrouter_base_url,+ http_client=http_client_no_proxy # Pass the proxy-disabled client+ )+ app.logger.info(f"OpenRouter client initialized. Using model: {openrouter_model_name}")+ except Exception as client_init_e:+ app.logger.error(f"Failed to initialize OpenRouter client: {client_init_e}", exc_info=True)++# Store details for the transcription client (potentially different)+transcription_api_key = os.environ.get("OPENAI_API_KEY", "cant-be-empty")+transcription_base_url = os.environ.get("OPENAI_BASE_URL", "http://192.168.68.85:1611/v1/")++app.logger.info(f"Using OpenRouter model for summaries: {openrouter_model_name}")++# --- Background Transcription & Summarization Task ---+def transcribe_audio_task(app_context, recording_id, filepath, original_filename):+ """Runs the transcription and summarization in a background thread."""+ with app_context: # Need app context for db operations in thread+ recording = db.session.get(Recording, recording_id)+ if not recording:+ app.logger.error(f"Error: Recording {recording_id} not found for transcription.")+ return++ try:+ app.logger.info(f"Starting transcription for recording {recording_id} ({original_filename})...")+ recording.status = 'PROCESSING'+ db.session.commit()++ # --- Step 1: Transcription ---+ with open(filepath, 'rb') as audio_file:+ # NOTE: This still uses the hardcoded Whisper model.+ # If you want OpenRouter for transcription too, change the model here+ # and potentially adjust the API call if needed.+ # For now, assuming Whisper via a local compatible endpoint.+ # You might need a *separate* client for Whisper if it's at a different URL.+ # Example using the configured client (assuming it points to Whisper or OpenRouter handles it):+ transcription_client = OpenAI(+ api_key=transcription_api_key,+ base_url=transcription_base_url,+ http_client=http_client_no_proxy # Reuse the same client configuration+ )+ transcript = transcription_client.audio.transcriptions.create(+ model="Systran/faster-distil-whisper-large-v3", # Your Whisper model+ file=audio_file,+ language="en" # Specify language if known+ )+ recording.transcription = transcript.text+ app.logger.info(f"Transcription completed for recording {recording_id}. Text length: {len(recording.transcription)}")+ # Don't commit yet, proceed to summarization++ # --- Step 2: Title & Summary Generation using OpenRouter ---+ if client is None: # Check if OpenRouter client initialized successfully earlier+ app.logger.warning(f"Skipping summary for {recording_id}: OpenRouter client not configured.")+ recording.summary = "[Summary skipped: OpenRouter client not configured]"+ recording.status = 'COMPLETED'+ db.session.commit()+ return # Exit cleanly++ recording.status = 'SUMMARIZING' # Update status+ db.session.commit()+ app.logger.info(f"Requesting title and summary from OpenRouter for recording {recording_id} using model {openrouter_model_name}...")++ if not recording.transcription or len(recording.transcription.strip()) < 10: # Basic check for valid transcript+ app.logger.warning(f"Transcription for recording {recording_id} is too short or empty. Skipping summarization.")+ recording.status = 'COMPLETED' # Mark as completed even without summary+ recording.summary = "[Summary skipped due to short transcription]"+ db.session.commit()+ return # Exit the task cleanly++ # Prepare the prompt for OpenRouter+ prompt_text = f"""Analyze the following audio transcription and generate a concise title and a brief summary.++Transcription:+\"\"\"+{recording.transcription[:30000]}+\"\"\"++Respond STRICTLY with a JSON object containing two keys: "title" (a short, descriptive title, max 15 words) and "summary" (a paragraph summarizing the key points, max 150 words).+Example Format:+{{+ "title": "Example Meeting Discussion on Q3 Results",+ "summary": "The meeting covered the financial results for Q3, highlighting key achievements and areas for improvement. Action items were assigned for follow-up."+}}++JSON Response:""" # The prompt guides the model towards the desired output++ try:+ # Use the OpenRouter client configured earlier+ completion = client.chat.completions.create(+ model=openrouter_model_name,+ messages=[+ {"role": "system", "content": "You are an AI assistant that generates titles and summaries for meeting transcripts. Respond only with the requested JSON object."},+ {"role": "user", "content": prompt_text}+ ],+ temperature=0.5, # Adjust temperature as needed+ max_tokens=300, # Adjust based on expected title+summary length+ response_format={"type": "json_object"} # Request JSON output+ )++ response_content = completion.choices[0].message.content+ app.logger.debug(f"Raw OpenRouter response for {recording_id}: {response_content}")++ try:+ response_content = completion.choices[0].message.content+ app.logger.debug(f"Raw OpenRouter response for {recording_id}: {response_content}")++ # Use regex to extract JSON content from potential markdown code blocks+ # This looks for content between markdown code blocks or just takes the whole content+ json_match = re.search(r'```(?:json)?(.*?)```|(.+)', response_content, re.DOTALL)++ if json_match:+ # Use the first group that matched (either between ``` or the whole content)+ sanitized_response = json_match.group(1) if json_match.group(1) else json_match.group(2)+ sanitized_response = sanitized_response.strip()+ else:+ sanitized_response = response_content.strip()++ summary_data = json.loads(response_content)+ generated_title = summary_data.get("title")+ generated_summary = summary_data.get("summary")++ if generated_title and generated_summary:+ # Update recording with AI generated content+ recording.title = generated_title.strip()+ recording.summary = generated_summary.strip()+ recording.status = 'COMPLETED'+ app.logger.info(f"Title and summary generated successfully for recording {recording_id}.")+ else:+ app.logger.warning(f"OpenRouter response for {recording_id} lacked 'title' or 'summary' key. Response: {response_content}")+ recording.summary = "[AI summary generation failed: Invalid JSON structure]"+ recording.status = 'COMPLETED' # Still completed, but summary failed++ except json.JSONDecodeError as json_e:+ app.logger.error(f"Failed to parse JSON response from OpenRouter for {recording_id}: {json_e}. Response: {response_content}")+ recording.summary = f"[AI summary generation failed: Invalid JSON response ({json_e})]"+ recording.status = 'COMPLETED' # Mark as completed, summary failed++ except Exception as summary_e:+ app.logger.error(f"Error calling OpenRouter API for summary ({recording_id}): {str(summary_e)}")+ # Keep transcription, but mark summary failed. Don't change status from SUMMARIZING yet.+ recording.summary = f"[AI summary generation failed: API Error ({str(summary_e)})]"+ recording.status = 'COMPLETED' # Even if summary fails, transcription worked.+++ db.session.commit() # Final commit for this step++ except Exception as e:+ db.session.rollback() # Rollback if any step failed critically+ app.logger.error(f"Processing FAILED for recording {recording_id}: {str(e)}", exc_info=True)+ # Retrieve recording again in case session was rolled back+ recording = db.session.get(Recording, recording_id)+ if recording:+ # Ensure status reflects failure even after rollback/retrieve attempt+ if recording.status not in ['COMPLETED', 'FAILED']: # Avoid overwriting final state+ recording.status = 'FAILED'+ if not recording.transcription: # If transcription itself failed+ recording.transcription = f"Processing failed: {str(e)}"+ # Add error note to summary if appropriate stage was reached+ if recording.status == 'SUMMARIZING' and not recording.summary:+ recording.summary = f"[Processing failed during summarization: {str(e)}]"++ db.session.commit()++# --- Chat with Transcription ---[email protected]('/chat', methods=['POST'])+def chat_with_transcription():+ try:+ data = request.json+ if not data:+ return jsonify({'error': 'No data provided'}), 400++ recording_id = data.get('recording_id')+ user_message = data.get('message')+ message_history = data.get('message_history', [])++ if not recording_id:+ return jsonify({'error': 'No recording ID provided'}), 400+ if not user_message:+ return jsonify({'error': 'No message provided'}), 400++ # Get the recording+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404++ # Check if OpenRouter client is available+ if client is None:+ return jsonify({'error': 'Chat service is not available (OpenRouter client not configured)'}), 503++ # Prepare the system prompt with the transcription+ system_prompt = f"""You are a professional meeting analyst working with Murtaza Nasir, Assistant Professor at Wichita State University. Analyze the following meeting information and respond to the specific request.++Following are the meeting participants and their roles:+{recording.participants or "No specific participants information provided."}++Following is the meeting transcript:+<<start transcript>>+{recording.transcription or "No transcript available."}+<<end transcript>>++Additional context and notes about the meeting:+{recording.notes or "none"}+"""++ # Call the LLM+ try:+ # Prepare messages array with system prompt and conversation history+ messages = [{"role": "system", "content": system_prompt}]++ # Add message history if provided+ if message_history:+ messages.extend(message_history)++ # Add the current user message+ messages.append({"role": "user", "content": user_message})++ completion = client.chat.completions.create(+ model=openrouter_model_name,+ messages=messages,+ temperature=0.7,+ max_tokens=1000+ )++ response_content = completion.choices[0].message.content++ # Convert markdown in the response to HTML+ response_html = md_to_html(response_content)++ return jsonify({+ 'response': response_content,+ 'response_html': response_html,+ 'success': True+ })++ except Exception as chat_error:+ app.logger.error(f"Error calling OpenRouter API for chat: {str(chat_error)}")+ return jsonify({'error': f'Chat service error: {str(chat_error)}'}), 500++ except Exception as e:+ app.logger.error(f"Error in chat endpoint: {str(e)}")+ return jsonify({'error': str(e)}), 500+++# --- Flask Routes ---[email protected]('/')+def index():+ return render_template('index.html')+[email protected]('/recordings', methods=['GET'])+def get_recordings():+ try:+ stmt = select(Recording).order_by(Recording.created_at.desc())+ recordings = db.session.execute(stmt).scalars().all()+ return jsonify([recording.to_dict() for recording in recordings])+ except Exception as e:+ app.logger.error(f"Error fetching recordings: {e}")+ return jsonify({'error': str(e)}), 500+[email protected]('/save', methods=['POST'])+def save_metadata():+ try:+ data = request.json+ if not data: return jsonify({'error': 'No data provided'}), 400+ recording_id = data.get('id')+ if not recording_id: return jsonify({'error': 'No recording ID provided'}), 400++ recording = db.session.get(Recording, recording_id)+ if not recording: return jsonify({'error': 'Recording not found'}), 404++ # Update fields if provided+ if 'title' in data: recording.title = data['title']+ if 'participants' in data: recording.participants = data['participants']+ if 'notes' in data: recording.notes = data['notes']+ if 'summary' in data: recording.summary = data['summary'] # <-- ADDED: Allow saving edited summary+ if 'meeting_date' in data:+ try:+ # Attempt to parse date string (e.g., "YYYY-MM-DD")+ date_str = data['meeting_date']+ if date_str:+ recording.meeting_date = datetime.strptime(date_str, '%Y-%m-%d').date()+ else:+ recording.meeting_date = None # Allow clearing the date+ except (ValueError, TypeError) as e:+ app.logger.warning(f"Could not parse meeting_date '{data.get('meeting_date')}': {e}")+ # Optionally return an error or just ignore the invalid date+ # return jsonify({'error': f"Invalid date format for meeting_date. Use YYYY-MM-DD."}), 400++ # Do not update transcription or status here+ db.session.commit()+ return jsonify({'success': True, 'recording': recording.to_dict()})++ except Exception as e:+ db.session.rollback()+ app.logger.error(f"Error saving metadata for recording {recording_id}: {e}")+ return jsonify({'error': str(e)}), 500++[email protected]('/upload', methods=['POST'])+def upload_file():+ try:+ if 'file' not in request.files:+ return jsonify({'error': 'No file provided'}), 400++ file = request.files['file']+ if file.filename == '':+ return jsonify({'error': 'No file selected'}), 400++ filename = secure_filename(file.filename)+ # Ensure filepath uses the configured UPLOAD_FOLDER+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}")++ # Get file size before saving+ file.seek(0, os.SEEK_END)+ file_size = file.tell()+ file.seek(0)++ # Check size limit again+ if file_size > app.config['MAX_CONTENT_LENGTH']:+ raise RequestEntityTooLarge()++ file.save(filepath)+ app.logger.info(f"File saved to {filepath}")++ # Create initial database entry with PENDING status and filename as placeholder title+ recording = Recording(+ audio_path=filepath,+ # Use filename (without path part) as initial title+ title=f"Recording - {filename}",+ file_size=file_size,+ status='PENDING', # Explicitly set status+ meeting_date=datetime.utcnow().date() # <-- ADDED: Default meeting_date to today+ )+ db.session.add(recording)+ db.session.commit()+ app.logger.info(f"Initial recording record created with ID: {recording.id}")++ # --- Start transcription & summarization in background thread ---+ thread = threading.Thread(+ target=transcribe_audio_task,+ # Pass original filename for logging clarity+ args=(app.app_context(), recording.id, filepath, filename)+ )+ thread.start()+ app.logger.info(f"Background processing thread started for recording ID: {recording.id}")++ # Return the initial recording data and ID immediately+ return jsonify(recording.to_dict()), 202 # 202 Accepted++ except RequestEntityTooLarge:+ max_size_mb = app.config['MAX_CONTENT_LENGTH'] / (1024 * 1024)+ app.logger.warning(f"Upload failed: File too large (>{max_size_mb}MB)")+ return jsonify({+ 'error': f'File too large. Maximum size is {max_size_mb:.0f} MB.',+ 'max_size_mb': max_size_mb+ }), 413+ except Exception as e:+ db.session.rollback() # Rollback if initial save failed+ app.logger.error(f"Error during file upload: {e}", exc_info=True)+ return jsonify({'error': str(e)}), 500+++# Status Endpoint (no changes needed, it returns the full recording dict)[email protected]('/status/<int:recording_id>', methods=['GET'])+def get_status(recording_id):+ """Endpoint to check the transcription/summarization status."""+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404+ return jsonify(recording.to_dict())+ except Exception as e:+ app.logger.error(f"Error fetching status for recording {recording_id}: {e}")+ return jsonify({'error': str(e)}), 500++# Get Audio Endpoint (no changes needed)[email protected]('/audio/<int:recording_id>')+def get_audio(recording_id):+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording or not recording.audio_path:+ return jsonify({'error': 'Recording or audio file not found'}), 404+ if not os.path.exists(recording.audio_path):+ app.logger.error(f"Audio file missing from server: {recording.audio_path}")+ return jsonify({'error': 'Audio file missing from server'}), 404+ return send_file(recording.audio_path)+ except Exception as e:+ app.logger.error(f"Error serving audio for recording {recording_id}: {e}")+ return jsonify({'error': str(e)}), 500++# Delete Recording Endpoint (no changes needed functionally)[email protected]('/recording/<int:recording_id>', methods=['DELETE'])+def delete_recording(recording_id):+ try:+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return jsonify({'error': 'Recording not found'}), 404++ # Delete the audio file first+ try:+ if recording.audio_path and os.path.exists(recording.audio_path):+ os.remove(recording.audio_path)+ app.logger.info(f"Deleted audio file: {recording.audio_path}")+ except Exception as e:+ app.logger.error(f"Error deleting audio file {recording.audio_path}: {e}")++ # Delete the database record+ db.session.delete(recording)+ db.session.commit()+ app.logger.info(f"Deleted recording record ID: {recording_id}")++ return jsonify({'success': True})+ except Exception as e:+ db.session.rollback()+ app.logger.error(f"Error deleting recording {recording_id}: {e}")+ return jsonify({'error': str(e)}), 500+++if __name__ == '__main__':+ # Consider using waitress or gunicorn for production+ # waitress-serve --host 0.0.0.0 --port 8899 app:app+ # For development:+ app.run(host='0.0.0.0', port=8899, debug=True) # Set debug=False if thread issues arisediff --git a/create_admin.py b/create_admin.pynew file mode 100644index 00000000..1db4a075--- /dev/null+++ b/create_admin.py@@ -0,0 +1,90 @@+#!/usr/bin/env python3++import os+import sys+import getpass+from email_validator import validate_email, EmailNotValidError++# Try to import from app context+try:+ from flask import current_app+ app = current_app._get_current_object()+ with app.app_context():+ db = app.extensions['sqlalchemy'].db+ User = app.extensions['sqlalchemy'].db.metadata.tables['user']+ bcrypt = app.extensions.get('bcrypt')+except (RuntimeError, AttributeError, KeyError):+ # If not in app context, import directly+ try:+ from app import app, db, User, bcrypt+ except ImportError as e:+ print(f"Error: Could not import required modules: {e}")+ print("Make sure create_admin.py is runnable and PYTHONPATH is set.")+ sys.exit(1)++def create_admin_user():+ """+ Create an admin user interactively.+ """+ print("Creating admin user for Speakr application")+ print("=========================================")++ # Get username+ while True:+ username = input("Enter username (min 3 characters): ").strip()+ if len(username) < 3:+ print("Username must be at least 3 characters long.")+ continue++ # Check if username already exists+ with app.app_context():+ existing_user = db.session.query(User).filter_by(username=username).first()+ if existing_user:+ print(f"Username '{username}' already exists. Please choose another.")+ continue+ break++ # Get email+ while True:+ email = input("Enter email address: ").strip()+ try:+ # Validate email+ validate_email(email)++ # Check if email already exists+ with app.app_context():+ existing_email = db.session.query(User).filter_by(email=email).first()+ if existing_email:+ print(f"Email '{email}' already exists. Please use another.")+ continue+ break+ except EmailNotValidError as e:+ print(f"Invalid email: {str(e)}")++ # Get password+ while True:+ password = getpass.getpass("Enter password (min 8 characters): ")+ if len(password) < 8:+ print("Password must be at least 8 characters long.")+ continue++ confirm_password = getpass.getpass("Confirm password: ")+ if password != confirm_password:+ print("Passwords do not match. Please try again.")+ continue+ break++ # Create user+ with app.app_context():+ hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')+ new_user = User(username=username, email=email, password=hashed_password, is_admin=True)+ db.session.add(new_user)+ db.session.commit()++ print("\nAdmin user created successfully!")+ print(f"Username: {username}")+ print(f"Email: {email}")+ print("You can now log in to the application with these credentials.")++if __name__ == "__main__":+ create_admin_user()diff --git a/deployment/setup.sh b/deployment/setup.shindex 6cf6055b..9a7c70fa 100755--- a/deployment/setup.sh+++ b/deployment/setup.sh@@ -9,8 +9,16 @@ cp app.py /opt/transcription-app/cp -r templates /opt/transcription-app/cp requirements.txt /opt/transcription-app/cp reset_db.py /opt/transcription-app/+cp migrate_db.py /opt/transcription-app/+cp create_admin.py /opt/transcription-app/cp .env /opt/transcription-app/ # Copy the .env file with API keys+# Add SECRET_KEY to .env file if it doesn't exist+if ! grep -q "SECRET_KEY" /opt/transcription-app/.env; then+ echo "SECRET_KEY=$(openssl rand -hex 32)" >> /opt/transcription-app/.env+ echo "Added SECRET_KEY to .env file"+fi+# Create and activate virtual environmentpython3 -m venv /opt/transcription-app/venvsource /opt/transcription-app/venv/bin/activate@@ -25,8 +33,16 @@ mkdir -p /opt/transcription-app/instancechmod 755 /opt/transcription-app/uploadschmod 755 /opt/transcription-app/instance-# Initialize the database-python reset_db.py+# Initialize or migrate the database+if [ ! -f /opt/transcription-app/instance/transcriptions.db ]; then+ # If database doesn't exist, create it from scratch+ echo "Database doesn't exist. Creating new database..."+ python reset_db.py+else+ # If database exists, migrate it to preserve data+ echo "Database exists. Migrating schema to preserve data..."+ python migrate_db.py+fi# Set proper ownership for all filessudo chown -R $USER:$USER /opt/transcription-app@@ -62,3 +78,12 @@ sleep 3sudo systemctl status transcriptionecho "Installation complete! The application should be running on port 8899."++# Ask if user wants to create an admin user+read -p "Do you want to create an admin user now? (y/n): " create_admin+if [[ $create_admin == "y" || $create_admin == "Y" ]]; then+ echo "Creating admin user..."+ python create_admin.py+else+ echo "You can create an admin user later by running: python create_admin.py"+fidiff --git a/migrate_db.py b/migrate_db.pynew file mode 100644index 00000000..baf5db00--- /dev/null+++ b/migrate_db.py@@ -0,0 +1,120 @@+#!/usr/bin/env python3++import os+import sys+from sqlalchemy import inspect, Column, Integer, ForeignKey+from sqlalchemy.exc import OperationalError++# Try to import from app context+try:+ from flask import current_app+ app = current_app._get_current_object()+ with app.app_context():+ db = app.extensions['sqlalchemy'].db+except (RuntimeError, AttributeError, KeyError):+ # If not in app context, import directly+ try:+ from app import app, db, User, Recording+ except ImportError as e:+ print(f"Error: Could not import 'app' and 'db': {e}")+ print("Make sure migrate_db.py is runnable and PYTHONPATH is set.")+ sys.exit(1)++def migrate_database():+ """+ Migrate the database schema without losing data:+ 1. Check if User table exists, create it if not+ 2. Check if Recording.user_id column exists, add it if not+ """+ print("Starting database migration...")++ with app.app_context():+ inspector = inspect(db.engine)+ existing_tables = inspector.get_table_names()++ # Check if User table exists+ if 'user' not in existing_tables:+ print("Creating User table...")+ # Create User table+ class TempUser(db.Model):+ __tablename__ = 'user'+ id = db.Column(db.Integer, primary_key=True)+ username = db.Column(db.String(20), unique=True, nullable=False)+ email = db.Column(db.String(120), unique=True, nullable=False)+ password = db.Column(db.String(60), nullable=False)++ # Create only the User table+ db.create_all(tables=[TempUser.__table__])+ print("User table created successfully!")+ else:+ print("User table already exists.")++ # Check if Recording.user_id column exists+ recording_columns = [column['name'] for column in inspector.get_columns('recording')]+ if 'user_id' not in recording_columns:+ print("Adding user_id column to Recording table...")+ try:+ # Add user_id column to Recording table+ with db.engine.begin() as conn:+ conn.execute(db.text("ALTER TABLE recording ADD COLUMN user_id INTEGER REFERENCES user(id)"))+ print("user_id column added successfully!")+ except OperationalError as e:+ print(f"Error adding user_id column: {e}")+ print("Attempting alternative approach...")+ try:+ # SQLite doesn't support ALTER TABLE ADD COLUMN with foreign keys+ # So we need to create a new table, copy data, drop old table, rename new table++ # 1. Create temporary table with new schema+ with db.engine.begin() as conn:+ conn.execute(db.text("""+ CREATE TABLE recording_new (+ id INTEGER PRIMARY KEY,+ title VARCHAR(200),+ participants VARCHAR(500),+ notes TEXT,+ transcription TEXT,+ summary TEXT,+ status VARCHAR(50),+ audio_path VARCHAR(500),+ created_at DATETIME,+ meeting_date DATE,+ file_size INTEGER,+ user_id INTEGER REFERENCES user(id)+ )+ """))++ # 2. Copy data from old table to new table+ with db.engine.begin() as conn:+ conn.execute(db.text("""+ INSERT INTO recording_new (+ id, title, participants, notes, transcription, summary,+ status, audio_path, created_at, meeting_date, file_size+ )+ SELECT+ id, title, participants, notes, transcription, summary,+ status, audio_path, created_at, meeting_date, file_size+ FROM recording+ """))++ # 3. Drop old table+ with db.engine.begin() as conn:+ conn.execute(db.text("DROP TABLE recording"))++ # 4. Rename new table+ with db.engine.begin() as conn:+ conn.execute(db.text("ALTER TABLE recording_new RENAME TO recording"))++ print("user_id column added successfully using table recreation!")+ except Exception as e2:+ print(f"Error during table recreation: {e2}")+ sys.exit(1)+ else:+ print("user_id column already exists in Recording table.")++ print("Database migration completed successfully!")++if __name__ == "__main__":+ print("Attempting to migrate the database...")+ migrate_database()+ print("Database migration process finished.")diff --git a/requirements.txt b/requirements.txtindex 061f7011..5047e6e6 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,5 +1,9 @@flask==2.3.3flask-sqlalchemy==3.1.1+flask-login==0.6.3+flask-wtf==1.2.2+flask-bcrypt==1.0.1+email-validator==2.2.0openai==1.3.0werkzeug==2.3.7gunicorn==21.2.0diff --git a/templates/account.html b/templates/account.htmlnew file mode 100644index 00000000..a72d8322--- /dev/null+++ b/templates/account.html@@ -0,0 +1,198 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>{{ title }} - Speakr</title>+ <script src="https://cdn.tailwindcss.com"></script>+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">+ <style>+ /* Dark Mode CSS Variables */+ :root {+ /* Light mode variables */+ --bg-primary: #f3f4f6; /* gray-100 */+ --bg-secondary: #ffffff; /* white */+ --bg-tertiary: #f9fafb; /* gray-50 */+ --bg-accent: #dbeafe; /* blue-100 */+ --bg-accent-hover: #bfdbfe; /* blue-200 */+ --bg-button: #2563eb; /* blue-600 */+ --bg-button-hover: #1d4ed8; /* blue-700 */+ --bg-danger: #dc2626; /* red-600 */+ --bg-danger-hover: #b91c1c; /* red-700 */+ --bg-danger-light: #fee2e2; /* red-100 */+ --bg-info-light: #dbeafe; /* blue-100 */+ --bg-warn-light: #fef3c7; /* amber-100 */+ --bg-success-light: #d1fae5; /* green-100 */+ --bg-pending-light: #f5f5f4; /* stone-100 */+ --bg-input: #ffffff; /* white */++ --text-primary: #1f2937; /* gray-800 */+ --text-secondary: #374151; /* gray-700 */+ --text-muted: #6b7280; /* gray-500 */+ --text-light: #9ca3af; /* gray-400 */+ --text-accent: #1d4ed8; /* blue-700 */+ --text-button: #ffffff; /* white */+ --text-danger: #b91c1c; /* red-700 */+ --text-danger-strong: #991b1b; /* red-800 */+ --text-info-strong: #1e40af; /* blue-800 */+ --text-warn-strong: #92400e; /* amber-800 */+ --text-success-strong: #065f46; /* green-800 */+ --text-pending-strong: #44403c; /* stone-700 */++ --border-primary: #e5e7eb; /* gray-200 */+ --border-secondary: #d1d5db; /* gray-300 */+ --border-accent: #93c5fd; /* blue-300 */+ --border-danger: #f87171; /* red-400 */+ --border-focus: #3b82f6; /* blue-500 */+ --ring-focus: #bfdbfe; /* blue-200 */+ }++ .dark {+ /* Dark mode variables */+ --bg-primary: #111827; /* gray-900 */+ --bg-secondary: #1f2937; /* gray-800 */+ --bg-tertiary: #374151; /* gray-700 */+ --bg-accent: #1e3a8a; /* blue-900 */+ --bg-accent-hover: #1e40af; /* blue-800 */+ --bg-button: #2563eb; /* blue-600 */+ --bg-button-hover: #3b82f6; /* blue-500 */+ --bg-danger: #dc2626; /* red-600 */+ --bg-danger-hover: #ef4444; /* red-500 */+ --bg-danger-light: #7f1d1d; /* red-900 */+ --bg-info-light: #1e3a8a; /* blue-900 */+ --bg-warn-light: #78350f; /* amber-900 */+ --bg-success-light: #064e3b; /* green-900 */+ --bg-pending-light: #292524; /* stone-800 */+ --bg-input: #374151; /* gray-700 */++ --text-primary: #f3f4f6; /* gray-100 */+ --text-secondary: #d1d5db; /* gray-300 */+ --text-muted: #9ca3af; /* gray-400 */+ --text-light: #6b7280; /* gray-500 */+ --text-accent: #60a5fa; /* blue-400 */+ --text-button: #ffffff; /* white */+ --text-danger: #f87171; /* red-400 */+ --text-danger-strong: #fca5a5; /* red-300 */+ --text-info-strong: #93c5fd; /* blue-300 */+ --text-warn-strong: #fcd34d; /* amber-300 */+ --text-success-strong: #6ee7b7; /* green-300 */+ --text-pending-strong: #d6d3d1; /* stone-300 */++ --border-primary: #374151; /* gray-700 */+ --border-secondary: #4b5563; /* gray-600 */+ --border-accent: #1d4ed8; /* blue-700 */+ --border-danger: #ef4444; /* red-500 */+ --border-focus: #3b82f6; /* blue-500 */+ --ring-focus: #1e40af; /* blue-800 */+ }++ html {+ background-color: var(--bg-primary);+ color: var(--text-primary);+ transition: background-color 0.3s, color 0.3s;+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;+ }+ html, body { height: 100%; margin: 0; }+ </style>+</head>+<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">+ <div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">+ <header class="flex justify-between items-center mb-6 pb-4 border-b border-[var(--border-primary)]">+ <h1 class="text-3xl font-bold text-[var(--text-primary)]">+ <a href="{{ url_for('index') }}">Speakr</a>+ </h1>+ <div class="flex items-center space-x-4">+ <a href="{{ url_for('index') }}" class="text-[var(--text-secondary)] hover:text-[var(--text-accent)]">+ <i class="fas fa-home mr-1"></i> Home+ </a>+ <a href="{{ url_for('logout') }}" class="text-[var(--text-secondary)] hover:text-[var(--text-danger)]">+ <i class="fas fa-sign-out-alt mr-1"></i> Logout+ </a>+ </div>+ </header>++ <main class="flex-grow">+ <div class="bg-[var(--bg-secondary)] p-8 rounded-xl shadow-lg border border-[var(--border-primary)]">+ <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6">Account Information</h2>++ {% with messages = get_flashed_messages(with_categories=true) %}+ {% if messages %}+ {% for category, message in messages %}+ <div class="mb-4 p-3 rounded-lg {% if category == 'success' %}bg-[var(--bg-success-light)] text-[var(--text-success-strong)]{% elif category == 'danger' %}bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]{% else %}bg-[var(--bg-info-light)] text-[var(--text-info-strong)]{% endif %}">+ {{ message }}+ </div>+ {% endfor %}+ {% endif %}+ {% endwith %}++ <div class="grid grid-cols-1 md:grid-cols-2 gap-8">+ <div>+ <div class="mb-6">+ <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">User Details</h3>+ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">+ <div class="mb-3">+ <span class="block text-sm font-medium text-[var(--text-muted)]">Username</span>+ <span class="block text-[var(--text-primary)]">{{ current_user.username }}</span>+ </div>+ <div>+ <span class="block text-sm font-medium text-[var(--text-muted)]">Email</span>+ <span class="block text-[var(--text-primary)]">{{ current_user.email }}</span>+ </div>+ </div>+ </div>++ <div>+ <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">Account Actions</h3>+ <div class="flex flex-col space-y-3">+ <a href="{{ url_for('index') }}" class="inline-flex items-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">+ <i class="fas fa-microphone mr-2"></i> Go to Recordings+ </a>+ </div>+ </div>+ </div>++ <div>+ <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">Account Statistics</h3>+ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">+ <div class="grid grid-cols-2 gap-4">+ <div class="text-center p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">+ <span class="block text-3xl font-bold text-[var(--text-accent)]">{{ current_user.recordings|length }}</span>+ <span class="block text-sm text-[var(--text-muted)]">Total Recordings</span>+ </div>++ <div class="text-center p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">+ <span class="block text-3xl font-bold text-[var(--text-accent)]">+ {% set completed_count = current_user.recordings|selectattr('status', 'equalto', 'COMPLETED')|list|length %}+ {{ completed_count }}+ </span>+ <span class="block text-sm text-[var(--text-muted)]">Completed</span>+ </div>++ <div class="text-center p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">+ <span class="block text-3xl font-bold text-[var(--text-warn-strong)]">+ {% set processing_count = current_user.recordings|selectattr('status', 'in', ['PENDING', 'PROCESSING', 'SUMMARIZING'])|list|length %}+ {{ processing_count }}+ </span>+ <span class="block text-sm text-[var(--text-muted)]">Processing</span>+ </div>++ <div class="text-center p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">+ <span class="block text-3xl font-bold text-[var(--text-danger)]">+ {% set failed_count = current_user.recordings|selectattr('status', 'equalto', 'FAILED')|list|length %}+ {{ failed_count }}+ </span>+ <span class="block text-sm text-[var(--text-muted)]">Failed</span>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </main>++ <footer class="text-center py-4 mt-8 text-xs text-[var(--text-light)] border-t border-[var(--border-primary)]">+ Speakr © {{ now.year }}+ </footer>+ </div>+</body>+</html>diff --git a/templates/admin.html b/templates/admin.htmlnew file mode 100644index 00000000..e61932a3--- /dev/null+++ b/templates/admin.html@@ -0,0 +1,731 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Admin Dashboard - Speakr</title>+ <script src="https://cdn.tailwindcss.com"></script>+ <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">+ <style>+ /* Dark Mode CSS Variables */+ :root {+ /* Light mode variables */+ --bg-primary: #f3f4f6; /* gray-100 */+ --bg-secondary: #ffffff; /* white */+ --bg-tertiary: #f9fafb; /* gray-50 */+ --bg-accent: #dbeafe; /* blue-100 */+ --bg-accent-hover: #bfdbfe; /* blue-200 */+ --bg-button: #2563eb; /* blue-600 */+ --bg-button-hover: #1d4ed8; /* blue-700 */+ --bg-danger: #dc2626; /* red-600 */+ --bg-danger-hover: #b91c1c; /* red-700 */+ --bg-danger-light: #fee2e2; /* red-100 */+ --bg-info-light: #dbeafe; /* blue-100 */+ --bg-warn-light: #fef3c7; /* amber-100 */+ --bg-success-light: #d1fae5; /* green-100 */+ --bg-pending-light: #f5f5f4; /* stone-100 */+ --bg-input: #ffffff; /* white */++ --text-primary: #1f2937; /* gray-800 */+ --text-secondary: #374151; /* gray-700 */+ --text-muted: #6b7280; /* gray-500 */+ --text-light: #9ca3af; /* gray-400 */+ --text-accent: #1d4ed8; /* blue-700 */+ --text-button: #ffffff; /* white */+ --text-danger: #b91c1c; /* red-700 */+ --text-danger-strong: #991b1b; /* red-800 */+ --text-info-strong: #1e40af; /* blue-800 */+ --text-warn-strong: #92400e; /* amber-800 */+ --text-success-strong: #065f46; /* green-800 */+ --text-pending-strong: #44403c; /* stone-700 */++ --border-primary: #e5e7eb; /* gray-200 */+ --border-secondary: #d1d5db; /* gray-300 */+ --border-accent: #93c5fd; /* blue-300 */+ --border-danger: #f87171; /* red-400 */+ --border-focus: #3b82f6; /* blue-500 */+ --ring-focus: #bfdbfe; /* blue-200 */+ }++ .dark {+ /* Dark mode variables */+ --bg-primary: #111827; /* gray-900 */+ --bg-secondary: #1f2937; /* gray-800 */+ --bg-tertiary: #374151; /* gray-700 */+ --bg-accent: #1e3a8a; /* blue-900 */+ --bg-accent-hover: #1e40af; /* blue-800 */+ --bg-button: #2563eb; /* blue-600 */+ --bg-button-hover: #3b82f6; /* blue-500 */+ --bg-danger: #dc2626; /* red-600 */+ --bg-danger-hover: #ef4444; /* red-500 */+ --bg-danger-light: #7f1d1d; /* red-900 */+ --bg-info-light: #1e3a8a; /* blue-900 */+ --bg-warn-light: #78350f; /* amber-900 */+ --bg-success-light: #064e3b; /* green-900 */+ --bg-pending-light: #292524; /* stone-800 */+ --bg-input: #374151; /* gray-700 */++ --text-primary: #f3f4f6; /* gray-100 */+ --text-secondary: #d1d5db; /* gray-300 */+ --text-muted: #9ca3af; /* gray-400 */+ --text-light: #6b7280; /* gray-500 */+ --text-accent: #60a5fa; /* blue-400 */+ --text-button: #ffffff; /* white */+ --text-danger: #f87171; /* red-400 */+ --text-danger-strong: #fca5a5; /* red-300 */+ --text-info-strong: #93c5fd; /* blue-300 */+ --text-warn-strong: #fcd34d; /* amber-300 */+ --text-success-strong: #6ee7b7; /* green-300 */+ --text-pending-strong: #d6d3d1; /* stone-300 */++ --border-primary: #374151; /* gray-700 */+ --border-secondary: #4b5563; /* gray-600 */+ --border-accent: #1d4ed8; /* blue-700 */+ --border-danger: #ef4444; /* red-500 */+ --border-focus: #3b82f6; /* blue-500 */+ --ring-focus: #1e40af; /* blue-800 */+ }++ html {+ background-color: var(--bg-primary);+ color: var(--text-primary);+ transition: background-color 0.3s, color 0.3s;+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;+ }+ html, body { height: 100%; margin: 0; }+ .custom-scrollbar::-webkit-scrollbar { width: 6px; }+ .custom-scrollbar::-webkit-scrollbar-track { background: var(--scrollbar-track); border-radius: 12px; }+ .custom-scrollbar::-webkit-scrollbar-thumb { background: var(--scrollbar-thumb); border-radius: 12px; }+ .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: var(--scrollbar-thumb-hover); }+ </style>+</head>+<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">+ <div id="app" class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">+ <header class="flex justify-between items-center mb-6 pb-4 border-b border-[var(--border-primary)]">+ <h1 class="text-3xl font-bold text-[var(--text-primary)]">+ <a href="{{ url_for('index') }}">Speakr</a>+ </h1>+ <div class="flex items-center space-x-2">+ <button @click="toggleDarkMode" class="p-2 rounded-full text-[var(--text-muted)] hover:bg-[var(--bg-tertiary)] dark:text-gray-400 dark:hover:bg-gray-700 transition-colors duration-200" :title="isDarkMode ? 'Switch to Light Mode' : 'Switch to Dark Mode'">+ <i :class="isDarkMode ? 'fas fa-sun' : 'fas fa-moon'"></i>+ </button>+ <div class="relative" @click.away="isDropdownOpen = false">+ <button @click="isDropdownOpen = !isDropdownOpen" class="flex items-center px-3 py-2 border border-[var(--border-secondary)] rounded-lg text-[var(--text-secondary)] hover:text-[var(--text-accent)] focus:outline-none">+ <i class="fas fa-user-shield mr-2"></i>+ <span>{{ current_user.username }}</span>+ <i class="fas fa-chevron-down ml-2"></i>+ </button>+ <div v-show="isDropdownOpen" class="absolute right-0 mt-2 w-48 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg z-10">+ <a href="{{ url_for('index') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">+ <i class="fas fa-home mr-2"></i> Home+ </a>+ <a href="{{ url_for('account') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">+ <i class="fas fa-user mr-2"></i> Account+ </a>+ <a href="{{ url_for('admin') }}" class="block px-4 py-2 text-[var(--text-accent)] bg-[var(--bg-accent)]">+ <i class="fas fa-user-shield mr-2"></i> Admin+ </a>+ <a href="{{ url_for('logout') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-danger)]">+ <i class="fas fa-sign-out-alt mr-2"></i> Logout+ </a>+ </div>+ </div>+ </div>+ </header>++ <main class="flex-grow">+ <div class="bg-[var(--bg-secondary)] p-6 rounded-xl shadow-lg border border-[var(--border-primary)]">+ <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6">Admin Dashboard</h2>++ {% with messages = get_flashed_messages(with_categories=true) %}+ {% if messages %}+ {% for category, message in messages %}+ <div class="mb-4 p-3 rounded-lg {% if category == 'success' %}bg-[var(--bg-success-light)] text-[var(--text-success-strong)]{% elif category == 'danger' %}bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]{% else %}bg-[var(--bg-info-light)] text-[var(--text-info-strong)]{% endif %}">+ {{ message }}+ </div>+ {% endfor %}+ {% endif %}+ {% endwith %}++ <!-- Tabs -->+ <div class="border-b border-[var(--border-primary)] mb-6">+ <nav class="-mb-px flex space-x-8" aria-label="Tabs">+ <button @click="activeTab = 'users'"+ :class="activeTab === 'users' ? 'border-[var(--border-focus)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"+ class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">+ <i class="fas fa-users mr-2"></i> User Management+ </button>+ <button @click="activeTab = 'stats'"+ :class="activeTab === 'stats' ? 'border-[var(--border-focus)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"+ class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">+ <i class="fas fa-chart-bar mr-2"></i> System Statistics+ </button>+ </nav>+ </div>++ <!-- User Management Tab -->+ <div v-show="activeTab === 'users'">+ <div class="flex justify-between items-center mb-4">+ <h3 class="text-lg font-medium text-[var(--text-secondary)]">User Management</h3>+ <button @click="showAddUserModal = true" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg shadow hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out">+ <i class="fas fa-user-plus mr-2"></i> Add User+ </button>+ </div>++ <!-- Search and Filter -->+ <div class="mb-4 flex">+ <div class="relative flex-grow">+ <input type="text" v-model="userSearchQuery" placeholder="Search users..." class="w-full px-4 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">+ <button v-if="userSearchQuery" @click="userSearchQuery = ''" class="absolute right-3 top-2.5 text-[var(--text-muted)] hover:text-[var(--text-secondary)]">+ <i class="fas fa-times"></i>+ </button>+ </div>+ </div>++ <!-- Users Table -->+ <div class="overflow-x-auto">+ <table class="min-w-full divide-y divide-[var(--border-primary)]">+ <thead class="bg-[var(--bg-tertiary)]">+ <tr>+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">ID</th>+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Username</th>+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Email</th>+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Admin</th>+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Recordings</th>+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Storage Used</th>+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Actions</th>+ </tr>+ </thead>+ <tbody class="bg-[var(--bg-secondary)] divide-y divide-[var(--border-primary)]">+ <tr v-for="user in filteredUsers" :key="user.id" class="hover:bg-[var(--bg-tertiary)]">+ <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ user.id }</td>+ <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-[var(--text-primary)]">${ user.username }</td>+ <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ user.email }</td>+ <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">+ <span v-if="user.is_admin" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-[var(--bg-success-light)] text-[var(--text-success-strong)]">Yes</span>+ <span v-else class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-[var(--bg-pending-light)] text-[var(--text-pending-strong)]">No</span>+ </td>+ <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ user.recordings_count }</td>+ <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ formatFileSize(user.storage_used) }</td>+ <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">+ <div class="flex space-x-2">+ <button @click="editUser(user)" class="text-[var(--text-accent)] hover:text-[var(--text-accent-hover)]" title="Edit User">+ <i class="fas fa-edit"></i>+ </button>+ <button @click="toggleAdminStatus(user)" :class="user.is_admin ? 'text-[var(--text-warn-strong)]' : 'text-[var(--text-info-strong)]'" :title="user.is_admin ? 'Remove Admin' : 'Make Admin'">+ <i class="fas" :class="user.is_admin ? 'fa-user-minus' : 'fa-user-shield'"></i>+ </button>+ <button @click="confirmDeleteUser(user)" class="text-[var(--text-danger)] hover:text-[var(--text-danger-hover)]" title="Delete User">+ <i class="fas fa-trash"></i>+ </button>+ </div>+ </td>+ </tr>+ <tr v-if="filteredUsers.length === 0">+ <td colspan="7" class="px-6 py-4 text-center text-sm text-[var(--text-muted)]">+ <div v-if="isLoadingUsers">+ <i class="fas fa-spinner fa-spin mr-2"></i> Loading users...+ </div>+ <div v-else>+ No users found.+ </div>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>++ <!-- System Statistics Tab -->+ <div v-show="activeTab === 'stats'">+ <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-4">System Statistics</h3>++ <!-- Summary Cards -->+ <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">+ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center">+ <div class="p-3 rounded-full bg-[var(--bg-info-light)] text-[var(--text-info-strong)]">+ <i class="fas fa-users text-xl"></i>+ </div>+ <div class="ml-4">+ <p class="text-sm font-medium text-[var(--text-muted)]">Total Users</p>+ <p class="text-2xl font-semibold text-[var(--text-primary)]">${ stats.total_users }</p>+ </div>+ </div>+ </div>++ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center">+ <div class="p-3 rounded-full bg-[var(--bg-success-light)] text-[var(--text-success-strong)]">+ <i class="fas fa-file-audio text-xl"></i>+ </div>+ <div class="ml-4">+ <p class="text-sm font-medium text-[var(--text-muted)]">Total Recordings</p>+ <p class="text-2xl font-semibold text-[var(--text-primary)]">${ stats.total_recordings }</p>+ </div>+ </div>+ </div>++ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center">+ <div class="p-3 rounded-full bg-[var(--bg-warn-light)] text-[var(--text-warn-strong)]">+ <i class="fas fa-database text-xl"></i>+ </div>+ <div class="ml-4">+ <p class="text-sm font-medium text-[var(--text-muted)]">Total Storage Used</p>+ <p class="text-2xl font-semibold text-[var(--text-primary)]">${ formatFileSize(stats.total_storage) }</p>+ </div>+ </div>+ </div>++ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">+ <div class="flex items-center">+ <div class="p-3 rounded-full bg-[var(--bg-accent)] text-[var(--text-accent)]">+ <i class="fas fa-comments text-xl"></i>+ </div>+ <div class="ml-4">+ <p class="text-sm font-medium text-[var(--text-muted)]">Total Queries</p>+ <p class="text-2xl font-semibold text-[var(--text-primary)]">${ stats.total_queries }</p>+ </div>+ </div>+ </div>+ </div>++ <!-- Status Distribution -->+ <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">+ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">+ <h4 class="text-md font-medium text-[var(--text-secondary)] mb-3">Recording Status Distribution</h4>+ <div class="grid grid-cols-2 gap-4">+ <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">+ <span class="block text-2xl font-bold text-[var(--text-success-strong)]">${ stats.completed_recordings }</span>+ <span class="block text-sm text-[var(--text-muted)]">Completed</span>+ </div>+ <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">+ <span class="block text-2xl font-bold text-[var(--text-warn-strong)]">${ stats.processing_recordings }</span>+ <span class="block text-sm text-[var(--text-muted)]">Processing</span>+ </div>+ <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">+ <span class="block text-2xl font-bold text-[var(--text-pending-strong)]">${ stats.pending_recordings }</span>+ <span class="block text-sm text-[var(--text-muted)]">Pending</span>+ </div>+ <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">+ <span class="block text-2xl font-bold text-[var(--text-danger-strong)]">${ stats.failed_recordings }</span>+ <span class="block text-sm text-[var(--text-muted)]">Failed</span>+ </div>+ </div>+ </div>++ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">+ <h4 class="text-md font-medium text-[var(--text-secondary)] mb-3">Top Users by Storage</h4>+ <div class="space-y-3">+ <div v-for="user in stats.top_users" :key="user.id" class="flex justify-between items-center p-2 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)]">+ <div class="flex items-center">+ <i class="fas fa-user text-[var(--text-accent)] mr-2"></i>+ <span class="text-sm font-medium text-[var(--text-primary)]">${ user.username }</span>+ </div>+ <div class="text-sm text-[var(--text-secondary)]">+ <span class="font-medium">${ formatFileSize(user.storage_used) }</span>+ <span class="text-[var(--text-muted)] ml-2">(${ user.recordings_count} recordings)</span>+ </div>+ </div>+ <div v-if="stats.top_users.length === 0" class="text-center text-sm text-[var(--text-muted)] p-2">+ No data available+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </main>++ <footer class="text-center py-4 mt-8 text-xs text-[var(--text-light)] border-t border-[var(--border-primary)]">+ Speakr © {{ now.year }}+ </footer>++ <!-- Add User Modal -->+ <div v-if="showAddUserModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">+ <div class="flex justify-between items-center mb-4">+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Add New User</h3>+ <button @click="showAddUserModal = false" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">×</button>+ </div>+ <form @submit.prevent="addUser">+ <div class="mb-4">+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Username</label>+ <input v-model="newUser.username" type="text" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">+ </div>+ <div class="mb-4">+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Email</label>+ <input v-model="newUser.email" type="email" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">+ </div>+ <div class="mb-4">+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Password</label>+ <input v-model="newUser.password" type="password" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">+ </div>+ <div class="mb-4">+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Confirm Password</label>+ <input v-model="newUser.confirmPassword" type="password" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">+ </div>+ <div class="mb-4 flex items-center">+ <input v-model="newUser.isAdmin" type="checkbox" id="isAdmin" class="rounded border-[var(--border-secondary)] text-[var(--text-accent)] focus:ring-[var(--border-focus)]">+ <label for="isAdmin" class="ml-2 text-sm text-[var(--text-secondary)]">Admin User</label>+ </div>+ <div class="flex justify-end space-x-3">+ <button type="button" @click="showAddUserModal = false" class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">Cancel</button>+ <button type="submit" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">Add User</button>+ </div>+ </form>+ </div>+ </div>++ <!-- Edit User Modal -->+ <div v-if="showEditUserModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">+ <div class="flex justify-between items-center mb-4">+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Edit User</h3>+ <button @click="showEditUserModal = false" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">×</button>+ </div>+ <form @submit.prevent="updateUser">+ <div class="mb-4">+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Username</label>+ <input v-model="editingUser.username" type="text" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">+ </div>+ <div class="mb-4">+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Email</label>+ <input v-model="editingUser.email" type="email" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">+ </div>+ <div class="mb-4">+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">New Password (leave blank to keep current)</label>+ <input v-model="editingUser.password" type="password" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">+ </div>+ <div class="mb-4 flex items-center">+ <input v-model="editingUser.is_admin" type="checkbox" id="editIsAdmin" class="rounded border-[var(--border-secondary)] text-[var(--text-accent)] focus:ring-[var(--border-focus)]">+ <label for="editIsAdmin" class="ml-2 text-sm text-[var(--text-secondary)]">Admin User</label>+ </div>+ <div class="flex justify-end space-x-3">+ <button type="button" @click="showEditUserModal = false" class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">Cancel</button>+ <button type="submit" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">Update User</button>+ </div>+ </form>+ </div>+ </div>++ <!-- Delete User Confirmation Modal -->+ <div v-if="showDeleteUserModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">+ <div class="flex justify-between items-center mb-4">+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Confirm Delete</h3>+ <button @click="showDeleteUserModal = false" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">×</button>+ </div>+ <p class="mb-4 text-[var(--text-secondary)]">Are you sure you want to delete the user <span class="font-semibold">${ userToDelete?.username }</span>? This action cannot be undone.</p>+ <div class="flex justify-end space-x-3">+ <button @click="showDeleteUserModal = false" class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">Cancel</button>+ <button @click="deleteUser" class="px-4 py-2 bg-[var(--bg-danger)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-danger-hover)]">Delete User</button>+ </div>+ </div>+ </div>+ </div>++ <script>+ const { createApp, ref, computed, onMounted, watch } = Vue++ createApp({+ setup() {+ // State+ const activeTab = ref('users');+ const users = ref([]);+ const stats = ref({+ total_users: 0,+ total_recordings: 0,+ total_storage: 0,+ total_queries: 0,+ completed_recordings: 0,+ processing_recordings: 0,+ pending_recordings: 0,+ failed_recordings: 0,+ top_users: []+ });+ const isLoadingUsers = ref(true);+ const userSearchQuery = ref('');+ const isDarkMode = ref(false);+ const isDropdownOpen = ref(false);++ // Modal state+ const showAddUserModal = ref(false);+ const showEditUserModal = ref(false);+ const showDeleteUserModal = ref(false);+ const newUser = ref({+ username: '',+ email: '',+ password: '',+ confirmPassword: '',+ isAdmin: false+ });+ const editingUser = ref(null);+ const userToDelete = ref(null);++ // Computed properties+ const filteredUsers = computed(() => {+ if (!userSearchQuery.value) return users.value;++ const query = userSearchQuery.value.toLowerCase();+ return users.value.filter(user =>+ user.username.toLowerCase().includes(query) ||+ user.email.toLowerCase().includes(query)+ );+ });++ // Methods+ const loadUsers = async () => {+ isLoadingUsers.value = true;+ try {+ const response = await fetch('/admin/users');+ if (!response.ok) throw new Error('Failed to load users');++ const data = await response.json();+ users.value = data;+ } catch (error) {+ console.error('Error loading users:', error);+ // Show error notification+ } finally {+ isLoadingUsers.value = false;+ }+ };++ const loadStats = async () => {+ try {+ const response = await fetch('/admin/stats');+ if (!response.ok) throw new Error('Failed to load statistics');++ const data = await response.json();+ stats.value = data;+ } catch (error) {+ console.error('Error loading statistics:', error);+ // Show error notification+ }+ };++ const addUser = async () => {+ if (newUser.value.password !== newUser.value.confirmPassword) {+ alert('Passwords do not match');+ return;+ }++ try {+ const response = await fetch('/admin/users', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify({+ username: newUser.value.username,+ email: newUser.value.email,+ password: newUser.value.password,+ is_admin: newUser.value.isAdmin+ })+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || 'Failed to add user');+ }++ // Reset form and close modal+ newUser.value = {+ username: '',+ email: '',+ password: '',+ confirmPassword: '',+ isAdmin: false+ };+ showAddUserModal.value = false;++ // Reload users+ await loadUsers();+ await loadStats();++ } catch (error) {+ console.error('Error adding user:', error);+ alert(error.message);+ }+ };++ const editUser = (user) => {+ editingUser.value = { ...user, password: '' };+ showEditUserModal.value = true;+ };++ const updateUser = async () => {+ try {+ const payload = {+ username: editingUser.value.username,+ email: editingUser.value.email,+ is_admin: editingUser.value.is_admin+ };++ // Only include password if it was changed+ if (editingUser.value.password) {+ payload.password = editingUser.value.password;+ }++ const response = await fetch(`/admin/users/${editingUser.value.id}`, {+ method: 'PUT',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify(payload)+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || 'Failed to update user');+ }++ // Close modal and reload users+ showEditUserModal.value = false;+ await loadUsers();++ } catch (error) {+ console.error('Error updating user:', error);+ alert(error.message);+ }+ };++ const confirmDeleteUser = (user) => {+ userToDelete.value = user;+ showDeleteUserModal.value = true;+ };++ const deleteUser = async () => {+ try {+ const response = await fetch(`/admin/users/${userToDelete.value.id}`, {+ method: 'DELETE'+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || 'Failed to delete user');+ }++ // Close modal and reload users+ showDeleteUserModal.value = false;+ await loadUsers();+ await loadStats();++ } catch (error) {+ console.error('Error deleting user:', error);+ alert(error.message);+ }+ };++ const toggleAdminStatus = async (user) => {+ try {+ const response = await fetch(`/admin/users/${user.id}/toggle-admin`, {+ method: 'POST'+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.error || 'Failed to toggle admin status');+ }++ // Reload users+ await loadUsers();++ } catch (error) {+ console.error('Error toggling admin status:', error);+ alert(error.message);+ }+ };++ const formatFileSize = (bytes) => {+ if (!bytes || bytes === 0) return '0 Bytes';++ const k = 1024;+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];+ const i = Math.floor(Math.log(bytes) / Math.log(k));++ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];+ };++ const toggleDarkMode = () => {+ isDarkMode.value = !isDarkMode.value;+ if (isDarkMode.value) {+ document.documentElement.classList.add('dark');+ localStorage.setItem('darkMode', 'true');+ } else {+ document.documentElement.classList.remove('dark');+ localStorage.setItem('darkMode', 'false');+ }+ };++ // Initialize dark mode+ const initializeDarkMode = () => {+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;+ const savedMode = localStorage.getItem('darkMode');++ if (savedMode === 'true' || (savedMode === null && prefersDark)) {+ isDarkMode.value = true;+ document.documentElement.classList.add('dark');+ } else {+ isDarkMode.value = false;+ document.documentElement.classList.remove('dark');+ }+ };++ // Lifecycle hooks+ onMounted(() => {+ loadUsers();+ loadStats();+ initializeDarkMode();+ });++ // Watch for tab changes to reload data+ watch(activeTab, (newTab) => {+ if (newTab === 'users') {+ loadUsers();+ } else if (newTab === 'stats') {+ loadStats();+ }+ });++ return {+ // State+ activeTab,+ users,+ stats,+ isLoadingUsers,+ userSearchQuery,+ isDarkMode,+ isDropdownOpen,++ // Modal state+ showAddUserModal,+ showEditUserModal,+ showDeleteUserModal,+ newUser,+ editingUser,+ userToDelete,++ // Computed+ filteredUsers,++ // Methods+ loadUsers,+ loadStats,+ addUser,+ editUser,+ updateUser,+ confirmDeleteUser,+ deleteUser,+ toggleAdminStatus,+ formatFileSize,+ toggleDarkMode+ };+ },+ delimiters: ['${', '}'] // Use different delimiters to avoid conflict with Flask's Jinja2+ }).mount('#app');+ </script>+</body>+</html>diff --git a/templates/index.html b/templates/index.htmlindex c4ff8337..599c8443 100644--- a/templates/index.html+++ b/templates/index.html@@ -368,10 +368,11 @@<button @click="toggleDarkMode" class="p-2 rounded-full text-[var(--text-muted)] hover:bg-[var(--bg-tertiary)] dark:text-gray-400 dark:hover:bg-gray-700 transition-colors duration-200" :title="isDarkMode ? 'Switch to Light Mode' : 'Switch to Dark Mode'"><i :class="isDarkMode ? 'fas fa-sun' : 'fas fa-moon'"></i></button>+ {% if current_user.is_authenticated %}<button @click="switchToUploadView" class="px-4 py-2 mr-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg shadow hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out"><i class="fas fa-plus mr-1"></i> New Recording</button>- <button+ <button@click="switchToGalleryView":class="{'bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)]': currentView !== 'gallery',@@ -380,6 +381,35 @@class="px-4 py-2 rounded-lg shadow-sm hover:bg-[var(--bg-tertiary)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-1 transition duration-150 ease-in-out"><i class="fas fa-images mr-1"></i> Gallery</button>+ <!-- User dropdown menu -->+ <div class="relative ml-2" @click.away="isUserMenuOpen = false">+ <button @click="isUserMenuOpen = !isUserMenuOpen" class="flex items-center px-3 py-2 border border-[var(--border-secondary)] rounded-lg text-[var(--text-secondary)] hover:text-[var(--text-accent)] focus:outline-none">+ <i class="fas fa-user mr-2"></i>+ <span>{{ current_user.username }}</span>+ <i class="fas fa-chevron-down ml-2"></i>+ </button>+ <div v-show="isUserMenuOpen" class="absolute right-0 mt-2 w-48 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg z-10">+ <a href="{{ url_for('account') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">+ <i class="fas fa-user-circle mr-2"></i> Account+ </a>+ {% if current_user.is_admin %}+ <a href="{{ url_for('admin') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">+ <i class="fas fa-user-shield mr-2"></i> Admin+ </a>+ {% endif %}+ <a href="{{ url_for('logout') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-danger)]">+ <i class="fas fa-sign-out-alt mr-2"></i> Logout+ </a>+ </div>+ </div>+ {% else %}+ <a href="{{ url_for('login') }}" class="px-4 py-2 ml-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg shadow hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out">+ <i class="fas fa-sign-in-alt mr-1"></i> Login+ </a>+ <a href="{{ url_for('register') }}" class="px-4 py-2 ml-2 text-[var(--text-secondary)] hover:text-[var(--text-accent)] border border-[var(--border-secondary)] rounded-lg">+ <i class="fas fa-user-plus mr-1"></i> Register+ </a>+ {% endif %}</div></header>@@ -407,6 +437,7 @@</div></div>+ {% if current_user.is_authenticated %}<div v-if="currentView === 'gallery'" class="flex-grow flex flex-col rounded-lg relative"><!-- Sidebar toggle button that appears when sidebar is collapsed - positioned at the left edge of main content, aligned with title --><button v-if="isSidebarCollapsed"@@ -688,7 +719,26 @@</div></div>- </main>+ {% else %}+ <div class="flex-grow flex items-center justify-center">+ <div class="text-center max-w-lg p-8 bg-[var(--bg-secondary)] rounded-xl shadow-lg border border-[var(--border-primary)]">+ <i class="fas fa-lock text-5xl mb-4 text-[var(--text-accent)]"></i>+ <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-4">Welcome to Speakr</h2>+ <p class="text-[var(--text-secondary)] mb-6">+ Speakr is an audio transcription and summarization app that helps you convert your audio recordings into text and generate summaries.+ </p>+ <div class="flex flex-col sm:flex-row justify-center space-y-3 sm:space-y-0 sm:space-x-4">+ <a href="{{ url_for('login') }}" class="px-6 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg shadow hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] focus:ring-offset-2 transition duration-150 ease-in-out">+ <i class="fas fa-sign-in-alt mr-2"></i> Login+ </a>+ <a href="{{ url_for('register') }}" class="px-6 py-2 text-[var(--text-secondary)] hover:text-[var(--text-accent)] border border-[var(--border-secondary)] rounded-lg">+ <i class="fas fa-user-plus mr-2"></i> Register+ </a>+ </div>+ </div>+ </div>+ {% endif %}+ </main><footer class="text-center py-4 mt-8 text-xs text-[var(--text-light)] border-t border-[var(--border-primary)]">Speakr © ${ new Date().getFullYear() }@@ -837,6 +887,7 @@const maxFileSizeMB = ref(250); // Default, could fetch from config if neededconst isDarkMode = ref(false); // Dark mode stateconst isSidebarCollapsed = ref(false); // Sidebar state+ const isUserMenuOpen = ref(false); // User dropdown menu state// Inline editing stateconst editingParticipants = ref(false);@@ -1756,6 +1807,8 @@toggleEditParticipants, toggleEditMeetingDate, toggleEditSummary, toggleEditNotes, saveInlineEdit,// Chat MethodssendChatMessage, copyMessage, copyTranscription,+ // User menu+ isUserMenuOpen,}},delimiters: ['${', '}'] // Keep Vue delimiters distinct from Flask's Jinjadiff --git a/templates/login.html b/templates/login.htmlnew file mode 100644index 00000000..08bf54c0--- /dev/null+++ b/templates/login.html@@ -0,0 +1,173 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>{{ title }} - Speakr</title>+ <script src="https://cdn.tailwindcss.com"></script>+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">+ <style>+ /* Dark Mode CSS Variables */+ :root {+ /* Light mode variables */+ --bg-primary: #f3f4f6; /* gray-100 */+ --bg-secondary: #ffffff; /* white */+ --bg-tertiary: #f9fafb; /* gray-50 */+ --bg-accent: #dbeafe; /* blue-100 */+ --bg-accent-hover: #bfdbfe; /* blue-200 */+ --bg-button: #2563eb; /* blue-600 */+ --bg-button-hover: #1d4ed8; /* blue-700 */+ --bg-danger: #dc2626; /* red-600 */+ --bg-danger-hover: #b91c1c; /* red-700 */+ --bg-danger-light: #fee2e2; /* red-100 */+ --bg-info-light: #dbeafe; /* blue-100 */+ --bg-warn-light: #fef3c7; /* amber-100 */+ --bg-success-light: #d1fae5; /* green-100 */+ --bg-pending-light: #f5f5f4; /* stone-100 */+ --bg-input: #ffffff; /* white */++ --text-primary: #1f2937; /* gray-800 */+ --text-secondary: #374151; /* gray-700 */+ --text-muted: #6b7280; /* gray-500 */+ --text-light: #9ca3af; /* gray-400 */+ --text-accent: #1d4ed8; /* blue-700 */+ --text-button: #ffffff; /* white */+ --text-danger: #b91c1c; /* red-700 */+ --text-danger-strong: #991b1b; /* red-800 */+ --text-info-strong: #1e40af; /* blue-800 */+ --text-warn-strong: #92400e; /* amber-800 */+ --text-success-strong: #065f46; /* green-800 */+ --text-pending-strong: #44403c; /* stone-700 */++ --border-primary: #e5e7eb; /* gray-200 */+ --border-secondary: #d1d5db; /* gray-300 */+ --border-accent: #93c5fd; /* blue-300 */+ --border-danger: #f87171; /* red-400 */+ --border-focus: #3b82f6; /* blue-500 */+ --ring-focus: #bfdbfe; /* blue-200 */+ }++ .dark {+ /* Dark mode variables */+ --bg-primary: #111827; /* gray-900 */+ --bg-secondary: #1f2937; /* gray-800 */+ --bg-tertiary: #374151; /* gray-700 */+ --bg-accent: #1e3a8a; /* blue-900 */+ --bg-accent-hover: #1e40af; /* blue-800 */+ --bg-button: #2563eb; /* blue-600 */+ --bg-button-hover: #3b82f6; /* blue-500 */+ --bg-danger: #dc2626; /* red-600 */+ --bg-danger-hover: #ef4444; /* red-500 */+ --bg-danger-light: #7f1d1d; /* red-900 */+ --bg-info-light: #1e3a8a; /* blue-900 */+ --bg-warn-light: #78350f; /* amber-900 */+ --bg-success-light: #064e3b; /* green-900 */+ --bg-pending-light: #292524; /* stone-800 */+ --bg-input: #374151; /* gray-700 */++ --text-primary: #f3f4f6; /* gray-100 */+ --text-secondary: #d1d5db; /* gray-300 */+ --text-muted: #9ca3af; /* gray-400 */+ --text-light: #6b7280; /* gray-500 */+ --text-accent: #60a5fa; /* blue-400 */+ --text-button: #ffffff; /* white */+ --text-danger: #f87171; /* red-400 */+ --text-danger-strong: #fca5a5; /* red-300 */+ --text-info-strong: #93c5fd; /* blue-300 */+ --text-warn-strong: #fcd34d; /* amber-300 */+ --text-success-strong: #6ee7b7; /* green-300 */+ --text-pending-strong: #d6d3d1; /* stone-300 */++ --border-primary: #374151; /* gray-700 */+ --border-secondary: #4b5563; /* gray-600 */+ --border-accent: #1d4ed8; /* blue-700 */+ --border-danger: #ef4444; /* red-500 */+ --border-focus: #3b82f6; /* blue-500 */+ --ring-focus: #1e40af; /* blue-800 */+ }++ html {+ background-color: var(--bg-primary);+ color: var(--text-primary);+ transition: background-color 0.3s, color 0.3s;+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;+ }+ html, body { height: 100%; margin: 0; }+ </style>+</head>+<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">+ <div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">+ <header class="flex justify-between items-center mb-6 pb-4 border-b border-[var(--border-primary)]">+ <h1 class="text-3xl font-bold text-[var(--text-primary)]">+ <a href="{{ url_for('index') }}">Speakr</a>+ </h1>+ </header>++ <main class="flex-grow flex items-center justify-center">+ <div class="w-full max-w-md bg-[var(--bg-secondary)] p-8 rounded-xl shadow-lg border border-[var(--border-primary)]">+ <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6 text-center">Login</h2>++ {% with messages = get_flashed_messages(with_categories=true) %}+ {% if messages %}+ {% for category, message in messages %}+ <div class="mb-4 p-3 rounded-lg {% if category == 'success' %}bg-[var(--bg-success-light)] text-[var(--text-success-strong)]{% elif category == 'danger' %}bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]{% else %}bg-[var(--bg-info-light)] text-[var(--text-info-strong)]{% endif %}">+ {{ message }}+ </div>+ {% endfor %}+ {% endif %}+ {% endwith %}++ <form method="POST" action="{{ url_for('login') }}">+ {{ form.hidden_tag() }}++ <div class="mb-4">+ {{ form.email.label(class="block text-sm font-medium text-[var(--text-secondary)] mb-1") }}+ {% if form.email.errors %}+ {{ form.email(class="mt-1 block w-full rounded-md border-[var(--border-danger)] shadow-sm focus:border-[var(--border-focus)] focus:ring-[var(--ring-focus)] focus:ring-opacity-50 bg-[var(--bg-input)] text-[var(--text-primary)]") }}+ <div class="text-[var(--text-danger)] text-xs mt-1">+ {% for error in form.email.errors %}+ <span>{{ error }}</span>+ {% endfor %}+ </div>+ {% else %}+ {{ form.email(class="mt-1 block w-full rounded-md border-[var(--border-secondary)] shadow-sm focus:border-[var(--border-focus)] focus:ring-[var(--ring-focus)] focus:ring-opacity-50 bg-[var(--bg-input)] text-[var(--text-primary)]") }}+ {% endif %}+ </div>++ <div class="mb-6">+ {{ form.password.label(class="block text-sm font-medium text-[var(--text-secondary)] mb-1") }}+ {% if form.password.errors %}+ {{ form.password(class="mt-1 block w-full rounded-md border-[var(--border-danger)] shadow-sm focus:border-[var(--border-focus)] focus:ring-[var(--ring-focus)] focus:ring-opacity-50 bg-[var(--bg-input)] text-[var(--text-primary)]") }}+ <div class="text-[var(--text-danger)] text-xs mt-1">+ {% for error in form.password.errors %}+ <span>{{ error }}</span>+ {% endfor %}+ </div>+ {% else %}+ {{ form.password(class="mt-1 block w-full rounded-md border-[var(--border-secondary)] shadow-sm focus:border-[var(--border-focus)] focus:ring-[var(--ring-focus)] focus:ring-opacity-50 bg-[var(--bg-input)] text-[var(--text-primary)]") }}+ {% endif %}+ </div>++ <div class="flex items-center mb-6">+ {{ form.remember(class="h-4 w-4 text-[var(--text-accent)] focus:ring-[var(--ring-focus)] border-[var(--border-secondary)] rounded") }}+ {{ form.remember.label(class="ml-2 block text-sm text-[var(--text-secondary)]") }}+ </div>++ <div class="flex flex-col space-y-4">+ {{ form.submit(class="w-full py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-[var(--text-button)] bg-[var(--bg-button)] hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)]") }}++ <div class="text-center text-sm text-[var(--text-muted)]">+ <span>Don't have an account?</span>+ <a href="{{ url_for('register') }}" class="font-medium text-[var(--text-accent)] hover:underline">Register here</a>+ </div>+ </div>+ </form>+ </div>+ </main>++ <footer class="text-center py-4 mt-8 text-xs text-[var(--text-light)] border-t border-[var(--border-primary)]">+ Speakr © {{ now.year }}+ </footer>+ </div>+</body>+</html>diff --git a/templates/register.html b/templates/register.htmlnew file mode 100644index 00000000..95692c70--- /dev/null+++ b/templates/register.html@@ -0,0 +1,197 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>{{ title }} - Speakr</title>+ <script src="https://cdn.tailwindcss.com"></script>+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">+ <style>+ /* Dark Mode CSS Variables */+ :root {+ /* Light mode variables */+ --bg-primary: #f3f4f6; /* gray-100 */+ --bg-secondary: #ffffff; /* white */+ --bg-tertiary: #f9fafb; /* gray-50 */+ --bg-accent: #dbeafe; /* blue-100 */+ --bg-accent-hover: #bfdbfe; /* blue-200 */+ --bg-button: #2563eb; /* blue-600 */+ --bg-button-hover: #1d4ed8; /* blue-700 */+ --bg-danger: #dc2626; /* red-600 */+ --bg-danger-hover: #b91c1c; /* red-700 */+ --bg-danger-light: #fee2e2; /* red-100 */+ --bg-info-light: #dbeafe; /* blue-100 */+ --bg-warn-light: #fef3c7; /* amber-100 */+ --bg-success-light: #d1fae5; /* green-100 */+ --bg-pending-light: #f5f5f4; /* stone-100 */+ --bg-input: #ffffff; /* white */++ --text-primary: #1f2937; /* gray-800 */+ --text-secondary: #374151; /* gray-700 */+ --text-muted: #6b7280; /* gray-500 */+ --text-light: #9ca3af; /* gray-400 */+ --text-accent: #1d4ed8; /* blue-700 */+ --text-button: #ffffff; /* white */+ --text-danger: #b91c1c; /* red-700 */+ --text-danger-strong: #991b1b; /* red-800 */+ --text-info-strong: #1e40af; /* blue-800 */+ --text-warn-strong: #92400e; /* amber-800 */+ --text-success-strong: #065f46; /* green-800 */+ --text-pending-strong: #44403c; /* stone-700 */++ --border-primary: #e5e7eb; /* gray-200 */+ --border-secondary: #d1d5db; /* gray-300 */+ --border-accent: #93c5fd; /* blue-300 */+ --border-danger: #f87171; /* red-400 */+ --border-focus: #3b82f6; /* blue-500 */+ --ring-focus: #bfdbfe; /* blue-200 */+ }++ .dark {+ /* Dark mode variables */+ --bg-primary: #111827; /* gray-900 */+ --bg-secondary: #1f2937; /* gray-800 */+ --bg-tertiary: #374151; /* gray-700 */+ --bg-accent: #1e3a8a; /* blue-900 */+ --bg-accent-hover: #1e40af; /* blue-800 */+ --bg-button: #2563eb; /* blue-600 */+ --bg-button-hover: #3b82f6; /* blue-500 */+ --bg-danger: #dc2626; /* red-600 */+ --bg-danger-hover: #ef4444; /* red-500 */+ --bg-danger-light: #7f1d1d; /* red-900 */+ --bg-info-light: #1e3a8a; /* blue-900 */+ --bg-warn-light: #78350f; /* amber-900 */+ --bg-success-light: #064e3b; /* green-900 */+ --bg-pending-light: #292524; /* stone-800 */+ --bg-input: #374151; /* gray-700 */++ --text-primary: #f3f4f6; /* gray-100 */+ --text-secondary: #d1d5db; /* gray-300 */+ --text-muted: #9ca3af; /* gray-400 */+ --text-light: #6b7280; /* gray-500 */+ --text-accent: #60a5fa; /* blue-400 */+ --text-button: #ffffff; /* white */+ --text-danger: #f87171; /* red-400 */+ --text-danger-strong: #fca5a5; /* red-300 */+ --text-info-strong: #93c5fd; /* blue-300 */+ --text-warn-strong: #fcd34d; /* amber-300 */+ --text-success-strong: #6ee7b7; /* green-300 */+ --text-pending-strong: #d6d3d1; /* stone-300 */++ --border-primary: #374151; /* gray-700 */+ --border-secondary: #4b5563; /* gray-600 */+ --border-accent: #1d4ed8; /* blue-700 */+ --border-danger: #ef4444; /* red-500 */+ --border-focus: #3b82f6; /* blue-500 */+ --ring-focus: #1e40af; /* blue-800 */+ }++ html {+ background-color: var(--bg-primary);+ color: var(--text-primary);+ transition: background-color 0.3s, color 0.3s;+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;+ }+ html, body { height: 100%; margin: 0; }+ </style>+</head>+<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">+ <div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">+ <header class="flex justify-between items-center mb-6 pb-4 border-b border-[var(--border-primary)]">+ <h1 class="text-3xl font-bold text-[var(--text-primary)]">+ <a href="{{ url_for('index') }}">Speakr</a>+ </h1>+ </header>++ <main class="flex-grow flex items-center justify-center">+ <div class="w-full max-w-md bg-[var(--bg-secondary)] p-8 rounded-xl shadow-lg border border-[var(--border-primary)]">+ <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6 text-center">Create an Account</h2>++ {% with messages = get_flashed_messages(with_categories=true) %}+ {% if messages %}+ {% for category, message in messages %}+ <div class="mb-4 p-3 rounded-lg {% if category == 'success' %}bg-[var(--bg-success-light)] text-[var(--text-success-strong)]{% elif category == 'danger' %}bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]{% else %}bg-[var(--bg-info-light)] text-[var(--text-info-strong)]{% endif %}">+ {{ message }}+ </div>+ {% endfor %}+ {% endif %}+ {% endwith %}++ <form method="POST" action="{{ url_for('register') }}">+ {{ form.hidden_tag() }}++ <div class="mb-4">+ {{ form.username.label(class="block text-sm font-medium text-[var(--text-secondary)] mb-1") }}+ {% if form.username.errors %}+ {{ form.username(class="mt-1 block w-full rounded-md border-[var(--border-danger)] shadow-sm focus:border-[var(--border-focus)] focus:ring-[var(--ring-focus)] focus:ring-opacity-50 bg-[var(--bg-input)] text-[var(--text-primary)]") }}+ <div class="text-[var(--text-danger)] text-xs mt-1">+ {% for error in form.username.errors %}+ <span>{{ error }}</span>+ {% endfor %}+ </div>+ {% else %}+ {{ form.username(class="mt-1 block w-full rounded-md border-[var(--border-secondary)] shadow-sm focus:border-[var(--border-focus)] focus:ring-[var(--ring-focus)] focus:ring-opacity-50 bg-[var(--bg-input)] text-[var(--text-primary)]") }}+ {% endif %}+ </div>++ <div class="mb-4">+ {{ form.email.label(class="block text-sm font-medium text-[var(--text-secondary)] mb-1") }}+ {% if form.email.errors %}+ {{ form.email(class="mt-1 block w-full rounded-md border-[var(--border-danger)] shadow-sm focus:border-[var(--border-focus)] focus:ring-[var(--ring-focus)] focus:ring-opacity-50 bg-[var(--bg-input)] text-[var(--text-primary)]") }}+ <div class="text-[var(--text-danger)] text-xs mt-1">+ {% for error in form.email.errors %}+ <span>{{ error }}</span>+ {% endfor %}+ </div>+ {% else %}+ {{ form.email(class="mt-1 block w-full rounded-md border-[var(--border-secondary)] shadow-sm focus:border-[var(--border-focus)] focus:ring-[var(--ring-focus)] focus:ring-opacity-50 bg-[var(--bg-input)] text-[var(--text-primary)]") }}+ {% endif %}+ </div>++ <div class="mb-4">+ {{ form.password.label(class="block text-sm font-medium text-[var(--text-secondary)] mb-1") }}+ {% if form.password.errors %}+ {{ form.password(class="mt-1 block w-full rounded-md border-[var(--border-danger)] shadow-sm focus:border-[var(--border-focus)] focus:ring-[var(--ring-focus)] focus:ring-opacity-50 bg-[var(--bg-input)] text-[var(--text-primary)]") }}+ <div class="text-[var(--text-danger)] text-xs mt-1">+ {% for error in form.password.errors %}+ <span>{{ error }}</span>+ {% endfor %}+ </div>+ {% else %}+ {{ form.password(class="mt-1 block w-full rounded-md border-[var(--border-secondary)] shadow-sm focus:border-[var(--border-focus)] focus:ring-[var(--ring-focus)] focus:ring-opacity-50 bg-[var(--bg-input)] text-[var(--text-primary)]") }}+ {% endif %}+ <p class="text-xs text-[var(--text-muted)] mt-1">Password must be at least 8 characters long.</p>+ </div>++ <div class="mb-6">+ {{ form.confirm_password.label(class="block text-sm font-medium text-[var(--text-secondary)] mb-1") }}+ {% if form.confirm_password.errors %}+ {{ form.confirm_password(class="mt-1 block w-full rounded-md border-[var(--border-danger)] shadow-sm focus:border-[var(--border-focus)] focus:ring-[var(--ring-focus)] focus:ring-opacity-50 bg-[var(--bg-input)] text-[var(--text-primary)]") }}+ <div class="text-[var(--text-danger)] text-xs mt-1">+ {% for error in form.confirm_password.errors %}+ <span>{{ error }}</span>+ {% endfor %}+ </div>+ {% else %}+ {{ form.confirm_password(class="mt-1 block w-full rounded-md border-[var(--border-secondary)] shadow-sm focus:border-[var(--border-focus)] focus:ring-[var(--ring-focus)] focus:ring-opacity-50 bg-[var(--bg-input)] text-[var(--text-primary)]") }}+ {% endif %}+ </div>++ <div class="flex flex-col space-y-4">+ {{ form.submit(class="w-full py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-[var(--text-button)] bg-[var(--bg-button)] hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)]") }}++ <div class="text-center text-sm text-[var(--text-muted)]">+ <span>Already have an account?</span>+ <a href="{{ url_for('login') }}" class="font-medium text-[var(--text-accent)] hover:underline">Login here</a>+ </div>+ </div>+ </form>+ </div>+ </main>++ <footer class="text-center py-4 mt-8 text-xs text-[var(--text-light)] border-t border-[var(--border-primary)]">+ Speakr © {{ now.year }}+ </footer>+ </div>+</body>+</html>