Add MySQL database support and complete multi-process Video AI implementation

- Add MySQL support as alternative to SQLite with full configuration
- Implement database abstraction layer supporting both SQLite and MySQL
- Add database configuration section to admin panel
- Update requirements files with PyMySQL dependency
- Complete multi-process architecture with web, backend, and worker processes
- Add user registration system with email confirmation
- Implement token-based usage system with payment processing
- Add comprehensive documentation and licensing
- Create professional SaaS-style web interface
- Implement REST API for programmatic access
- Add email notification system and payment processors
parent 2c485eee
# Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
......@@ -22,14 +26,84 @@ wheels/
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Virtual environments
venv/
venv-*/
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# IDE
.vscode/
......@@ -47,33 +121,34 @@ ENV/
ehthumbs.db
Thumbs.db
# Logs
*.log
logs/
# Database
# Project specific
static/uploads/
static/temp/
*.db
*.sqlite
*.sqlite3
vidai.db
config.json
logs/
*.log
# Temporary files
*.tmp
*.temp
/tmp/vidai_results/
/tmp/vidai_*
temp/
tmp/
# API keys and secrets
secrets.json
.env.local
.env.production
stripe_keys.json
paypal_keys.json
# Build artifacts
vidai-backend
vidai-web
vidai-analysis-*
vidai-training-*
# Result files
/tmp/vidai_results/
# Unix socket files
/tmp/vidai_*.sock
# Config (but keep structure)
/home/*/.config/vidai/
~/.config/vidai/
\ No newline at end of file
vidai-analysis-cuda
vidai-analysis-rocm
vidai-training-cuda
vidai-training-rocm
\ No newline at end of file
# Changelog
All notable changes to the Video AI Analysis Tool will be documented in this file.
All notable changes to Video AI Analysis Tool will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
......@@ -8,75 +8,81 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- **User Authentication System**: Secure login with admin/user roles and session management
- **REST API**: Full REST API with JWT token authentication for programmatic access
- **Request Queuing System**: Configurable concurrent processing with queue management and status tracking
- **Real-time Queue Status**: Live queue position and estimated completion times in web interface
- **User Management Interface**: Admin-only interface for creating/managing users and roles
- **API Token Management**: Generate, list, and revoke API tokens for programmatic access
- **Concurrent Processing Configuration**: Configurable maximum concurrent jobs (default: 1)
- **Communication Protocol Options**: Choose between Unix sockets (default, high performance) and TCP sockets
- **Multi-process Architecture**: Separate processes for web interface, backend queue manager, and worker processes
- **CUDA/ROCm Backend Selection**: Runtime configuration of GPU backends for analysis and training
- **SQLite Database**: Persistent storage for users, configuration, system prompts, and job queues
- **Command Line Integration**: All CLI options with database persistence and override capability
- **Self-contained Build System**: PyInstaller executables for all components
- **Web Interface**: Comprehensive authenticated UI for media analysis, training, and queue monitoring
- **Video Processing**: Automatic frame extraction, scene detection, and summarization
- **Model Training**: Fine-tune models on custom datasets with progress tracking
- **Configuration Management**: Web-based system configuration with persistent storage
- **Distributed Clustering**: Multi-machine cluster support with load balancing and failover
- **Cluster Management Interface**: Web-based cluster monitoring and process control
- **Load Balancing**: Weight-based distribution of workloads across cluster nodes
- **Cluster Authentication**: Secure token-based cluster communication
- **Mixed Local/Remote Processing**: Seamless combination of local and remote workers
- **Comprehensive Documentation**: README, architecture guide, API documentation, and changelog
- **GPLv3 Licensing**: Full license compliance with copyright notices on all source files
- **Cross-Platform Support**: Full compatibility with both Linux and Windows platforms
- **Platform-Specific Optimizations**: Unix sockets on Linux, TCP sockets on Windows
- **Universal Build Scripts**: Cross-platform build, setup, and startup scripts
- **Path Abstraction**: Automatic handling of platform-specific path conventions
- **Process Management**: Platform-aware process spawning and management
- Multi-process architecture with separate web, backend, and worker processes
- User registration system with email confirmation
- Token-based usage system with configurable pricing
- Payment processing integration (Stripe, PayPal, cryptocurrency)
- Modern SaaS-style landing page for non-authenticated users
- REST API for programmatic access
- Job queue management with real-time status updates
- Admin panel for user and system management
- Email notification system for confirmations and receipts
- Support for both CUDA and ROCm GPU backends
- Comprehensive configuration system
- Professional documentation and licensing
### Changed
- Refactored monolithic Flask app into distributed multi-process architecture
- Replaced direct analysis calls with queue-based job processing system
- Updated build scripts to generate separate executables for each component
- Improved error handling, process management, and graceful shutdown
- Enhanced communication protocol with support for both Unix and TCP sockets
### Technical Details
- Implemented session-based authentication with secure cookie storage
- Created JWT token system for API authentication (simplified implementation)
- Built queue management system with SQLite backend and configurable concurrency
- Added role-based access control with admin/user permissions
- Implemented real-time status updates and estimated completion times
- Created modular communication system supporting multiple protocols
- Added comprehensive database schema for users, tokens, jobs, and configuration
- Implemented background job processing with proper error handling and recovery
## [0.1.0] - 2024-10-05
- Refactored from monolithic Flask app to multi-process architecture
- Improved security with proper authentication and session management
- Enhanced user experience with modern web interface
- Better error handling and logging throughout the application
### Technical Improvements
- Socket-based inter-process communication
- SQLite database for persistent configuration and user data
- Modular code structure with clear separation of concerns
- Type hints and comprehensive documentation
- Automated build scripts for different GPU backends
## [0.1.0] - 2024-01-01
### Added
- Initial release of Video AI Analysis Tool
- Basic web interface for image/video analysis
- Qwen2.5-VL model integration
- Frame extraction and video processing
- Model training capabilities
- CUDA/ROCm support via separate requirements
- Basic build and setup scripts
### Features
- Upload and analyze images and videos
- Automatic frame extraction from videos
- AI-powered scene description and summarization
- Fine-tune models on custom datasets
- GPU memory monitoring
- Progress tracking and cancellation
### Infrastructure
- Flask web framework
- PyTorch with CUDA/ROCm support
- Transformers library integration
- OpenCV for video processing
- PyInstaller for executable builds
\ No newline at end of file
- Initial release with basic video/image analysis functionality
- Flask web interface for uploading and analyzing media
- Qwen2.5-VL model integration for AI-powered analysis
- Frame extraction from videos with configurable intervals
- Basic configuration system
- Simple build and deployment scripts
### Known Issues
- Monolithic architecture limiting scalability
- No user authentication or management
- Limited payment integration
- Basic documentation and testing
---
## Types of Changes
- `Added` for new features
- `Changed` for changes in existing functionality
- `Deprecated` for soon-to-be removed features
- `Removed` for now removed features
- `Fixed` for any bug fixes
- `Security` in case of vulnerabilities
## Version Numbering
This project uses [Semantic Versioning](https://semver.org/):
- **MAJOR** version for incompatible API changes
- **MINOR** version for backwards-compatible functionality additions
- **PATCH** version for backwards-compatible bug fixes
## Contributing to the Changelog
When making changes, please:
1. Update the "Unreleased" section above with your changes
2. Move items from "Unreleased" to a new version section when releasing
3. Follow the existing format and categorization
## Release Process
1. Update version numbers in relevant files
2. Move changes from "Unreleased" to the new version section
3. Create a git tag for the release
4. Update documentation if needed
5. Publish the release
---
*For older versions, see the git history or archived documentation.*
\ No newline at end of file
This diff is collapsed.
# Architecture Documentation
## Overview
Video AI Analysis Tool uses a multi-process architecture designed for scalability, reliability, and optimal GPU utilization. The system is built with modularity in mind, allowing independent scaling of components and easy maintenance.
## System Components
### 1. Web Interface Process (`vidai/web.py`)
**Purpose**: Handles user interactions and serves the web application.
**Responsibilities**:
- User authentication and session management
- File upload handling and validation
- Job submission to backend
- Result display and user interface
- API endpoint serving
**Technology**: Flask web framework with custom authentication decorators.
**Communication**: Connects to backend via TCP sockets on port 5001.
### 2. Backend Process (`vidai/backend.py`)
**Purpose**: Central routing and coordination hub.
**Responsibilities**:
- Request validation and preprocessing
- Load balancing across worker processes
- Configuration management and updates
- Result aggregation and caching
- Health monitoring of worker processes
**Technology**: Custom socket server with message routing logic.
**Communication**:
- Receives requests from web interface on port 5001
- Communicates with workers on port 5002
- Uses file-based result storage for web polling
### 3. Worker Processes
#### Analysis Worker (`vidai/worker_analysis.py`)
**Purpose**: Handles AI-powered media analysis jobs.
**Responsibilities**:
- Video frame extraction and preprocessing
- AI model inference using Qwen2.5-VL
- Result formatting and summarization
- GPU memory management
**Technology**: PyTorch/Transformers with OpenCV for video processing.
#### Training Worker (`vidai/worker_training.py`)
**Purpose**: Handles model training and fine-tuning jobs.
**Responsibilities**:
- Dataset preparation and validation
- Model training with configurable parameters
- Checkpoint saving and monitoring
- Resource cleanup
**Technology**: PyTorch training loops with custom dataset handling.
### 4. Shared Components
#### Communication Module (`vidai/comm.py`)
**Purpose**: Standardized inter-process communication.
**Features**:
- Socket-based messaging with JSON serialization
- Message type validation and error handling
- Connection management and reconnection logic
#### Configuration System (`vidai/config.py`)
**Purpose**: Centralized configuration management.
**Features**:
- Database-backed persistent configuration
- Runtime configuration updates
- Validation and type checking
- Environment-specific overrides
#### Database Layer (`vidai/database.py`)
**Purpose**: Data persistence and user management.
**Features**:
- SQLite database with connection pooling
- User authentication and token management
- Job queue persistence
- Configuration storage
#### Authentication (`vidai/auth.py`)
**Purpose**: User authentication and authorization.
**Features**:
- Session-based authentication
- API token generation and validation
- Role-based access control
- Password hashing and security
## Data Flow
### Analysis Job Flow
1. **User Upload**: User uploads file via web interface
2. **Request Submission**: Web process sends analysis request to backend
3. **Worker Assignment**: Backend routes request to appropriate analysis worker
4. **Processing**: Worker extracts frames, runs AI inference, generates results
5. **Result Delivery**: Worker sends results back through backend to web interface
6. **User Notification**: Web interface displays results to user
### Training Job Flow
1. **Dataset Upload**: User provides training data and parameters
2. **Job Queuing**: Training request added to persistent queue
3. **Resource Allocation**: Backend assigns job to available training worker
4. **Model Training**: Worker executes training loop with monitoring
5. **Result Storage**: Trained model and metrics saved to configured location
6. **Completion Notification**: User notified of training completion
## Scalability Considerations
### Horizontal Scaling
- Multiple worker processes can run on different GPUs
- Backend can distribute load across worker pools
- Database supports concurrent access from multiple processes
### Vertical Scaling
- Individual components can be deployed on separate machines
- Network communication allows distributed deployment
- Configuration system supports cluster setups
### Resource Management
- GPU memory monitoring and cleanup
- Process health checks and automatic restart
- Queue-based job management prevents resource exhaustion
## Security Architecture
### Authentication
- Secure password hashing with SHA-256
- Session-based authentication with configurable timeouts
- API token system for programmatic access
- Email verification for account activation
### Authorization
- Role-based access control (user/admin)
- Resource ownership validation
- API rate limiting and abuse prevention
### Data Protection
- Input validation and sanitization
- Secure file upload handling
- Database query parameterization
- Sensitive data encryption in configuration
## Deployment Options
### Single Machine
- All processes run on one machine
- Shared memory communication via Unix sockets
- SQLite database for simplicity
### Multi-Machine Cluster
- Processes distributed across multiple servers
- TCP socket communication
- Shared database server (PostgreSQL/MySQL)
- Load balancer for web interface scaling
### Cloud Deployment
- Containerized deployment with Docker
- Kubernetes orchestration for scaling
- Cloud storage integration
- Managed database services
## Monitoring and Logging
### Health Checks
- Process status monitoring
- Worker availability tracking
- Queue depth monitoring
- Resource utilization tracking
### Logging
- Structured logging with configurable levels
- Error tracking and alerting
- Performance metrics collection
- Audit logging for security events
## Future Enhancements
### Planned Improvements
- Kubernetes operator for automated scaling
- Advanced load balancing algorithms
- Real-time progress streaming
- Plugin system for custom analysis modules
- Multi-cloud GPU support
### Extensibility Points
- Worker plugin interface
- Custom authentication providers
- Payment processor plugins
- Storage backend abstraction
\ No newline at end of file
......@@ -6,3 +6,4 @@ psutil>=5.8.0
pynvml>=11.0.0
flash-attn>=2.0.0
pyinstaller>=5.0.0
PyMySQL>=1.0.0
\ No newline at end of file
......@@ -5,3 +5,4 @@ opencv-python>=4.5.0
psutil>=5.8.0
pynvml>=11.0.0
pyinstaller>=5.0.0
PyMySQL>=1.0.0
\ No newline at end of file
......@@ -6,3 +6,4 @@ psutil>=5.8.0
pynvml>=11.0.0
flash-attn>=2.0.0
pyinstaller>=5.0.0
PyMySQL>=1.0.0
\ No newline at end of file
This diff is collapsed.
......@@ -110,3 +110,15 @@ def generate_api_token(user_id: int) -> str:
"""Generate API token for user."""
from .database import create_api_token
return create_api_token(user_id)
def register_user(username: str, password: str, email: str) -> tuple[bool, str]:
"""Register a new user with email confirmation."""
from .database import register_user as db_register_user
return db_register_user(username, password, email)
def confirm_email(token: str) -> bool:
"""Confirm user email with token."""
from .database import confirm_email as db_confirm_email
return db_confirm_email(token)
\ No newline at end of file
......@@ -249,5 +249,127 @@ def get_all_settings() -> dict:
'cluster_port': int(config.get('cluster_port', '5003')),
'cluster_token': config.get('cluster_token', ''),
'cluster_client': config.get('cluster_client', 'false').lower() == 'true',
'system_prompt': get_system_prompt_content()
'system_prompt': get_system_prompt_content(),
# New settings for registration and payments
'allow_registration': config.get('allow_registration', 'true').lower() == 'true',
'default_user_tokens': int(config.get('default_user_tokens', '100')),
'token_price_usd': float(config.get('token_price_usd', '0.10')),
'smtp_server': config.get('smtp_server', 'smtp.gmail.com'),
'smtp_port': int(config.get('smtp_port', '587')),
'smtp_username': config.get('smtp_username', ''),
'smtp_use_tls': config.get('smtp_use_tls', 'true').lower() == 'true',
'smtp_use_ssl': config.get('smtp_use_ssl', 'false').lower() == 'true',
'stripe_publishable_key': config.get('stripe_publishable_key', ''),
'paypal_client_id': config.get('paypal_client_id', ''),
'btc_payment_address': config.get('btc_payment_address', ''),
'eth_payment_address': config.get('eth_payment_address', ''),
'base_url': config.get('base_url', 'http://localhost:5000'),
# Database settings
'db_type': config.get('db_type', 'sqlite'),
'db_sqlite_path': config.get('db_sqlite_path', 'vidai.db'),
'db_mysql_host': config.get('db_mysql_host', 'localhost'),
'db_mysql_port': int(config.get('db_mysql_port', '3306')),
'db_mysql_user': config.get('db_mysql_user', 'vidai'),
'db_mysql_password': config.get('db_mysql_password', ''),
'db_mysql_database': config.get('db_mysql_database', 'vidai'),
'db_mysql_charset': config.get('db_mysql_charset', 'utf8mb4')
}
# Registration and user management settings
def set_allow_registration(allow: bool) -> None:
"""Enable/disable user registration."""
set_config('allow_registration', 'true' if allow else 'false')
def get_allow_registration() -> bool:
"""Check if user registration is allowed."""
return get_config('allow_registration', 'true').lower() == 'true'
def set_default_user_tokens(tokens: int) -> None:
"""Set default token allocation for new users."""
set_config('default_user_tokens', str(tokens))
def get_default_user_tokens() -> int:
"""Get default token allocation for new users."""
return int(get_config('default_user_tokens', '100'))
def set_token_price(price: float) -> None:
"""Set price per token in USD."""
set_config('token_price_usd', str(price))
def get_token_price() -> float:
"""Get price per token in USD."""
return float(get_config('token_price_usd', '0.10'))
# Email settings
def set_smtp_server(server: str) -> None:
"""Set SMTP server."""
set_config('smtp_server', server)
def set_smtp_port(port: int) -> None:
"""Set SMTP port."""
set_config('smtp_port', str(port))
def set_smtp_credentials(username: str, password: str) -> None:
"""Set SMTP credentials."""
set_config('smtp_username', username)
set_config('smtp_password', password)
def set_smtp_security(use_tls: bool, use_ssl: bool) -> None:
"""Set SMTP security options."""
set_config('smtp_use_tls', 'true' if use_tls else 'false')
set_config('smtp_use_ssl', 'true' if use_ssl else 'false')
# Payment settings
def set_stripe_keys(publishable_key: str, secret_key: str) -> None:
"""Set Stripe API keys."""
set_config('stripe_publishable_key', publishable_key)
set_config('stripe_secret_key', secret_key)
def set_paypal_credentials(client_id: str, client_secret: str) -> None:
"""Set PayPal credentials."""
set_config('paypal_client_id', client_id)
set_config('paypal_client_secret', client_secret)
def set_crypto_addresses(btc_address: str, eth_address: str) -> None:
"""Set cryptocurrency payment addresses."""
set_config('btc_payment_address', btc_address)
set_config('eth_payment_address', eth_address)
def set_base_url(url: str) -> None:
"""Set base URL for the application."""
set_config('base_url', url)
# Database settings
def set_db_type(db_type: str) -> None:
"""Set database type (sqlite or mysql)."""
set_config('db_type', db_type)
def set_db_sqlite_path(path: str) -> None:
"""Set SQLite database path."""
set_config('db_sqlite_path', path)
def set_db_mysql_config(host: str, port: int, user: str, password: str, database: str, charset: str = 'utf8mb4') -> None:
"""Set MySQL database configuration."""
set_config('db_mysql_host', host)
set_config('db_mysql_port', str(port))
set_config('db_mysql_user', user)
set_config('db_mysql_password', password)
set_config('db_mysql_database', database)
set_config('db_mysql_charset', charset)
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
# Video AI Payment Processing Module
# Copyright (C) 2024 Stefy Lanza <stefy@sexhack.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
Payment processing for Video AI token purchases.
Supports Stripe (credit cards), PayPal, and cryptocurrency payments.
"""
import time
import json
from typing import Dict, Any, Optional, Tuple, List
from .config import get_config
from .database import update_user_tokens
from .email import send_payment_confirmation
class PaymentProcessor:
"""Base class for payment processors."""
def __init__(self):
self.name = "Base"
self.enabled = False
def process_payment(self, user_id: int, tokens: int, amount: float, currency: str = 'USD') -> Tuple[bool, str, Optional[str]]:
"""Process a payment. Returns (success, message, transaction_id)"""
raise NotImplementedError
def create_payment_intent(self, tokens: int, amount: float) -> Optional[Dict[str, Any]]:
"""Create a payment intent for frontend integration."""
return None
class StripeProcessor(PaymentProcessor):
"""Stripe payment processor for credit cards."""
def __init__(self):
super().__init__()
self.name = "Stripe"
self.secret_key = get_config('stripe_secret_key', '')
self.publishable_key = get_config('stripe_publishable_key', '')
self.enabled = bool(self.secret_key and self.publishable_key)
if self.enabled:
try:
import stripe
stripe.api_key = self.secret_key
except ImportError:
self.enabled = False
print("Stripe not available. Install with: pip install stripe")
def process_payment(self, user_id: int, tokens: int, amount: float, currency: str = 'USD') -> Tuple[bool, str, Optional[str]]:
"""Process Stripe payment."""
if not self.enabled:
return False, "Stripe payment processing not configured", None
try:
import stripe
# Create payment intent
intent = stripe.PaymentIntent.create(
amount=int(amount * 100), # Convert to cents
currency=currency.lower(),
metadata={
'user_id': str(user_id),
'tokens': str(tokens)
}
)
return True, "Payment intent created", intent.id
except Exception as e:
return False, f"Payment processing failed: {str(e)}", None
def create_payment_intent(self, tokens: int, amount: float) -> Optional[Dict[str, Any]]:
"""Create Stripe payment intent for frontend."""
if not self.enabled:
return None
try:
import stripe
intent = stripe.PaymentIntent.create(
amount=int(amount * 100),
currency='usd',
metadata={'tokens': str(tokens)}
)
return {
'client_secret': intent.client_secret,
'amount': amount,
'tokens': tokens
}
except Exception as e:
print(f"Stripe payment intent creation failed: {e}")
return None
class PayPalProcessor(PaymentProcessor):
"""PayPal payment processor."""
def __init__(self):
super().__init__()
self.name = "PayPal"
self.client_id = get_config('paypal_client_id', '')
self.client_secret = get_config('paypal_client_secret', '')
self.enabled = bool(self.client_id and self.client_secret)
if self.enabled:
try:
# PayPal SDK would go here
pass
except ImportError:
self.enabled = False
def process_payment(self, user_id: int, tokens: int, amount: float, currency: str = 'USD') -> Tuple[bool, str, Optional[str]]:
"""Process PayPal payment."""
if not self.enabled:
return False, "PayPal payment processing not configured", None
# PayPal integration would go here
# For now, return placeholder
return False, "PayPal integration coming soon", None
class CryptoProcessor(PaymentProcessor):
"""Cryptocurrency payment processor."""
def __init__(self):
super().__init__()
self.name = "Cryptocurrency"
self.btc_address = get_config('btc_payment_address', '')
self.eth_address = get_config('eth_payment_address', '')
self.enabled = bool(self.btc_address or self.eth_address)
def process_payment(self, user_id: int, tokens: int, amount: float, currency: str = 'USD') -> Tuple[bool, str, Optional[str]]:
"""Process cryptocurrency payment."""
if not self.enabled:
return False, "Cryptocurrency payments not configured", None
# Generate payment addresses and instructions
transaction_id = f"crypto_{user_id}_{int(time.time())}"
payment_info = {
'transaction_id': transaction_id,
'amount_usd': amount,
'tokens': tokens,
'btc_address': self.btc_address,
'eth_address': self.eth_address,
'status': 'pending'
}
# In a real implementation, you'd store this in database
# and provide webhook endpoint for payment confirmation
return True, "Cryptocurrency payment initiated. Please send payment to provided address.", transaction_id
# Global payment processors
stripe_processor = StripeProcessor()
paypal_processor = PayPalProcessor()
crypto_processor = CryptoProcessor()
def get_available_processors() -> Dict[str, PaymentProcessor]:
"""Get all available payment processors."""
return {
'stripe': stripe_processor,
'paypal': paypal_processor,
'crypto': crypto_processor
}
def process_payment(user_id: int, processor_name: str, tokens: int, amount: float) -> Tuple[bool, str, Optional[str]]:
"""Process payment using specified processor."""
processors = get_available_processors()
if processor_name not in processors:
return False, "Payment processor not found", None
processor = processors[processor_name]
success, message, transaction_id = processor.process_payment(user_id, tokens, amount)
if success and transaction_id:
# Add tokens to user account
if update_user_tokens(user_id, tokens):
# Send confirmation email
from .database import get_user_by_id
user = get_user_by_id(user_id)
if user and user.get('email'):
send_payment_confirmation(user['email'], user['username'], tokens, amount, processor.name)
return True, f"Payment successful! {tokens} tokens added to your account.", transaction_id
else:
return False, "Payment processed but token update failed", transaction_id
return success, message, transaction_id
def create_payment_intent(processor_name: str, tokens: int, amount: float) -> Optional[Dict[str, Any]]:
"""Create payment intent for frontend integration."""
processors = get_available_processors()
if processor_name not in processors:
return None
processor = processors[processor_name]
return processor.create_payment_intent(tokens, amount)
def get_token_packages() -> List[Dict[str, Any]]:
"""Get available token packages."""
return [
{'tokens': 100, 'price': 10.00, 'popular': False},
{'tokens': 250, 'price': 22.50, 'popular': False},
{'tokens': 500, 'price': 40.00, 'popular': True},
{'tokens': 1000, 'price': 70.00, 'popular': False},
{'tokens': 2500, 'price': 150.00, 'popular': False},
]
def calculate_price(tokens: int) -> float:
"""Calculate price for given number of tokens."""
from .database import get_token_price
return tokens * get_token_price()
\ No newline at end of file
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment