File size: 6,583 Bytes
8a01471
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * API Client for NN3D Backend Service
 * Communicates with Python FastAPI server for model analysis
 */

const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000';

export interface LayerInfo {
  id: string;
  name: string;
  type: string;
  category: string;
  inputShape: number[] | null;
  outputShape: number[] | null;
  params: Record<string, unknown>;
  numParameters: number;
  trainable: boolean;
}

export interface ConnectionInfo {
  source: string;
  target: string;
  tensorShape: number[] | null;
}

export interface ModelArchitecture {
  name: string;
  framework: string;
  totalParameters: number;
  trainableParameters: number;
  inputShape: number[] | null;
  outputShape: number[] | null;
  layers: LayerInfo[];
  connections: ConnectionInfo[];
}

export interface AnalysisResponse {
  success: boolean;
  model_type: string;
  architecture: ModelArchitecture;
  message: string | null;
}

export interface HealthResponse {
  status: string;
  pytorch_version: string;
  cuda_available: boolean;
}

/**
 * Check if the backend server is available
 */
export async function checkBackendHealth(): Promise<HealthResponse | null> {
  try {
    const response = await fetch(`${API_BASE_URL}/health`, {
      method: 'GET',
      headers: { 'Accept': 'application/json' },
    });
    
    if (response.ok) {
      return await response.json();
    }
    return null;
  } catch {
    return null;
  }
}

/**
 * Analyze a PyTorch model file using the backend service
 */
export async function analyzeModelWithBackend(
  file: File,
  inputShape?: number[]
): Promise<AnalysisResponse> {
  const formData = new FormData();
  formData.append('file', file);
  
  let url = `${API_BASE_URL}/analyze`;
  if (inputShape && inputShape.length > 0) {
    url += `?input_shape=${inputShape.join(',')}`;
  }
  
  const response = await fetch(url, {
    method: 'POST',
    body: formData,
  });
  
  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: 'Unknown error' }));
    throw new Error(error.detail || `HTTP ${response.status}`);
  }
  
  return await response.json();
}

/**
 * Analyze an ONNX model file using the backend service
 */
export async function analyzeONNXWithBackend(file: File): Promise<AnalysisResponse> {
  const formData = new FormData();
  formData.append('file', file);
  
  const response = await fetch(`${API_BASE_URL}/analyze/onnx`, {
    method: 'POST',
    body: formData,
  });
  
  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: 'Unknown error' }));
    throw new Error(error.detail || `HTTP ${response.status}`);
  }
  
  return await response.json();
}

/**
 * Analyze any model file using the universal endpoint
 * Supports: .pt, .pth, .ckpt, .bin, .model, .onnx, .h5, .hdf5, .keras, .pb, .safetensors
 */
export async function analyzeUniversal(file: File): Promise<AnalysisResponse> {
  const formData = new FormData();
  formData.append('file', file);
  
  const response = await fetch(`${API_BASE_URL}/analyze/universal`, {
    method: 'POST',
    body: formData,
  });
  
  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: 'Unknown error' }));
    throw new Error(error.detail || `HTTP ${response.status}`);
  }
  
  return await response.json();
}

/**
 * Check if backend is available and has required capabilities
 */
export async function isBackendAvailable(): Promise<boolean> {
  const health = await checkBackendHealth();
  return health !== null && health.status === 'healthy';
}

// =============================================================================
// Saved Models API
// =============================================================================

export interface SavedModelSummary {
  id: number;
  name: string;
  framework: string;
  total_parameters: number;
  layer_count: number;
  created_at: string;
}

export interface SavedModel extends SavedModelSummary {
  architecture: ModelArchitecture;
}

/**
 * Get list of all saved models
 */
export async function getSavedModels(): Promise<SavedModelSummary[]> {
  const response = await fetch(`${API_BASE_URL}/models/saved`, {
    method: 'GET',
    headers: { 'Accept': 'application/json' },
  });
  
  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: 'Unknown error' }));
    throw new Error(error.detail || `HTTP ${response.status}`);
  }
  
  const data = await response.json();
  return data.models || [];
}

/**
 * Check if a model with the given name already exists
 * Returns the model if found, null otherwise
 */
export async function findModelByName(name: string): Promise<SavedModelSummary | null> {
  try {
    const models = await getSavedModels();
    return models.find(m => m.name === name) || null;
  } catch {
    return null;
  }
}

/**
 * Get a saved model by ID with full architecture
 */
export async function getSavedModelById(id: number): Promise<SavedModel> {
  const response = await fetch(`${API_BASE_URL}/models/saved/${id}`, {
    method: 'GET',
    headers: { 'Accept': 'application/json' },
  });
  
  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: 'Unknown error' }));
    throw new Error(error.detail || `HTTP ${response.status}`);
  }
  
  const data = await response.json();
  return data.model;
}

/**
 * Save a model to the database
 */
export async function saveModel(
  name: string,
  framework: string,
  totalParameters: number,
  layerCount: number,
  architecture: ModelArchitecture,
  fileHash?: string
): Promise<{ id: number; message: string }> {
  const response = await fetch(`${API_BASE_URL}/models/save`, {
    method: 'POST',
    headers: { 
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      name,
      framework,
      totalParameters,
      layerCount,
      architecture,
      fileHash,
    }),
  });
  
  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: 'Unknown error' }));
    throw new Error(error.detail || `HTTP ${response.status}`);
  }
  
  return await response.json();
}

/**
 * Delete a saved model
 */
export async function deleteSavedModel(id: number): Promise<void> {
  const response = await fetch(`${API_BASE_URL}/models/saved/${id}`, {
    method: 'DELETE',
    headers: { 'Accept': 'application/json' },
  });
  
  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: 'Unknown error' }));
    throw new Error(error.detail || `HTTP ${response.status}`);
  }
}