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
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import React, { useState } from 'react';
import { 
  Button, 
  Box, 
  Typography, 
  CircularProgress, 
  Snackbar,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid,
  Card,
  CardMedia,
  CardContent,
  Chip
} from '@material-ui/core';
import { Alert } from '@material-ui/lab';
import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles((theme) => ({
  root: {
    marginTop: theme.spacing(2),
    marginBottom: theme.spacing(2),
    padding: theme.spacing(2),
    backgroundColor: '#f5f5f5',
    borderRadius: theme.shape.borderRadius,
  },
  button: {
    marginRight: theme.spacing(2),
  },
  searchDialog: {
    minWidth: '500px',
  },
  formControl: {
    marginBottom: theme.spacing(2),
    minWidth: '100%',
  },
  searchResults: {
    marginTop: theme.spacing(2),
  },
  resultCard: {
    marginBottom: theme.spacing(2),
  },
  resultImage: {
    height: 140,
    objectFit: 'contain',
  },
  chip: {
    margin: theme.spacing(0.5),
  },
  similarityChip: {
    backgroundColor: theme.palette.primary.main,
    color: 'white',
  }
}));

const VectorDBActions = ({ results }) => {
  const classes = useStyles();
  const [isSaving, setIsSaving] = useState(false);
  const [saveSuccess, setSaveSuccess] = useState(false);
  const [saveError, setSaveError] = useState(null);
  const [openSearchDialog, setOpenSearchDialog] = useState(false);
  const [searchType, setSearchType] = useState('image');
  const [searchClass, setSearchClass] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [isSearching, setIsSearching] = useState(false);
  const [searchError, setSearchError] = useState(null);
  
  // Extract model and data from results
  const { model, data } = results;
  
  // Handle saving to vector DB
  const handleSaveToVectorDB = async () => {
    setIsSaving(true);
    setSaveError(null);
    
    try {
      let response;
      
      if (model === 'vit') {
        // For ViT, save the whole image with classifications
        response = await fetch('/api/add-to-collection', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            image: data.image,
            metadata: {
              model: 'vit',
              classifications: data.classifications
            }
          })
        });
      } else {
        // For YOLO and DETR, save detected objects
        response = await fetch('/api/add-detected-objects', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            image: data.image,
            objects: data.detections,
            imageId: generateUUID()
          })
        });
      }
      
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      
      const result = await response.json();
      
      if (result.error) {
        throw new Error(result.error);
      }
      
      setSaveSuccess(true);
      setTimeout(() => setSaveSuccess(false), 5000);
    } catch (err) {
      console.error('Error saving to vector DB:', err);
      setSaveError(`Error saving to vector DB: ${err.message}`);
    } finally {
      setIsSaving(false);
    }
  };
  
  // Handle opening search dialog
  const handleOpenSearchDialog = () => {
    setOpenSearchDialog(true);
    setSearchResults([]);
    setSearchError(null);
  };
  
  // Handle closing search dialog
  const handleCloseSearchDialog = () => {
    setOpenSearchDialog(false);
  };
  
  // Handle search type change
  const handleSearchTypeChange = (event) => {
    setSearchType(event.target.value);
    setSearchResults([]);
    setSearchError(null);
  };
  
  // Handle search class change
  const handleSearchClassChange = (event) => {
    setSearchClass(event.target.value);
  };
  
  // Handle search
  const handleSearch = async () => {
    setIsSearching(true);
    setSearchError(null);
    
    try {
      let requestBody = {};
      
      if (searchType === 'image') {
        // Search by current image
        requestBody = {
          searchType: 'image',
          image: data.image,
          n_results: 5
        };
      } else {
        // Search by class name
        if (!searchClass.trim()) {
          throw new Error('Please enter a class name');
        }
        
        requestBody = {
          searchType: 'class',
          class_name: searchClass.trim(),
          n_results: 5
        };
      }
      
      const response = await fetch('/api/search-similar-objects', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody)
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      
      const result = await response.json();
      
      if (result.error) {
        throw new Error(result.error);
      }
      
      console.log('Search API response:', result);
      
      // The backend responds with {success, searchType, results} structure, so extract only the results array
      if (result.success && Array.isArray(result.results)) {
        console.log('Setting search results array:', result.results);
        console.log('Results array length:', result.results.length);
        console.log('First result item:', result.results[0]);
        setSearchResults(result.results);
      } else {
        console.error('Unexpected API response format:', result);
        throw new Error('Unexpected API response format');
      }
    } catch (err) {
      console.error('Error searching vector DB:', err);
      setSearchError(`Error searching vector DB: ${err.message}`);
    } finally {
      setIsSearching(false);
    }
  };
  
  // Generate UUID for image ID
  const generateUUID = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      const r = Math.random() * 16 | 0;
      const v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  };
  
  // Render search results
  const renderSearchResults = () => {
    console.log('Rendering search results:', searchResults);
    console.log('Search results length:', searchResults.length);
    
    if (searchResults.length === 0) {
      console.log('No results to render');
      return (
        <Typography variant="body1">No results found.</Typography>
      );
    }
    
    return (
      <Grid container spacing={2}>
        {searchResults.map((result, index) => {
          const similarity = (1 - result.distance) * 100;
          
          return (
            <Grid item xs={12} sm={6} key={index}>
              <Card className={classes.resultCard}>
                {result.metadata && result.metadata.image_data ? (
                  <CardMedia
                    className={classes.resultImage}
                    component="img"
                    height="200"
                    image={`data:image/jpeg;base64,${result.metadata.image_data}`}
                    alt={result.metadata && result.metadata.class ? result.metadata.class : 'Object'}
                  />
                ) : (
                  <Box 
                    className={classes.resultImage}
                    style={{ 
                      backgroundColor: '#f0f0f0', 
                      display: 'flex', 
                      alignItems: 'center', 
                      justifyContent: 'center',
                      height: 200
                    }}
                  >
                    <Typography variant="body2" color="textSecondary">
                      {result.metadata && result.metadata.class ? result.metadata.class : 'Object'} Image
                    </Typography>
                  </Box>
                )}
                <CardContent>
                  <Box display="flex" justifyContent="space-between" alignItems="center" mb={1}>
                    <Typography variant="subtitle1">Result #{index + 1}</Typography>
                    <Chip 
                      label={`Similarity: ${similarity.toFixed(2)}%`}
                      className={classes.similarityChip}
                      size="small"
                    />
                  </Box>
                  <Typography variant="body2" color="textSecondary">
                    <strong>Class:</strong> {result.metadata.class || 'N/A'}
                  </Typography>
                  {result.metadata.confidence && (
                    <Typography variant="body2" color="textSecondary">
                      <strong>Confidence:</strong> {(result.metadata.confidence * 100).toFixed(2)}%
                    </Typography>
                  )}
                  <Typography variant="body2" color="textSecondary">
                    <strong>Object ID:</strong> {result.id}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
          );
        })}
      </Grid>
    );
  };
  
  return (
    <Box className={classes.root}>
      <Typography variant="h6" gutterBottom>
        Vector Database Actions
      </Typography>
      
      <Box display="flex" alignItems="center" mb={2}>
        <Button
          variant="contained"
          color="primary"
          onClick={handleSaveToVectorDB}
          disabled={isSaving}
          className={classes.button}
        >
          {isSaving ? (
            <>
              <CircularProgress size={20} color="inherit" style={{ marginRight: 8 }} />
              Saving...
            </>
          ) : (
            'Save to Vector DB'
          )}
        </Button>
        
        <Button
          variant="outlined"
          color="primary"
          onClick={handleOpenSearchDialog}
          className={classes.button}
        >
          Search Similar
        </Button>
      </Box>
      
      {saveError && (
        <Alert severity="error" style={{ marginTop: 8 }}>
          {saveError}
        </Alert>
      )}
      
      <Snackbar open={saveSuccess} autoHideDuration={5000} onClose={() => setSaveSuccess(false)}>
        <Alert severity="success">
          {model === 'vit' ? (
            'Image and classifications successfully saved to vector DB!'
          ) : (
            'Detected objects successfully saved to vector DB!'
          )}
        </Alert>
      </Snackbar>
      
      {/* Search Dialog */}
      <Dialog
        open={openSearchDialog}
        onClose={handleCloseSearchDialog}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>Search Vector Database</DialogTitle>
        <DialogContent>
          <FormControl className={classes.formControl}>
            <InputLabel id="search-type-label">Search Type</InputLabel>
            <Select
              labelId="search-type-label"
              id="search-type"
              value={searchType}
              onChange={handleSearchTypeChange}
            >
              <MenuItem value="image">Search by Current Image</MenuItem>
              <MenuItem value="class">Search by Class Name</MenuItem>
            </Select>
          </FormControl>
          
          {searchType === 'class' && (
            <FormControl className={classes.formControl}>
              <TextField
                label="Class Name"
                value={searchClass}
                onChange={handleSearchClassChange}
                placeholder="e.g. person, car, dog..."
                fullWidth
              />
            </FormControl>
          )}
          
          {searchError && (
            <Alert severity="error" style={{ marginBottom: 16 }}>
              {searchError}
            </Alert>
          )}
          
          <Box className={classes.searchResults}>
            {isSearching ? (
              <Box display="flex" justifyContent="center" alignItems="center" p={4}>
                <CircularProgress />
                <Typography variant="body1" style={{ marginLeft: 16 }}>
                  Searching...
                </Typography>
              </Box>
            ) : (
              <>
                {console.log('Search dialog render - searchResults:', searchResults)}
                {searchResults.length > 0 ? renderSearchResults() : 
                  <Typography variant="body1">No results found. Please try another search.</Typography>
                }
              </>
            )}
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseSearchDialog} color="default">
            Close
          </Button>
          <Button 
            onClick={handleSearch} 
            color="primary" 
            variant="contained"
            disabled={isSearching || (searchType === 'class' && !searchClass.trim())}
          >
            Search
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default VectorDBActions;