File size: 12,844 Bytes
68b18cf
 
 
 
 
 
 
 
 
 
 
 
 
 
e8a76c8
68b18cf
e8a76c8
b176d1c
 
 
 
 
fc56cab
b176d1c
 
fc56cab
e8a76c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc56cab
 
 
e8a76c8
 
 
fc56cab
e8a76c8
 
 
 
 
fc56cab
 
e8a76c8
fc56cab
e8a76c8
 
b176d1c
 
 
 
e8a76c8
b176d1c
 
e8a76c8
b176d1c
 
 
 
 
e8a76c8
b176d1c
 
 
 
 
 
 
 
 
e8a76c8
68b18cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c99e18
753647d
2c99e18
753647d
 
 
 
 
2c99e18
 
 
 
 
 
 
 
3c5ff56
 
 
 
 
 
d39cb8d
3c5ff56
 
 
 
 
 
 
 
fc56cab
68b18cf
 
 
fc56cab
68b18cf
fc56cab
 
 
 
 
 
 
 
 
 
68b18cf
 
 
 
 
 
 
fc56cab
 
 
 
 
e8a76c8
 
 
 
68b18cf
753647d
68b18cf
 
 
 
753647d
2c99e18
3c5ff56
 
984b04a
753647d
68b18cf
753647d
68b18cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc56cab
 
 
 
68b18cf
 
 
 
 
 
fc56cab
 
68b18cf
 
 
 
 
 
 
 
 
753647d
 
68b18cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab27fab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
"""
Builder LLM (LLM-B) β€” receives observer state and produces code patches.

The observer compresses; the builder compiles.
"""

import os
import json
import hashlib
import time
import requests
from .stream_state import SessionState, sha256_text


BUILDER_PROMPT = """You are the Builder in a Sensory Proprietary Compiler β€” a research lab system that extracts maximum value from human sensory input.

Your job is NOT to build a code assistant. Your job is NOT to build a debugging tool. Your job is to extract novel patterns from sensory data and create ML artifacts that have intellectual property value.

CRITICAL RULES β€” VIOLATION = REJECTION:
1. The CODE section MUST contain ONLY valid, executable Python code.
2. Do NOT put prose, explanations, or English text in the CODE section.
3. Do NOT put code in the EVIDENCE or REASONING sections.
4. All imports MUST be from packages available in the environment: fastapi, uvicorn, pillow, numpy, requests, openai, huggingface_hub, python-multipart, and Python stdlib (os, sys, json, math, re, collections, datetime, hashlib, time, uuid, etc.).
5. Do NOT import cv2, torch, tensorflow, pandas, matplotlib, scipy, sklearn, or any package not listed above.
6. Do NOT use input() or any interactive call β€” code must run non-interactively.

WHAT TO BUILD β€” based on available evidence:

If AUDIO FEATURES are present (dominant_freq, spectral_centroid, estimated_bpm, patterns):
  - Extract and quantify the environmental signals: AC hum frequency, mechanical rhythms, background noise patterns
  - Create feature vectors from the frequency spectrum data
  - Build pattern detectors that identify repeating cycles (e.g. AC 60Hz cycle, mechanical rotation, HVAC cycling)
  - Generate signal classification models using numpy (FFT, spectral analysis, autocorrelation)
  - Create data structures that capture the unique signature of this recording session
  - Build novelty detectors that flag when the signal pattern changes
  - Example: AC cycle analyzer that detects 60Hz/120Hz harmonics, rhythm pattern extractor, spectral fingerprint generator

If SPEECH TRANSCRIPT is present:
  - Extract semantic patterns, topic clusters, and intent signals from the transcript
  - Build text analysis tools that quantify information density, novelty, and signal-to-noise ratio
  - Create topic extraction and association mapping code
  - Generate intent classifiers that map speech to actionable patterns
  - Build evidence extraction pipelines that pull claims, timestamps, and verification markers

If CAMERA/VISUAL data is present:
  - Extract visual features: motion vectors, color distributions, frame entropy
  - Build scene change detectors and visual novelty scorers
  - Create visual pattern recognizers using numpy operations on frame data

FALLBACK LADDER β€” you are at the level indicated:

LEVEL 1 (task_code): Explicit user intent detected from speech. Generate code that does what the user asked β€” but frame it as a data extraction or pattern analysis tool, not a generic utility.

LEVEL 2 (signal_extraction): No explicit intent, but rich audio features. Generate code that:
  - Analyzes the frequency spectrum and extracts dominant patterns
  - Detects environmental rhythms (AC cycles, mechanical patterns, biological rhythms)
  - Creates a spectral fingerprint unique to this recording environment
  - Builds a pattern classifier that can distinguish this session from others
  - Produces a feature vector or data structure from the sensory input

LEVEL 3 (aesthetic_motif): Distinctive visual features but no clear intent. Generate code that:
  - Extracts aesthetic features from described visual input (color palette, light patterns)
  - Creates a visual motif or style specification from the sensory description
  - Produces a design grammar or compression of the visual state

LEVEL 4 (topic_association): Only background audio detected. Generate code that:
  - Maps detected audio patterns to potential data sources and ML applications
  - Creates a signal-to-topic association dictionary
  - Generates an environmental audio classifier or background pattern extractor
  - Builds a novelty detector for ambient sound changes

LEVEL 5 (capture_protocol): Minimal sensory signal. Generate code that:
  - Improves the capture and analysis protocol itself
  - Creates a better sampling strategy or capture diagnostic
  - Produces a session health check or signal quality report
  - Builds an adaptive sampling optimizer

Output format (use exactly these headers):

EVIDENCE:
- List specific sensory evidence. Include channel names, feature values, frequencies, patterns detected.

REASONING:
- Step by step: why this artifact should exist. Connect sensory evidence to the ML approach. What novel pattern was extracted? What is the intellectual property value of this artifact?

CODE:
```python
# ONLY executable Python code here. No prose. No explanations.
# Must pass syntax validation. Must use only installed packages.
# This code should EXTRACT PATTERNS, not build generic tools.
```

RUN:
- Exact shell command to execute the code.

TEST:
- Minimal verification step.

ATTRIBUTION:
- Which sensory evidence (frequencies, patterns, transcripts, frame hashes) triggered this code. Be specific with numerical values.
"""


def call_ollama(prompt: str) -> str:
    model = os.getenv("OLLAMA_MODEL", "llava")
    host = os.getenv("OLLAMA_HOST", "http://localhost:11434")
    payload = {"model": model, "prompt": prompt, "stream": False}
    r = requests.post(f"{host}/api/generate", json=payload, timeout=180)
    if r.status_code >= 400:
        raise RuntimeError(f"Ollama error: {r.text[:500]}")
    return r.json().get("response", "")


def call_openai(prompt: str) -> str:
    from openai import OpenAI
    model = os.getenv("OPENAI_MODEL", "gpt-4o")
    client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
    response = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": prompt}],
        max_tokens=2000,
    )
    return response.choices[0].message.content


def call_grok(prompt: str) -> str:
    """Call Groq API for code generation using llama-3.3-70b."""
    from openai import OpenAI
    client = OpenAI(
        api_key=os.getenv("GROQ_API_KEY", os.getenv("GROK_API_KEY", "")),
        base_url="https://api.groq.com/openai/v1",
    )
    model = os.getenv("GROQ_TEXT_MODEL", "llama-3.3-70b-versatile")
    response = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": prompt}],
        max_tokens=2000,
    )
    return response.choices[0].message.content


def call_hf_inference(prompt: str) -> str:
    """Call HF Inference API for code generation."""
    from huggingface_hub import InferenceClient

    token = os.getenv("HF_TOKEN") or os.getenv("HUGGING_FACE_HUB_TOKEN")
    client = InferenceClient(token=token)
    model = os.getenv("HF_TEXT_MODEL", "Qwen/Qwen2.5-7B-Instruct")
    response = client.chat_completion(
        model=model,
        messages=[{"role": "user", "content": prompt}],
        max_tokens=2000,
    )
    return response.choices[0].message.content


def build(state: SessionState, observation: dict, gate_result=None) -> dict:
    """Run builder LLM on observer output.

    Returns code patch with attribution receipt.
    Now accepts gate_result with fallback_level and feature_attribution.
    """
    fallback_level = 1
    artifact_type = "task_code"
    sensory_channels = []
    feature_attribution = {}
    if gate_result:
        fallback_level = gate_result.fallback_level
        artifact_type = gate_result.artifact_type
        sensory_channels = gate_result.sensory_channels
        feature_attribution = gate_result.feature_attribution

    prompt = f"""{BUILDER_PROMPT}

OBSERVER OUTPUT:
{observation.get('observer_output', '')}

MODE: {state.mode}

FALLBACK LEVEL: {fallback_level}
ARTIFACT TYPE: {artifact_type}
SENSORY CHANNELS: {', '.join(sensory_channels) if sensory_channels else 'none'}
FEATURE ATTRIBUTION: {json.dumps(feature_attribution, default=str)}

AUDIO FEATURES (from browser Web Audio API analysis):
{json.dumps(observation.get('audio_features', {}), indent=2, default=str) if observation.get('audio_features') else 'No audio features available β€” use transcript and visual evidence only.'}

You are at FALLBACK LEVEL {fallback_level}. Generate {artifact_type} based on the available sensory evidence. NEVER return INSUFFICIENT_EVIDENCE. Always produce a CODE section with runnable Python that EXTRACTS PATTERNS or ANALYZES SIGNALS."""

    provider = os.getenv("PROVIDER", "groq").lower().strip()
    if provider == "ollama":
        output = call_ollama(prompt)
    elif provider == "openai":
        output = call_openai(prompt)
    elif provider == "grok" or provider == "groq":
        output = call_grok(prompt)
    elif provider == "huggingface":
        output = call_hf_inference(prompt)
    elif provider == "hybrid":
        output = call_grok(prompt)
    else:
        raise RuntimeError(f"PROVIDER must be 'groq', 'hybrid', 'ollama', 'openai', or 'huggingface', got: {provider!r}.")

    # Build patch receipt
    patch_hash = sha256_text(output + str(time.time()))
    receipt = {
        "receipt_type": "PATCH_RECEIPT_V1",
        "patch_hash": patch_hash,
        "session_id": state.session_id,
        "timestamp": time.time(),
        "derived_from": {
            "frame_hashes": state.frame_hashes(),
            "audio_chunk_hashes": state.audio_chunk_hashes(),
            "speaker_segments": state.speaker_segments(),
            "observer_state_hash": observation.get("state_hash", ""),
        },
        "reason_codes": _extract_reasons(state, observation),
        "uncertainty": _extract_uncertainty(observation),
        "mode": state.mode,
        "provider": provider,
        "fallback_level": fallback_level,
        "artifact_type": artifact_type,
        "sensory_channels": sensory_channels,
        "feature_attribution": feature_attribution,
    }

    return {
        "patch_output": output,
        "patch_hash": patch_hash,
        "receipt": receipt,
        "fallback_level": fallback_level,
        "artifact_type": artifact_type,
    }


def _extract_reasons(state: SessionState, observation: dict) -> list:
    reasons = []
    if state.motion_score > 0.1:
        reasons.append(f"camera motion detected (score={state.motion_score:.3f})")
    if state.speakers.get("user", {}).get("transcript"):
        reasons.append("user speech detected")
    if state.frames and len(state.frames) > 0:
        reasons.append(f"{len(state.frames)} frames captured")
    if not reasons:
        reasons.append("automatic periodic synthesis")
    return reasons


def _extract_uncertainty(observation: dict) -> list:
    obs_text = observation.get("observer_output", "")
    uncertainties = []
    if "INSUFFICIENT" in obs_text.upper():
        uncertainties.append("observer reported insufficient evidence")
    if "diarization" in obs_text.lower():
        uncertainties.append("speaker diarization not fully available")
    if not uncertainties:
        uncertainties.append("standard uncertainty β€” verify generated code before running")
    return uncertainties


DEBUG_PROMPT = """You are the Debug Fixer in a Continuity Sensory Code Engine.

The previous code generated by the Builder failed to execute. Your job is to fix it.

Here is the failed code:
```python
{failed_code}
```

Here is the error output:
```
{error_output}
```

Original observer context:
{observer_context}

Fix the code. Return ONLY:
1. REASONING: What went wrong and why. Be specific about the error.
2. CODE: The corrected complete runnable Python code.
3. RUN: Shell command to run it.

Rules:
- Fix the actual error, don't just wrap it in try/except.
- Keep the code correlated with the original sensory evidence.
- Return complete code, not a diff.
"""


def debug_fix(failed_code: str, error_output: str, observer_context: str) -> dict:
    """Send failed code + error back to LLM for correction."""
    prompt = DEBUG_PROMPT.format(
        failed_code=failed_code,
        error_output=error_output,
        observer_context=observer_context[:2000],
    )

    provider = os.getenv("PROVIDER", "groq").lower().strip()
    if provider in ("groq", "grok", "hybrid"):
        output = call_grok(prompt)
    elif provider == "ollama":
        output = call_ollama(prompt)
    elif provider == "openai":
        output = call_openai(prompt)
    elif provider == "huggingface":
        output = call_hf_inference(prompt)
    else:
        raise RuntimeError(f"PROVIDER must be 'groq', got: {provider!r}.")

    patch_hash = sha256_text(output + str(time.time()) + "_debug")
    return {
        "patch_output": output,
        "patch_hash": patch_hash,
        "debug": True,
    }