- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
Latest commit
executable file
·217 lines (178 loc) · 6.71 KB
/
Copy pathapp.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
importos
importtime
importjson
importrandom
importthreading
importhashlib
importmath
fromflaskimportFlask, request, jsonify, send_from_directory
fromflask_sockimportSock
importrequests
# --- 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()
defread_db():
"""Reads the entire database from the JSON file."""
withdb_lock:
ifnotos.path.exists(DB_FILE):
return {}
withopen(DB_FILE, 'r') asf:
returnjson.load(f)
defwrite_db(data):
"""Writes the entire database to the JSON file."""
withdb_lock:
withopen(DB_FILE, 'w') asf:
json.dump(data, f, indent=4)
# --- Serve Frontend ---
@app.route('/')
defindex():
returnsend_from_directory('public', 'index.html')
@app.route('/<path:path>')
defstatic_proxy(path):
returnsend_from_directory('public', path)
# --- New Validation and Hashing Endpoints ---
@app.route('/api/validation/genesis', methods=['POST'])
defset_genesis_hash():
"""Sets the initial 'genesis hash' from a given text."""
data=request.get_json()
ifnotdataor'text'notindata:
returnjsonify({"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)
returnjsonify({"message": "Genesis hash set successfully.", "genesis_hash": genesis_hash})
@app.route('/api/entropy', methods=['GET'])
defget_entropy():
"""Returns the current calculated offset-entropy."""
db=read_db()
returnjsonify(db.get('offset_entropy_index', {}))
@app.route('/api/importance', methods=['GET'])
defget_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)
returnjsonify(sorted_hashes)
# --- Enhanced Ollama API Bridge ---
@app.route('/api/ollama/generate', methods=['POST'])
defgenerate_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()
ifnotdataor'model'notindataor'prompt'notindata:
returnjsonify({"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) ifgenesis_hashelseNone
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
ifprompt_hashnotindb.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()
exceptrequests.exceptions.RequestExceptionase:
print(f"Error bridging to Ollama API: {e}")
write_db(db) # Save validation attempt even if Ollama fails
returnjsonify({"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() forpinresponse_text.split('.') ifp.strip()]
mindmap= {
"id": "root",
"topic": prompt[:30] +'...',
"children": [
{"id": f"chunk-{i}", "topic": chunk} fori, chunkinenumerate(chunks)
]
}
write_db(db)
returnjsonify({
"original_response": ollama_data,
"security_validation": validation_record,
"mindmap": mindmap
})
# --- WebSocket "Particle Streamline" ---
@sock.route('/websocket')
defwebsocket_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= []
defstream_data():
whileTrue:
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))
iflen(recent_values) >100: # Sliding window of 100 values
recent_values.pop(0)
# Calculate frequency of each value
freqs= {}
foriteminrecent_values:
freqs[item] =freqs.get(item, 0) +1
# Calculate Shannon entropy
entropy=0.0
forfreqinfreqs.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))
exceptException:
break
time.sleep(0.1)
client_thread=threading.Thread(target=stream_data)
client_thread.daemon=True
client_thread.start()
whileTrue:
try:
message=ws.receive(timeout=1)
ifmessage:
print(f"Received message from client: {message}")
exceptException:
break
print("Client disconnected.")
# --- Main Entry Point ---
if__name__=='__main__':
app.run(port=3000, host='0.0.0.0', debug=False)