File size: 9,656 Bytes
8c867c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
modules/persistence.py
Supabase persistence layer for IntelliForm v0.9.

Provides project storage, retrieval, and active learning feedback
across sessions. Falls back gracefully to in-memory storage when
Supabase credentials are not configured.

Supabase schema (run migrations/001_create_tables.sql to set up):

  Table: intelliform_projects
    id              uuid  PRIMARY KEY DEFAULT uuid_generate_v4()
    session_id      text  NOT NULL
    user_email      text
    created_at      timestamptz DEFAULT now()
    application     text
    blend           jsonb
    cost_per_kg     float
    bio_pct         float
    perf_score      float
    eco_score       float
    eco_grade       text
    optimizer       text
    parser          text
    relaxed         boolean
    nl_input        text

  Table: intelliform_feedback
    id              uuid  PRIMARY KEY DEFAULT uuid_generate_v4()
    session_id      text
    smiles          text
    target          text   -- 'Biodegradability' | 'Ecotoxicity' | 'Performance'
    predicted       float
    actual          float
    created_at      timestamptz DEFAULT now()

  Table: intelliform_pilot_bookings
    id              uuid  PRIMARY KEY DEFAULT uuid_generate_v4()
    session_id      text
    user_email      text
    blend           jsonb
    cost_per_kg     float
    batch_kg        int
    quote_usd       float
    application     text
    created_at      timestamptz DEFAULT now()
    status          text DEFAULT 'pending'
"""
import os
import json
from datetime import datetime
from typing import Dict, List, Optional, Any

# ── Optional Supabase import ──────────────────────────────────────────────────
try:
    from supabase import create_client, Client
    SUPABASE_OK = True
except ImportError:
    SUPABASE_OK = False

# ── In-memory fallback store ──────────────────────────────────────────────────
_MEMORY_STORE: Dict[str, List] = {
    "projects": [],
    "feedback": [],
    "bookings": [],
}


# ── Client singleton ──────────────────────────────────────────────────────────

def _get_client() -> Optional[Any]:
    if not SUPABASE_OK:
        return None
    url  = os.getenv("SUPABASE_URL", "")
    key  = os.getenv("SUPABASE_ANON_KEY", "")
    if not url or not key:
        return None
    try:
        return create_client(url, key)
    except Exception:
        return None


def is_connected() -> bool:
    """Returns True if Supabase is configured and reachable."""
    return _get_client() is not None


# ── Project storage ───────────────────────────────────────────────────────────

def save_project(project: Dict, session_id: str) -> bool:
    """
    Persist a formulation project.
    Returns True on success, False on error (never raises).
    """
    record = {
        "session_id":  session_id,
        "created_at":  datetime.utcnow().isoformat(),
        "application": project.get("application"),
        "blend":       project.get("blend", {}),
        "cost_per_kg": project.get("cost"),
        "bio_pct":     project.get("bio"),
        "perf_score":  project.get("perf"),
        "eco_score":   project.get("eco_score"),
        "eco_grade":   project.get("eco_grade"),
        "optimizer":   project.get("optimizer", "pulp"),
        "parser":      project.get("parser", "regex"),
        "relaxed":     project.get("relaxed", False),
        "nl_input":    project.get("input", ""),
    }

    client = _get_client()
    if client:
        try:
            client.table("intelliform_projects").insert(record).execute()
            return True
        except Exception as e:
            print(f"[persistence] Supabase save failed: {e}")

    # Fallback to memory
    _MEMORY_STORE["projects"].append(record)
    return False  # indicates memory fallback


def load_projects(session_id: str, limit: int = 50) -> List[Dict]:
    """
    Load projects for a session (most recent first).
    """
    client = _get_client()
    if client:
        try:
            resp = (
                client.table("intelliform_projects")
                .select("*")
                .eq("session_id", session_id)
                .order("created_at", desc=True)
                .limit(limit)
                .execute()
            )
            return resp.data or []
        except Exception as e:
            print(f"[persistence] Supabase load failed: {e}")

    # Memory fallback
    return [p for p in reversed(_MEMORY_STORE["projects"])
            if p.get("session_id") == session_id][:limit]


def load_all_projects(limit: int = 200) -> List[Dict]:
    """Load all projects across sessions (admin view)."""
    client = _get_client()
    if client:
        try:
            resp = (
                client.table("intelliform_projects")
                .select("*")
                .order("created_at", desc=True)
                .limit(limit)
                .execute()
            )
            return resp.data or []
        except Exception as e:
            print(f"[persistence] Supabase load_all failed: {e}")

    return list(reversed(_MEMORY_STORE["projects"]))[:limit]


# ── Active learning feedback ──────────────────────────────────────────────────

def save_feedback(session_id: str, smiles: str, target: str,
                  predicted: float, actual: float) -> bool:
    """Store a validated data point for QSAR active learning."""
    record = {
        "session_id": session_id,
        "smiles":     smiles,
        "target":     target,
        "predicted":  predicted,
        "actual":     actual,
        "created_at": datetime.utcnow().isoformat(),
    }
    client = _get_client()
    if client:
        try:
            client.table("intelliform_feedback").insert(record).execute()
            return True
        except Exception as e:
            print(f"[persistence] Feedback save failed: {e}")

    _MEMORY_STORE["feedback"].append(record)
    return False


def load_feedback_for_retraining() -> List[Dict]:
    """Load all validated feedback for model retraining."""
    client = _get_client()
    if client:
        try:
            resp = client.table("intelliform_feedback").select("*").execute()
            return resp.data or []
        except Exception:
            pass
    return _MEMORY_STORE["feedback"]


# ── Pilot bookings ────────────────────────────────────────────────────────────

def save_booking(session_id: str, blend: Dict, cost_per_kg: float,
                 batch_kg: int, quote_usd: float, application: str,
                 user_email: str = "") -> bool:
    """Record a pilot booking request."""
    record = {
        "session_id":  session_id,
        "user_email":  user_email,
        "blend":       blend,
        "cost_per_kg": cost_per_kg,
        "batch_kg":    batch_kg,
        "quote_usd":   quote_usd,
        "application": application,
        "created_at":  datetime.utcnow().isoformat(),
        "status":      "pending",
    }
    client = _get_client()
    if client:
        try:
            client.table("intelliform_pilot_bookings").insert(record).execute()
            return True
        except Exception as e:
            print(f"[persistence] Booking save failed: {e}")

    _MEMORY_STORE["bookings"].append(record)
    return False


# ── SQL migration helper ──────────────────────────────────────────────────────

MIGRATION_SQL = """
-- Run this in your Supabase SQL editor to set up IntelliForm tables
-- migrations/001_create_tables.sql

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE IF NOT EXISTS intelliform_projects (
    id          UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    session_id  TEXT NOT NULL,
    user_email  TEXT,
    created_at  TIMESTAMPTZ DEFAULT NOW(),
    application TEXT,
    blend       JSONB,
    cost_per_kg FLOAT,
    bio_pct     FLOAT,
    perf_score  FLOAT,
    eco_score   FLOAT,
    eco_grade   TEXT,
    optimizer   TEXT,
    parser      TEXT,
    relaxed     BOOLEAN,
    nl_input    TEXT
);

CREATE TABLE IF NOT EXISTS intelliform_feedback (
    id          UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    session_id  TEXT,
    smiles      TEXT,
    target      TEXT,
    predicted   FLOAT,
    actual      FLOAT,
    created_at  TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS intelliform_pilot_bookings (
    id          UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    session_id  TEXT,
    user_email  TEXT,
    blend       JSONB,
    cost_per_kg FLOAT,
    batch_kg    INT,
    quote_usd   FLOAT,
    application TEXT,
    created_at  TIMESTAMPTZ DEFAULT NOW(),
    status      TEXT DEFAULT 'pending'
);

-- Index for fast session lookups
CREATE INDEX IF NOT EXISTS idx_projects_session  ON intelliform_projects(session_id);
CREATE INDEX IF NOT EXISTS idx_feedback_session  ON intelliform_feedback(session_id);
CREATE INDEX IF NOT EXISTS idx_bookings_session  ON intelliform_pilot_bookings(session_id);
"""