File size: 7,850 Bytes
a1aef88
 
 
 
 
 
0e62cc9
a1aef88
 
 
 
 
 
 
 
 
 
0e62cc9
a1aef88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e62cc9
 
 
 
 
 
 
 
 
 
 
a1aef88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e62cc9
 
 
 
 
 
 
a1aef88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type {
  LoadDataResponse,
  AnalysisResponse,
  DashboardSummary,
  SchemaListResponse,
  SchemaMergeResponse,
  SchemaCoverageResponse,
  ParseUploadResponse,
  CostEstimate,
  ParseRunResponse,
  ScuCriteriaResponse,
  ScuNormalizeResponse,
  ScuFilterResponse,
  RagSearchResponse,
  CramersVResponse,
  ContingencyResponse,
  ColumnGroupsResponse,
  XgboostImportanceResponse,
} from '../types';

// API origin is configurable for split deployments (e.g. frontend on Vercel,
// backend on Hugging Face Spaces / Render). Set VITE_API_BASE to the backend
// origin at build time, e.g. "https://user-uap.hf.space". When unset it falls
// back to a same-origin "/api", which the Vite dev proxy (vite.config.ts) and
// a Vercel `/api` rewrite both handle transparently.
const API_ORIGIN = (import.meta.env.VITE_API_BASE ?? '').replace(/\/+$/, '');
const BASE = `${API_ORIGIN}/api`;

async function request<T>(url: string, init?: RequestInit): Promise<T> {
  const res = await fetch(`${BASE}${url}`, {
    headers: { 'Content-Type': 'application/json' },
    ...init,
  });
  if (!res.ok) {
    const body = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(body.detail || `Request failed: ${res.status}`);
  }
  return res.json();
}

export const api = {
  loadData(type = 'west', rows = 15000): Promise<LoadDataResponse> {
    return request(`/data/load?type=${type}&rows=${rows}`);
  },

  uploadFile(file: File): Promise<LoadDataResponse> {
    const form = new FormData();
    form.append('file', file);
    return fetch(`${BASE}/data/upload`, { method: 'POST', body: form }).then(
      async (res) => {
        if (!res.ok) {
          const body = await res.json().catch(() => ({ detail: res.statusText }));
          throw new Error(body.detail || `Upload failed: ${res.status}`);
        }
        return res.json();
      }
    );
  },

  filterData(
    filters: {
      column: string;
      type: string;
      values?: string[];
      min_val?: number;
      max_val?: number;
      pattern?: string;
    }[]
  ): Promise<LoadDataResponse> {
    return request('/data/filter', {
      method: 'POST',
      body: JSON.stringify(filters),
    });
  },

  getColumns(): Promise<{ columns: { name: string; dtype: string; unique: number; non_null: number }[] }> {
    return request('/data/columns');
  },

  getColumnValues(
    column: string,
    search = '',
    limit = 50
  ): Promise<{
    column: string;
    values: { value: string; count: number }[];
    total_matches: number;
  }> {
    return request(
      `/data/column-values?column=${encodeURIComponent(column)}&search=${encodeURIComponent(search)}&limit=${limit}`
    );
  },

  runAnalysis(
    columns: string[],
    opts: {
      enable_tfidf?: boolean;
      min_cluster_size?: number;
      n_neighbors?: number;
      min_dist?: number;
      top_n?: number;
    } = {}
  ): Promise<AnalysisResponse> {
    return request('/analyze/run', {
      method: 'POST',
      body: JSON.stringify({ columns, ...opts }),
    });
  },

  // ── Parsing ───────────────────────────────────────────────────────────
  getSchemas(): Promise<SchemaListResponse> {
    return request('/parse/schemas');
  },

  mergeSchema(
    labels: string[],
    customFields?: Record<string, unknown>
  ): Promise<SchemaMergeResponse> {
    return request('/parse/schema-merge', {
      method: 'POST',
      body: JSON.stringify({ labels, custom_fields: customFields ?? null }),
    });
  },

  schemaCoverage(
    labels: string[],
    columns: string[],
    customFields?: Record<string, unknown>
  ): Promise<SchemaCoverageResponse> {
    return request('/parse/schema-coverage', {
      method: 'POST',
      body: JSON.stringify({ labels, columns, custom_fields: customFields ?? null }),
    });
  },

  uploadParseFile(file: File): Promise<ParseUploadResponse> {
    const form = new FormData();
    form.append('file', file);
    return fetch(`${BASE}/parse/upload`, { method: 'POST', body: form }).then(
      async (res) => {
        if (!res.ok) {
          const body = await res.json().catch(() => ({ detail: res.statusText }));
          throw new Error(body.detail || `Upload failed: ${res.status}`);
        }
        return res.json();
      }
    );
  },

  estimateParse(
    columns: string[],
    formatJson: string,
    model: string,
    useBatch = false
  ): Promise<CostEstimate> {
    return request('/parse/estimate', {
      method: 'POST',
      body: JSON.stringify({ columns, format_json: formatJson, model, use_batch: useBatch }),
    });
  },

  runParse(payload: {
    columns: string[];
    format_json: string;
    provider: string;
    model: string;
    api_key: string;
    max_workers?: number;
    keep_columns?: string[];
  }): Promise<ParseRunResponse> {
    return request('/parse/run', {
      method: 'POST',
      body: JSON.stringify(payload),
    });
  },

  // ── SCU normalization ─────────────────────────────────────────────────
  getScuCriteria(): Promise<ScuCriteriaResponse> {
    return request('/scu/criteria');
  },

  scuNormalize(): Promise<ScuNormalizeResponse> {
    return request('/scu/normalize', { method: 'POST', body: '{}' });
  },

  scuFilter(criterionKeys: string[]): Promise<ScuFilterResponse> {
    return request('/scu/filter', {
      method: 'POST',
      body: JSON.stringify({ criterion_keys: criterionKeys }),
    });
  },

  // ── RAG search (Cohere) ───────────────────────────────────────────────
  ragSearch(
    columns: string[],
    question: string,
    cohereKey: string,
    topN = 50
  ): Promise<RagSearchResponse> {
    return request('/rag/search', {
      method: 'POST',
      body: JSON.stringify({ columns, question, cohere_key: cohereKey, top_n: topN }),
    });
  },

  // ── CramΓ©r's V explorer ───────────────────────────────────────────────
  cramersV(payload: {
    columns?: string[] | null;
    drop_missing?: boolean;
    exclude_trivial?: boolean;
    strong_threshold?: number;
    high_threshold?: number;
    source?: string;
  }): Promise<CramersVResponse> {
    return request('/analysis/cramers-v', {
      method: 'POST',
      body: JSON.stringify(payload),
    });
  },

  contingency(payload: {
    col1: string;
    col2: string;
    drop_missing?: boolean;
    source?: string;
  }): Promise<ContingencyResponse> {
    return request('/analysis/contingency', {
      method: 'POST',
      body: JSON.stringify(payload),
    });
  },

  columnGroups(payload: {
    source?: string;
    high_threshold?: number;
  }): Promise<ColumnGroupsResponse> {
    return request('/analysis/column-groups', {
      method: 'POST',
      body: JSON.stringify(payload),
    });
  },

  xgboostImportance(columns: string[], source = 'dataset'): Promise<XgboostImportanceResponse> {
    return request('/analysis/xgboost', {
      method: 'POST',
      body: JSON.stringify({ columns, source }),
    });
  },

  queryGemini(question: string, columns: string[], geminiKey: string): Promise<{ status: string; response: string; context_rows_used?: number; columns_used?: string[] }> {
    return request('/query/gemini', {
      method: 'POST',
      body: JSON.stringify({ question, columns, gemini_key: geminiKey }),
    });
  },

  getDashboardSummary(): Promise<DashboardSummary> {
    return request('/dashboard/summary');
  },

  healthCheck(): Promise<{ status: string; version: string }> {
    return request('/health');
  },
};