import os import logging from flask import Flask, render_template, request, jsonify, flash, redirect, url_for import spacy from flask_sqlalchemy import SQLAlchemy from sqlalchemy.orm import DeclarativeBase from nlp_processor import process_text from quantum_thinking import quantum_recursive_thinking from openai_integration import generate_completion # Configure logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) # Create the base class for SQLAlchemy models class Base(DeclarativeBase): pass # Initialize SQLAlchemy db = SQLAlchemy(model_class=Base) # Create Flask app app = Flask(__name__) app.secret_key = os.environ.get("SESSION_SECRET") # Configure database app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL") app.config["SQLALCHEMY_ENGINE_OPTIONS"] = { "pool_recycle": 300, "pool_pre_ping": True, } # Initialize the extensions db.init_app(app) # Import models and create database tables with app.app_context(): import models # This has to be imported after db is initialized db.create_all() # Initialize the task scheduler from task_scheduler import scheduler scheduler.start() logger.info("Database tables created and task scheduler started") # Load spaCy model (English) try: nlp = spacy.load("en_core_web_sm") logger.info("Successfully loaded spaCy English model") except OSError: logger.warning("Downloading spaCy model...") logger.warning("Please run: python -m spacy download en_core_web_sm") # Fallback: use a smaller model try: nlp = spacy.load("en") except: logger.error("Failed to load spaCy model. Using blank model.") nlp = spacy.blank("en") @app.route('/') def index(): return render_template('index.html') @app.route('/settings') def settings(): """Settings page with user preferences for the application.""" api_key = os.environ.get("OPENAI_API_KEY", "") api_key_masked = "••••••••" + api_key[-4:] if api_key else "" api_key_status = bool(api_key) ai_model = "gpt-4o" # Default to the newest model return render_template( 'settings.html', api_key_masked=api_key_masked, api_key_status=api_key_status, ai_model=ai_model ) @app.route('/zap-integrations') def zap_integrations(): integrations = [ { "name": "OpenAI Connector", "description": "Connect the quantum framework to OpenAI's GPT models", "icon": "fa-robot", "status": "active" if os.environ.get("OPENAI_API_KEY") else "inactive" }, { "name": "Language Processing Pipeline", "description": "NLP processing workflow with quantum enhancement", "icon": "fa-code-branch", "status": "active" }, { "name": "Quantum Discord Notifier", "description": "Send multi-dimensional analysis results to Discord", "icon": "fa-bell", "status": "pending" }, { "name": "JSON Export Automation", "description": "Export quantum thinking results to JSON format", "icon": "fa-file-export", "status": "active" }, { "name": "Email Summarization", "description": "Generate quantum-enhanced summaries of emails", "icon": "fa-envelope", "status": "pending" } ] return render_template('zap_integrations.html', integrations=integrations) @app.route('/automation-workflow') def automation_workflow(): workflow_steps = [ { "id": 1, "name": "Text Input", "description": "User enters text for quantum processing", "status": "completed", "color": "#da4b86" }, { "id": 2, "name": "NLP Processing", "description": "Initial language processing with spaCy", "status": "completed", "color": "#6f42c1" }, { "id": 3, "name": "Quantum Thinking", "description": "Multi-dimensional recursive thinking algorithm", "status": "active", "color": "#0dcaf0" }, { "id": 4, "name": "Pattern Recognition", "description": "Identifying patterns across quantum dimensions", "status": "pending", "color": "#6f42c1" }, { "id": 5, "name": "Response Generation", "description": "Creating AI response with quantum insights", "status": "pending", "color": "#da4b86" } ] return render_template('automation_workflow.html', workflow_steps=workflow_steps) @app.route('/process', methods=['POST']) def process(): try: input_text = request.form.get('input_text', '') if not input_text: flash('Please enter some text to process', 'warning') return redirect(url_for('index')) # Process with NLP nlp_results = process_text(nlp, input_text) # Process with quantum-inspired recursive thinking depth = int(request.form.get('depth', 3)) quantum_results = quantum_recursive_thinking(input_text, depth) # Generate OpenAI completion use_ai = request.form.get('use_ai') == 'on' ai_response = None if use_ai: try: ai_response = generate_completion(input_text, quantum_results) except Exception as e: logger.error(f"OpenAI API error: {str(e)}") flash(f"Error with OpenAI API: {str(e)}", 'danger') return render_template( 'index.html', input_text=input_text, nlp_results=nlp_results, quantum_results=quantum_results, ai_response=ai_response, depth=depth ) except Exception as e: logger.error(f"Error processing request: {str(e)}") flash(f"An error occurred: {str(e)}", 'danger') return redirect(url_for('index')) @app.route('/save-api-key', methods=['POST']) def save_api_key(): """Save OpenAI API key.""" api_key = request.form.get('api_key', '') ai_model = request.form.get('ai_model', 'gpt-4o') # For a production app, we would need to securely store this API key # For this demo, we will just flash a message if api_key: flash('API key settings updated successfully!', 'success') else: flash('API key has been cleared.', 'warning') return redirect(url_for('settings')) @app.route('/api/process', methods=['POST']) def api_process(): try: data = request.get_json() input_text = data.get('input_text', '') depth = data.get('depth', 3) use_ai = data.get('use_ai', False) if not input_text: return jsonify({'error': 'No input text provided'}), 400 # Process with NLP nlp_results = process_text(nlp, input_text) # Process with quantum-inspired recursive thinking quantum_results = quantum_recursive_thinking(input_text, depth) # Generate OpenAI completion ai_response = None if use_ai: try: ai_response = generate_completion(input_text, quantum_results) except Exception as e: logger.error(f"OpenAI API error: {str(e)}") return jsonify({'error': f'OpenAI API error: {str(e)}'}), 500 return jsonify({ 'nlp_results': nlp_results, 'quantum_results': quantum_results, 'ai_response': ai_response }) except Exception as e: logger.error(f"API Error: {str(e)}") return jsonify({'error': str(e)}), 500 if __name__ == "__main__": app.run(host="0.0.0.0", port=5000, debug=True)