-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·217 lines (178 loc) · 6.71 KB
/
app.py
File metadata and controls
executable file
·217 lines (178 loc) · 6.71 KB
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
#!/bin/env python3
import os
import time
import json
import random
import threading
import hashlib
import math
from flask import Flask, request, jsonify, send_from_directory
from flask_sock import Sock
import requests
# --- Basic Setup ---
app = Flask(__name__)
sock = Sock(app)
OLLAMA_API_URL = 'http://localhost:11434'
DB_FILE = 'database.json'
# --- JSON Database (CRUD) ---
db_lock = threading.Lock()
def read_db():
"""Reads the entire database from the JSON file."""
with db_lock:
if not os.path.exists(DB_FILE):
return {}
with open(DB_FILE, 'r') as f:
return json.load(f)
def write_db(data):
"""Writes the entire database to the JSON file."""
with db_lock:
with open(DB_FILE, 'w') as f:
json.dump(data, f, indent=4)
# --- Serve Frontend ---
@app.route('/')
def index():
return send_from_directory('public', 'index.html')
@app.route('/<path:path>')
def static_proxy(path):
return send_from_directory('public', path)
# --- New Validation and Hashing Endpoints ---
@app.route('/api/validation/genesis', methods=['POST'])
def set_genesis_hash():
"""Sets the initial 'genesis hash' from a given text."""
data = request.get_json()
if not data or 'text' not in data:
return jsonify({"error": "Text for genesis hash is required."}), 400
genesis_text = data['text']
genesis_hash = hashlib.sha256(genesis_text.encode()).hexdigest()
db = read_db()
db['genesis_hash'] = genesis_hash
write_db(db)
return jsonify({"message": "Genesis hash set successfully.", "genesis_hash": genesis_hash})
@app.route('/api/entropy', methods=['GET'])
def get_entropy():
"""Returns the current calculated offset-entropy."""
db = read_db()
return jsonify(db.get('offset_entropy_index', {}))
@app.route('/api/importance', methods=['GET'])
def get_importance_hashes():
"""Returns the modulated and sorted list of importance hashes."""
db = read_db()
hashes = db.get('importance_hashes', [])
# "Modulated" sorting (for demonstration, we sort alphabetically)
# A real modulation could involve numeric conversion and scaling.
sorted_hashes = sorted(hashes)
return jsonify(sorted_hashes)
# --- Enhanced Ollama API Bridge ---
@app.route('/api/ollama/generate', methods=['POST'])
def generate_ollama_response():
"""
Handles generation, including:
- "Origin-to-genesis-rehashing" security validation
- Querying Ollama
- Generating a "mindmap" from the response chunks
- Storing validation artifacts
"""
data = request.get_json()
if not data or 'model' not in data or 'prompt' not in data:
return jsonify({"error": "Model and prompt are required."}), 400
prompt = data['prompt']
db = read_db()
# 1. "Origin-to-Genesis-Rehashing" Security Validation
prompt_hash = hashlib.sha256(prompt.encode()).hexdigest()
genesis_hash = db.get('genesis_hash')
is_valid = (prompt_hash == genesis_hash) if genesis_hash else None
validation_record = {
'prompt': prompt,
'prompt_hash': prompt_hash,
'genesis_hash': genesis_hash,
'is_valid': is_valid,
'timestamp': time.time()
}
db['prompt_validations'].append(validation_record)
# Add to importance hashes
if prompt_hash not in db.get('importance_hashes', []):
db.setdefault('importance_hashes', []).append(prompt_hash)
# 2. Query Ollama
try:
ollama_response = requests.post(
f"{OLLAMA_API_URL}/api/generate",
json={"model": data['model'], "prompt": prompt, "stream": False},
timeout=60
)
ollama_response.raise_for_status()
ollama_data = ollama_response.json()
except requests.exceptions.RequestException as e:
print(f"Error bridging to Ollama API: {e}")
write_db(db) # Save validation attempt even if Ollama fails
return jsonify({"error": "Failed to get a response from Ollama API."}), 500
# 3. "Chunk Tokenize" and "Mindmap" Generation
response_text = ollama_data.get('response', '')
# Simple chunking by sentence
chunks = [p.strip() for p in response_text.split('.') if p.strip()]
mindmap = {
"id": "root",
"topic": prompt[:30] + '...',
"children": [
{"id": f"chunk-{i}", "topic": chunk} for i, chunk in enumerate(chunks)
]
}
write_db(db)
return jsonify({
"original_response": ollama_data,
"security_validation": validation_record,
"mindmap": mindmap
})
# --- WebSocket "Particle Streamline" ---
@sock.route('/websocket')
def websocket_stream(ws):
"""Handles streaming 'octal wave' data and calculates entropy."""
print("Client connected to WebSocket Particle Streamline.")
# Store recent values for entropy calculation
recent_values = []
def stream_data():
while True:
raw_val = random.random() * 256
gamma, beta = 1.2, -10.0 # Modulation factors
modulated_val = max(0, min((raw_val * gamma) + beta, 255))
# --- Entropy Calculation ---
recent_values.append(int(modulated_val))
if len(recent_values) > 100: # Sliding window of 100 values
recent_values.pop(0)
# Calculate frequency of each value
freqs = {}
for item in recent_values:
freqs[item] = freqs.get(item, 0) + 1
# Calculate Shannon entropy
entropy = 0.0
for freq in freqs.values():
prob = freq / len(recent_values)
entropy -= prob * math.log2(prob)
# Update the database
db = read_db()
db['offset_entropy_index']['current_entropy'] = entropy
write_db(db)
particle = {
'type': 'octal-wave-particle',
'timestamp': time.time(),
'octalValue': oct(int(modulated_val))[2:].zfill(3),
'amplitude': random.random(),
}
try:
ws.send(json.dumps(particle))
except Exception:
break
time.sleep(0.1)
client_thread = threading.Thread(target=stream_data)
client_thread.daemon = True
client_thread.start()
while True:
try:
message = ws.receive(timeout=1)
if message:
print(f"Received message from client: {message}")
except Exception:
break
print("Client disconnected.")
# --- Main Entry Point ---
if __name__ == '__main__':
app.run(port=3000, host='0.0.0.0', debug=False)