File size: 8,081 Bytes
8beb2b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
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)