mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 10:55:27 +00:00
feat(search): add image similarity search (#537)
* feat(search): add image similarity search * feat(search): support pasting image attachments
This commit is contained in:
@@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Added
|
||||
|
||||
- **search**: Find similar images and video segments from a project image, or choose, drop, or paste an image in semantic search.
|
||||
|
||||
### Fixed
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -95,6 +95,8 @@ apps/web/e2e/
|
||||
| Owner searches the file list by an English name keyword | `tests/project/search-file-list.spec.ts` |
|
||||
| Owner searches the file list by Chinese, Japanese, and Korean name keywords | `tests/project/search-file-list.spec.ts` |
|
||||
| Owner searches the file list with a keyword and a filter condition | `tests/project/search-file-list.spec.ts` |
|
||||
| Owner finds similar media and filters the results by type | `tests/project/search-file-list.spec.ts` |
|
||||
| Owner submits a resized image with filters and can remove the attachment | `tests/project/search-file-list.spec.ts` |
|
||||
| Owner saves a search result as a collection | `tests/project/save-search-collection.spec.ts` |
|
||||
| Image share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
|
||||
| Video share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
|
||||
|
||||
@@ -28,7 +28,7 @@ test('owner saves a search result as a collection', async ({ project, prisma })
|
||||
await expect(dialog).toBeVisible()
|
||||
|
||||
await dialog.getByPlaceholder('Search records by name...').fill('report')
|
||||
await dialog.getByRole('button', { name: 'Search' }).click()
|
||||
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
|
||||
await expect(dialog.getByText(matching, { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByText(other, { exact: true })).not.toBeVisible()
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { APIRequestContext } from '@playwright/test'
|
||||
import type { AssetInfo, ImageSearchRequest } from '@shumai/dtos'
|
||||
import { expect, test } from '../../fixtures'
|
||||
import { apiUploadFile, fileCard } from '../../helpers/files'
|
||||
|
||||
@@ -38,7 +39,7 @@ test('owner searches the file list by an English name keyword', async ({ project
|
||||
|
||||
// Keyword-only search (no filter conditions)
|
||||
await dialog.getByPlaceholder('Search records by name...').fill('report')
|
||||
await dialog.getByRole('button', { name: 'Search' }).click()
|
||||
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
|
||||
|
||||
await expect(dialog.getByText(report2024, { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByText(report2025, { exact: true })).toBeVisible()
|
||||
@@ -75,7 +76,7 @@ test('owner searches the file list by Chinese, Japanese, and Korean name keyword
|
||||
const dialog = page.getByRole('dialog')
|
||||
await expect(dialog).toBeVisible()
|
||||
await dialog.getByPlaceholder('Search records by name...').fill(keyword)
|
||||
await dialog.getByRole('button', { name: 'Search' }).click()
|
||||
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
|
||||
for (const name of visible) {
|
||||
await expect(dialog.getByText(name, { exact: true })).toBeVisible()
|
||||
}
|
||||
@@ -149,7 +150,7 @@ test('owner searches the file list with a keyword and a filter condition', async
|
||||
// confirms the filter became active before we run the search.
|
||||
await expect(dialog.getByText('1 active')).toBeVisible()
|
||||
|
||||
await dialog.getByRole('button', { name: 'Search' }).click()
|
||||
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
|
||||
await expect(dialog.getByText(bigReport, { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByText(smallReport, { exact: true })).not.toBeVisible()
|
||||
|
||||
@@ -160,3 +161,192 @@ test('owner searches the file list with a keyword and a filter condition', async
|
||||
await expect(fileCard(page, bigReport)).toBeVisible()
|
||||
await expect(fileCard(page, smallReport)).not.toBeVisible()
|
||||
})
|
||||
|
||||
test.describe('image search', () => {
|
||||
test.use({ fileOptions: { mediaType: 'image' } })
|
||||
|
||||
test('owner finds similar media and filters the results by type', async ({ file }) => {
|
||||
const { page, teamId, projectId, rootFolderId, fileId, fileName } = file
|
||||
const source = fileCard(page, fileName)
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await source.click({ button: 'right' })
|
||||
await expect(page.getByRole('menu')).toBeVisible()
|
||||
await expect(page.getByRole('menuitem', { name: 'Find similar' })).toHaveCount(0)
|
||||
|
||||
await page.route(`**/api/teams/${teamId}/settings`, async (route) => {
|
||||
const response = await route.fetch()
|
||||
await route.fulfill({
|
||||
response,
|
||||
json: { ...(await response.json()), semanticSearchEnabled: true },
|
||||
})
|
||||
})
|
||||
const image: AssetInfo = {
|
||||
id: 'image-result',
|
||||
name: 'result.jpg',
|
||||
type: 'file',
|
||||
sizeByte: 100,
|
||||
fileCount: 1,
|
||||
status: 'processed',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
updatedAt: '2026-01-01T00:00:00.000Z',
|
||||
proxyType: 'image',
|
||||
}
|
||||
const video: AssetInfo = {
|
||||
...image,
|
||||
id: 'video-result',
|
||||
name: 'result.mp4',
|
||||
proxyType: 'video',
|
||||
startTime: 65,
|
||||
endTime: 120,
|
||||
}
|
||||
const requests: ImageSearchRequest[] = []
|
||||
await page.route(`**/api/folders/${rootFolderId}/image-search`, async (route) => {
|
||||
const request = route.request().postDataJSON() as ImageSearchRequest
|
||||
requests.push(request)
|
||||
const data =
|
||||
request.mediaType === 'image'
|
||||
? [image]
|
||||
: request.mediaType === 'video'
|
||||
? [video]
|
||||
: [image, video]
|
||||
await route.fulfill({ json: { data, pageInfo: { total: data.length } } })
|
||||
})
|
||||
|
||||
const settingsLoaded = page.waitForResponse(`**/api/teams/${teamId}/settings`)
|
||||
await page.reload()
|
||||
await settingsLoaded
|
||||
await source.click({ button: 'right' })
|
||||
await page.getByRole('menuitem', { name: 'Find similar' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: 'Find similar' })
|
||||
await expect(dialog.getByText(image.name)).toBeVisible()
|
||||
await expect(dialog.getByText(video.name)).toBeVisible()
|
||||
await expect(dialog.getByTestId('file-preview-matched-duration')).toHaveText('01:05 - 02:00')
|
||||
expect(requests.at(-1)).toMatchObject({ sourceAssetId: fileId, first: 20 })
|
||||
|
||||
await dialog.getByText('Videos', { exact: true }).click()
|
||||
await expect(dialog.getByText(video.name)).toBeVisible()
|
||||
await expect(dialog.getByText(image.name)).toHaveCount(0)
|
||||
expect(requests.at(-1)).toMatchObject({ sourceAssetId: fileId, mediaType: 'video' })
|
||||
|
||||
await dialog.getByText('Images', { exact: true }).click()
|
||||
await expect(dialog.getByText(image.name)).toBeVisible()
|
||||
await expect(dialog.getByText(video.name)).toHaveCount(0)
|
||||
expect(requests.at(-1)).toMatchObject({ sourceAssetId: fileId, mediaType: 'image' })
|
||||
})
|
||||
|
||||
test('owner submits a resized image with filters and can remove the attachment', async ({
|
||||
project,
|
||||
browserName,
|
||||
}) => {
|
||||
const { page, teamId, projectId, rootFolderId } = project
|
||||
await page.route(`**/api/teams/${teamId}/settings`, async (route) => {
|
||||
const response = await route.fetch()
|
||||
await route.fulfill({
|
||||
response,
|
||||
json: { ...(await response.json()), semanticSearchEnabled: true },
|
||||
})
|
||||
})
|
||||
const requests: ImageSearchRequest[] = []
|
||||
await page.route(`**/api/folders/${rootFolderId}/image-search`, async (route) => {
|
||||
requests.push(route.request().postDataJSON() as ImageSearchRequest)
|
||||
await route.fulfill({ json: { data: [], pageInfo: { total: 0 } } })
|
||||
})
|
||||
|
||||
await page.goto(`/projects/${projectId}`)
|
||||
await page.getByRole('button', { name: 'Search' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: 'Search', exact: true })
|
||||
const semantic = dialog.getByRole('switch', { name: 'Semantic Search' })
|
||||
await expect(semantic).toBeEnabled()
|
||||
await semantic.click()
|
||||
await dialog.getByPlaceholder('Search records by content...').fill('text draft')
|
||||
|
||||
await dialog.getByRole('button', { name: '+ Add condition' }).click()
|
||||
const comboboxes = dialog.getByRole('combobox')
|
||||
await comboboxes.first().click()
|
||||
await page.getByRole('option', { name: 'Size', exact: true }).click()
|
||||
await comboboxes.nth(1).click()
|
||||
await page.getByRole('option', { name: '>', exact: true }).click()
|
||||
await dialog.locator('input[type="number"]').fill('100')
|
||||
await expect(dialog.getByText('1 active')).toBeVisible()
|
||||
|
||||
await dialog.getByRole('button', { name: 'Attach an image' }).click()
|
||||
const picker = page.getByRole('dialog', { name: 'Attach an image' })
|
||||
await expect(picker).toBeVisible()
|
||||
const png = await page.evaluate(() => {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = 2560
|
||||
canvas.height = 1440
|
||||
return canvas.toDataURL('image/png').split(',')[1]
|
||||
})
|
||||
const chooser = page.waitForEvent('filechooser')
|
||||
await picker.getByRole('button', { name: 'Choose image' }).click()
|
||||
await (
|
||||
await chooser
|
||||
).setFiles({ name: 'reference.png', mimeType: 'image/png', buffer: Buffer.from(png, 'base64') })
|
||||
await expect(dialog.getByText('reference.png')).toBeVisible()
|
||||
await expect(dialog.getByPlaceholder('Search records by content...')).toHaveCount(0)
|
||||
const thumbnail = dialog.locator('img').first()
|
||||
await expect
|
||||
.poll(() =>
|
||||
thumbnail.evaluate((image: HTMLImageElement) => ({
|
||||
width: image.naturalWidth,
|
||||
height: image.naturalHeight,
|
||||
})),
|
||||
)
|
||||
.toEqual({ width: 1280, height: 720 })
|
||||
expect(requests).toHaveLength(0)
|
||||
|
||||
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
|
||||
await expect.poll(() => requests.length).toBe(1)
|
||||
expect(requests[0]).toMatchObject({
|
||||
image: expect.stringMatching(/^\/9j\//),
|
||||
conditions: [{ field: 'sizeByte', operator: 'gt', value: 100 }],
|
||||
})
|
||||
expect(requests[0]).not.toHaveProperty('query')
|
||||
|
||||
await dialog.getByRole('button', { name: 'Attach an image' }).click()
|
||||
const transfer = await page.evaluateHandle(() => {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = 720
|
||||
canvas.height = 1280
|
||||
const png = atob(canvas.toDataURL('image/png').split(',')[1])
|
||||
const bytes = Uint8Array.from(png, (byte) => byte.charCodeAt(0))
|
||||
const transfer = new DataTransfer()
|
||||
transfer.items.add(new File([bytes], 'dropped.png', { type: 'image/png' }))
|
||||
return transfer
|
||||
})
|
||||
await picker
|
||||
.getByRole('button', { name: 'Choose image' })
|
||||
.dispatchEvent('drop', { dataTransfer: transfer })
|
||||
await transfer.dispose()
|
||||
await expect(dialog.getByText('dropped.png')).toBeVisible()
|
||||
|
||||
if (browserName === 'chromium') {
|
||||
await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])
|
||||
await page.evaluate(async (base64) => {
|
||||
const bytes = Uint8Array.from(atob(base64), (byte) => byte.charCodeAt(0))
|
||||
const image = new Blob([bytes], { type: 'image/png' })
|
||||
await navigator.clipboard.write([new ClipboardItem({ 'image/png': image })])
|
||||
}, png)
|
||||
await dialog.getByRole('button', { name: 'Attach an image' }).click()
|
||||
await expect(picker).toBeVisible()
|
||||
await page.keyboard.press('ControlOrMeta+V')
|
||||
await expect(picker).toBeHidden()
|
||||
await expect(dialog.getByText('dropped.png')).toHaveCount(0)
|
||||
await expect(thumbnail).toHaveJSProperty('naturalWidth', 1280)
|
||||
await expect(thumbnail).toHaveJSProperty('naturalHeight', 720)
|
||||
await dialog.getByRole('button', { name: 'Search', exact: true }).click()
|
||||
await expect.poll(() => requests.length).toBe(2)
|
||||
expect(requests[1]).toMatchObject({
|
||||
image: expect.stringMatching(/^\/9j\//),
|
||||
conditions: [{ field: 'sizeByte', operator: 'gt', value: 100 }],
|
||||
})
|
||||
}
|
||||
|
||||
await dialog.getByRole('button', { name: 'Remove image' }).click()
|
||||
await expect(dialog.getByPlaceholder('Search records by content...')).toBeVisible()
|
||||
await expect(dialog.getByText('1 active')).toBeVisible()
|
||||
await dialog.getByRole('button', { name: 'Close', exact: true }).last().click()
|
||||
await expect(page.getByText('This folder is empty')).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -60,6 +60,7 @@ describe('folder api', () => {
|
||||
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'listChildren').mockImplementation(vi.fn())
|
||||
vi.spyOn(searchService, 'search').mockImplementation(vi.fn())
|
||||
vi.spyOn(searchService, 'searchByImage').mockResolvedValue({ data: [], pageInfo: { total: 0 } })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -329,6 +330,83 @@ describe('folder api', () => {
|
||||
)
|
||||
})
|
||||
|
||||
describe('POST /folders/:folderId/image-search', () => {
|
||||
function request(body: Record<string, unknown>) {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
return app.request('/folders/scope-id/image-search', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
it('checks both permissions and passes a stored image search to Core', async () => {
|
||||
const res = await request({ sourceAssetId: 'image-id', mediaType: 'video', first: 20 })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ data: [], pageInfo: { total: 0 } })
|
||||
expect(vi.mocked(authzService.hasPermission).mock.calls.map(([input]) => input.id)).toEqual([
|
||||
'scope-id',
|
||||
'image-id',
|
||||
])
|
||||
expect(authzService.hasPermission).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'image-id',
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
}),
|
||||
)
|
||||
expect(searchService.searchByImage).toHaveBeenCalledWith('scope-id', {
|
||||
sourceAssetId: 'image-id',
|
||||
mediaType: 'video',
|
||||
first: 20,
|
||||
operator: 'AND',
|
||||
conditions: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('checks folder read access before passing image data to Core', async () => {
|
||||
const conditions = [{ field: 'status', operator: 'eq', value: 'approved' }]
|
||||
const res = await request({ image: 'aW1hZ2U=', conditions })
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledTimes(1)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'scope-id',
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
}),
|
||||
)
|
||||
expect(searchService.searchByImage).toHaveBeenCalledWith('scope-id', {
|
||||
image: 'aW1hZ2U=',
|
||||
conditions,
|
||||
operator: 'AND',
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects a denied folder or source before running the search', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new HTTPException(403))
|
||||
expect((await request({ image: 'aW1hZ2U=' })).status).toBe(403)
|
||||
vi.mocked(authzService.hasPermission)
|
||||
.mockResolvedValueOnce(undefined)
|
||||
.mockRejectedValueOnce(new HTTPException(403))
|
||||
expect((await request({ sourceAssetId: 'image-id' })).status).toBe(403)
|
||||
expect(searchService.searchByImage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects incomplete, ambiguous, and invalid search inputs', async () => {
|
||||
for (const body of [
|
||||
{},
|
||||
{ image: 'aW1hZ2U=', sourceAssetId: 'both' },
|
||||
{ image: 'invalid!' },
|
||||
{ sourceAssetId: 'image-id', mediaType: 'audio' },
|
||||
]) {
|
||||
expect((await request(body)).status).toBe(400)
|
||||
}
|
||||
expect((await request({ image: 'A'.repeat(1_600_000) })).status).toBe(413)
|
||||
expect(searchService.searchByImage).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /folders/:folderId/order', async () => {
|
||||
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
|
||||
id: 'test-id',
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { bodyLimit } from 'hono/body-limit'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { searchService } from '@shumai/core/src/search/search'
|
||||
@@ -11,7 +12,11 @@ import {
|
||||
updateAgentsMdRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { listChildrenRequestSchema, updateAssetOrderRequestSchema, AuditAction } from '@shumai/dtos'
|
||||
import { searchRequestSchema } from '@shumai/dtos'
|
||||
import {
|
||||
imageSearchRequestSchema,
|
||||
MAX_SEARCH_IMAGE_BASE64_LENGTH,
|
||||
searchRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import {
|
||||
@@ -154,6 +159,33 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
const result = await searchService.search(folderId, req)
|
||||
return c.json(result)
|
||||
})
|
||||
.post(
|
||||
'/folders/:folderId/image-search',
|
||||
bodyLimit({ maxSize: MAX_SEARCH_IMAGE_BASE64_LENGTH + 64 * 1024 }),
|
||||
zValidator('json', imageSearchRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
if (req.sourceAssetId) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: req.sourceAssetId,
|
||||
})
|
||||
}
|
||||
|
||||
return c.json(await searchService.searchByImage(folderId, req))
|
||||
},
|
||||
)
|
||||
.get('/folders/:folderId/agentsmd', async (c) => {
|
||||
const { content } = await runOperation(
|
||||
getFolderInstructionsOp,
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
export function getGemmaEmbeddingEndpoint(): string {
|
||||
const baseUrl = process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL || 'http://localhost:9379/v1'
|
||||
const url = baseUrl.replace(/\/+$/, '')
|
||||
if (url.endsWith('/embeddings')) return url
|
||||
return url.endsWith('/v1') ? `${url}/embeddings` : `${url}/v1/embeddings`
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import sharp from 'sharp'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ImageEmbeddingService } from './image-embedding'
|
||||
|
||||
const embedContent = vi.fn()
|
||||
vi.mock('@google/genai', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
GoogleGenAI: class {
|
||||
models = { embedContent }
|
||||
},
|
||||
}))
|
||||
|
||||
async function jpeg(width = 32, height = 24) {
|
||||
const buffer = await sharp({
|
||||
create: { width, height, channels: 3, background: '#ffffff' },
|
||||
})
|
||||
.jpeg()
|
||||
.toBuffer()
|
||||
return buffer.toString('base64')
|
||||
}
|
||||
|
||||
describe('ImageEmbeddingService', () => {
|
||||
let service: ImageEmbeddingService
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('EMBEDDING_PROVIDER', undefined)
|
||||
vi.stubEnv('GEMINI_API_KEY', 'fake-key')
|
||||
embedContent.mockReset()
|
||||
service = new ImageEmbeddingService()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('embeds JPEG images with Gemini and caches the result by team and image', async () => {
|
||||
const image = await jpeg()
|
||||
const embedding = Array<number>(1536).fill(0.02)
|
||||
embedContent.mockResolvedValue({ embeddings: [{ values: embedding }] })
|
||||
|
||||
expect(await service.generateEmbedding(image, 'team-a')).toEqual(embedding)
|
||||
expect(await service.generateEmbedding(image, 'team-a')).toEqual(embedding)
|
||||
expect(embedContent).toHaveBeenCalledTimes(1)
|
||||
expect(embedContent).toHaveBeenCalledWith({
|
||||
model: 'gemini-embedding-2',
|
||||
contents: [{ inlineData: { data: image, mimeType: 'image/jpeg' } }],
|
||||
config: { outputDimensionality: 1536, abortSignal: expect.any(AbortSignal) },
|
||||
})
|
||||
|
||||
await service.generateEmbedding(image, 'team-b')
|
||||
await service.generateEmbedding(await jpeg(18), 'team-a')
|
||||
expect(embedContent).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('uses the configured local Gemma endpoint and accepts portrait images', async () => {
|
||||
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
|
||||
vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', 'http://embedding.test/custom/embeddings/')
|
||||
const image = await jpeg(720, 1280)
|
||||
const embedding = Array<number>(768).fill(0.02)
|
||||
const fetchMock = vi.fn().mockResolvedValue(Response.json({ data: [{ embedding }] }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
expect(await service.generateEmbedding(image, 'team-a')).toEqual(embedding)
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'http://embedding.test/custom/embeddings',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
model: 'embeddinggemma-2',
|
||||
input: [
|
||||
{
|
||||
type: 'image_url',
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- OpenAI request field
|
||||
image_url: { url: `data:image/jpeg;base64,${image}` },
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
)
|
||||
expect(embedContent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects invalid, non-JPEG, and oversized images before contacting the provider', async () => {
|
||||
const png = await sharp({
|
||||
create: { width: 32, height: 24, channels: 3, background: '#ffffff' },
|
||||
})
|
||||
.png()
|
||||
.toBuffer()
|
||||
for (const image of ['aW1hZ2U=', png.toString('base64'), await jpeg(1281, 200)]) {
|
||||
await expect(service.generateEmbedding(image, 'team-a')).rejects.toMatchObject({
|
||||
status: 400,
|
||||
})
|
||||
}
|
||||
expect(embedContent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports provider errors and allows the image to be retried', async () => {
|
||||
const image = await jpeg()
|
||||
const embedding = Array<number>(1536).fill(0.02)
|
||||
embedContent
|
||||
.mockRejectedValueOnce(new Error('Provider failed'))
|
||||
.mockResolvedValueOnce({ embeddings: [{ values: [1, 2, 3] }] })
|
||||
.mockResolvedValueOnce({ embeddings: [{ values: embedding }] })
|
||||
|
||||
await expect(service.generateEmbedding(image, 'team-a')).rejects.toMatchObject({ status: 502 })
|
||||
await expect(service.generateEmbedding(image, 'team-a')).rejects.toMatchObject({ status: 502 })
|
||||
expect(await service.generateEmbedding(image, 'team-a')).toEqual(embedding)
|
||||
expect(embedContent).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,99 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { GoogleGenAI } from '@google/genai'
|
||||
import { LruTtlCache } from '@shumai/core/src/cache/lru-ttl-cache'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import sharp from 'sharp'
|
||||
import { getGemmaEmbeddingEndpoint } from './gemma-embedding-endpoint'
|
||||
|
||||
export function getImageEmbeddingDimensions(): 768 | 1536 {
|
||||
return process.env.EMBEDDING_PROVIDER === 'gemma-embedding-2-openai' ? 768 : 1536
|
||||
}
|
||||
|
||||
export class ImageEmbeddingService {
|
||||
private readonly cache = new LruTtlCache<string, number[]>(100)
|
||||
|
||||
async generateEmbedding(image: string, teamId: string): Promise<number[]> {
|
||||
const dimensions = getImageEmbeddingDimensions()
|
||||
const digest = createHash('sha256').update(image).digest('hex')
|
||||
const cacheKey = `${teamId}:${dimensions}:${digest}`
|
||||
const cached = this.cache.get(cacheKey)
|
||||
if (cached) return cached
|
||||
|
||||
const buffer = Buffer.from(image, 'base64')
|
||||
const metadata = await sharp(buffer, { limitInputPixels: 1280 * 720 })
|
||||
.metadata()
|
||||
.catch(() => null)
|
||||
if (
|
||||
metadata?.format !== 'jpeg' ||
|
||||
Math.max(metadata.width, metadata.height) > 1280 ||
|
||||
Math.min(metadata.width, metadata.height) > 720
|
||||
) {
|
||||
throw new HTTPException(400, { message: 'Provide a JPEG image resized to 720p.' })
|
||||
}
|
||||
|
||||
let embedding: number[] | undefined
|
||||
try {
|
||||
const signal = AbortSignal.timeout(15000)
|
||||
embedding =
|
||||
dimensions === 768
|
||||
? await this.embedWithGemma(image, signal)
|
||||
: await this.embedWithGemini(image, signal)
|
||||
if (
|
||||
!embedding ||
|
||||
embedding.length !== dimensions ||
|
||||
!embedding.every(Number.isFinite) ||
|
||||
!embedding.some((value) => value !== 0)
|
||||
) {
|
||||
throw new Error('Invalid image embedding returned by provider')
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ teamId, dimensions, errorName: err instanceof Error ? err.name : undefined },
|
||||
'Failed to generate image search embedding',
|
||||
)
|
||||
throw new HTTPException(502, { message: 'Failed to generate image search embedding.' })
|
||||
}
|
||||
|
||||
this.cache.set(cacheKey, embedding, 10 * 60 * 1000)
|
||||
return embedding
|
||||
}
|
||||
|
||||
private async embedWithGemini(image: string, signal: AbortSignal) {
|
||||
const apiKey = process.env.GEMINI_API_KEY
|
||||
if (!apiKey) throw new Error('GEMINI_API_KEY environment variable is not configured')
|
||||
|
||||
const ai = new GoogleGenAI({ apiKey: process.env[apiKey] || apiKey })
|
||||
const response = await ai.models.embedContent({
|
||||
model: 'gemini-embedding-2',
|
||||
contents: [{ inlineData: { data: image, mimeType: 'image/jpeg' } }],
|
||||
config: { outputDimensionality: 1536, abortSignal: signal },
|
||||
})
|
||||
|
||||
return response.embeddings?.[0]?.values
|
||||
}
|
||||
|
||||
private async embedWithGemma(image: string, signal: AbortSignal) {
|
||||
const response = await fetch(getGemmaEmbeddingEndpoint(), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
model: 'embeddinggemma-2',
|
||||
input: [
|
||||
{
|
||||
type: 'image_url',
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- OpenAI request field
|
||||
image_url: { url: `data:image/jpeg;base64,${image}` },
|
||||
},
|
||||
],
|
||||
}),
|
||||
signal,
|
||||
})
|
||||
if (!response.ok) throw new Error(`Embedding server returned status ${response.status}`)
|
||||
|
||||
const result = (await response.json()) as { data?: { embedding?: number[] }[] }
|
||||
return result.data?.[0]?.embedding
|
||||
}
|
||||
}
|
||||
|
||||
export const imageEmbeddingService = new ImageEmbeddingService()
|
||||
@@ -0,0 +1,199 @@
|
||||
import { prisma, Prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { imageSearchRequestSchema } from '@shumai/dtos'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { imageEmbeddingService } from './image-embedding'
|
||||
import { searchService } from './search'
|
||||
|
||||
function vector(dimensions: number, x: number, y = 0): number[] {
|
||||
return [x, y, ...Array<number>(dimensions - 2).fill(0)]
|
||||
}
|
||||
|
||||
async function insertEmbedding(
|
||||
assetId: string,
|
||||
embedding: number[],
|
||||
startTime: number | null = null,
|
||||
endTime: number | null = null,
|
||||
) {
|
||||
const column = embedding.length === 768 ? Prisma.sql`embedding_768` : Prisma.sql`embedding`
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, ${column}, start_time, end_time, created_at, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${assetId}, ${JSON.stringify(embedding)}::vector,
|
||||
${startTime}, ${endTime}, NOW(), NOW())
|
||||
`
|
||||
}
|
||||
|
||||
async function createProjectAssets() {
|
||||
const team = await prisma.team.create({ data: { name: 'Image search team' } })
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Embedding agent', email: 'visual-search-agent@example.com', type: 'agent' },
|
||||
})
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: user.id,
|
||||
teamId: team.id,
|
||||
type: 'embedding',
|
||||
config: { provider: 'google', model: 'gemini-embedding-2' },
|
||||
},
|
||||
})
|
||||
const project = await prisma.project.create({ data: { name: 'Visual search', teamId: team.id } })
|
||||
const root = await prisma.asset.create({
|
||||
data: { name: 'Root', type: 'root', status: 'processed', projectId: project.id },
|
||||
})
|
||||
await prisma.project.update({ where: { id: project.id }, data: { rootFolderId: root.id } })
|
||||
const subfolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'Subfolder',
|
||||
type: 'folder',
|
||||
status: 'uploaded',
|
||||
projectId: project.id,
|
||||
parentId: root.id,
|
||||
},
|
||||
})
|
||||
const file = (name: string, mediaType: string, parentId = root.id) =>
|
||||
prisma.asset.create({
|
||||
data: { name, mediaType, parentId, projectId: project.id, type: 'file', status: 'processed' },
|
||||
})
|
||||
const source = await file('source.jpg', 'image/jpeg', subfolder.id)
|
||||
return { team, agent, root, subfolder, source, file }
|
||||
}
|
||||
|
||||
describe('image search', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('ENABLE_EMBEDDING_AGENT', undefined)
|
||||
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('finds images and video segments across the project using the stored image vector', async () => {
|
||||
const { root, source, file } = await createProjectAssets()
|
||||
const image = await file('result.jpg', 'image/jpeg')
|
||||
const video = await file('result.mp4', 'video/mp4')
|
||||
const deleted = await file('deleted.jpg', 'image/jpeg')
|
||||
const audio = await file('audio.mp3', 'audio/mpeg')
|
||||
await prisma.asset.update({ where: { id: deleted.id }, data: { isDeleted: true } })
|
||||
|
||||
await insertEmbedding(source.id, vector(1536, 1))
|
||||
await insertEmbedding(video.id, vector(1536, 1), 4, 12)
|
||||
await insertEmbedding(video.id, vector(1536, 0, 1), 12, 20)
|
||||
await insertEmbedding(image.id, vector(1536, 1, 1))
|
||||
await insertEmbedding(deleted.id, vector(1536, 1))
|
||||
await insertEmbedding(audio.id, vector(1536, 1))
|
||||
|
||||
const provider = vi.spyOn(imageEmbeddingService, 'generateEmbedding')
|
||||
const request = { sourceAssetId: source.id }
|
||||
const first = await searchService.searchByImage(
|
||||
root.id,
|
||||
imageSearchRequestSchema.parse({ ...request, first: 2 }),
|
||||
)
|
||||
expect(first.data.map((item) => item.id)).toEqual([video.id, image.id])
|
||||
expect(first.data[0]).toMatchObject({ startTime: 4, endTime: 12 })
|
||||
expect(first.pageInfo).toMatchObject({ total: 3, cursor: expect.any(String) })
|
||||
const next = await searchService.searchByImage(
|
||||
root.id,
|
||||
imageSearchRequestSchema.parse({ ...request, first: 2, after: first.pageInfo.cursor }),
|
||||
)
|
||||
expect(next.data).toMatchObject([{ id: video.id, startTime: 12, endTime: 20 }])
|
||||
expect(next.pageInfo.cursor).toBeUndefined()
|
||||
|
||||
const images = await searchService.searchByImage(
|
||||
root.id,
|
||||
imageSearchRequestSchema.parse({ ...request, mediaType: 'image' }),
|
||||
)
|
||||
const videos = await searchService.searchByImage(
|
||||
root.id,
|
||||
imageSearchRequestSchema.parse({ ...request, mediaType: 'video' }),
|
||||
)
|
||||
expect(images.data.map((item) => item.id)).toEqual([image.id])
|
||||
expect(videos.data.map((item) => item.startTime)).toEqual([4, 12])
|
||||
expect(provider).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('uses the active provider vector column and reports when an image needs indexing', async () => {
|
||||
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
|
||||
const { root, source, file } = await createProjectAssets()
|
||||
const image = await file('result.jpg', 'image/jpeg')
|
||||
const req = imageSearchRequestSchema.parse({ sourceAssetId: source.id })
|
||||
await insertEmbedding(source.id, vector(1536, 1))
|
||||
await expect(searchService.searchByImage(root.id, req)).rejects.toMatchObject({ status: 409 })
|
||||
|
||||
await insertEmbedding(source.id, vector(768, 1))
|
||||
await insertEmbedding(image.id, vector(768, 1))
|
||||
const result = await searchService.searchByImage(root.id, req)
|
||||
expect(result.data.map((item) => item.id)).toEqual([image.id])
|
||||
})
|
||||
|
||||
it('limits an uploaded-image search to the folder and applies metadata filters', async () => {
|
||||
const { team, subfolder, source, file } = await createProjectAssets()
|
||||
const match = await file('approved.png', 'image/png', subfolder.id)
|
||||
const outside = await file('outside.png', 'image/png')
|
||||
for (const asset of [match, source, outside]) {
|
||||
await insertEmbedding(asset.id, vector(1536, 1))
|
||||
}
|
||||
for (const asset of [match, outside]) {
|
||||
await prisma.assetMetadataValue.create({
|
||||
data: { assetId: asset.id, fieldKey: 'status', stringValue: 'approved' },
|
||||
})
|
||||
}
|
||||
const provider = vi
|
||||
.spyOn(imageEmbeddingService, 'generateEmbedding')
|
||||
.mockResolvedValue(vector(1536, 1))
|
||||
const image = 'aW1hZ2U='
|
||||
const result = await searchService.searchByImage(
|
||||
subfolder.id,
|
||||
imageSearchRequestSchema.parse({
|
||||
image,
|
||||
conditions: [{ field: 'status', operator: 'eq', value: 'approved' }],
|
||||
}),
|
||||
)
|
||||
expect(provider).toHaveBeenCalledWith(image, team.id)
|
||||
expect(result.data.map((item) => item.id)).toEqual([match.id])
|
||||
})
|
||||
|
||||
it('requires a readable image from the project root scope', async () => {
|
||||
const { team, root, subfolder, source, file } = await createProjectAssets()
|
||||
const video = await file('video.mp4', 'video/mp4')
|
||||
const other = await prisma.project.create({ data: { name: 'Other project', teamId: team.id } })
|
||||
const otherImage = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'other.jpeg',
|
||||
mediaType: 'image/jpeg',
|
||||
projectId: other.id,
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
},
|
||||
})
|
||||
for (const id of [video.id, otherImage.id]) {
|
||||
const req = imageSearchRequestSchema.parse({ sourceAssetId: id })
|
||||
await expect(searchService.searchByImage(root.id, req)).rejects.toMatchObject({ status: 404 })
|
||||
}
|
||||
const req = imageSearchRequestSchema.parse({ sourceAssetId: source.id })
|
||||
await expect(searchService.searchByImage(subfolder.id, req)).rejects.toMatchObject({
|
||||
status: 400,
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects both forms of image search when the agent is disabled', async () => {
|
||||
const { agent, root, source } = await createProjectAssets()
|
||||
vi.stubEnv('ENABLE_EMBEDDING_AGENT', 'false')
|
||||
await expect(
|
||||
searchService.searchByImage(
|
||||
root.id,
|
||||
imageSearchRequestSchema.parse({ sourceAssetId: source.id }),
|
||||
),
|
||||
).rejects.toMatchObject({ status: 422 })
|
||||
vi.stubEnv('ENABLE_EMBEDDING_AGENT', undefined)
|
||||
await prisma.agent.update({ where: { id: agent.id }, data: { enabled: false } })
|
||||
const provider = vi.spyOn(imageEmbeddingService, 'generateEmbedding')
|
||||
await expect(
|
||||
searchService.searchByImage(root.id, imageSearchRequestSchema.parse({ image: 'aW1hZ2U=' })),
|
||||
).rejects.toMatchObject({ status: 422 })
|
||||
expect(provider).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
+177
-180
@@ -1,11 +1,11 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { Prisma, AssetType } from '@shumai/db'
|
||||
import { AssetService, assetService } from '@shumai/core/src/asset/asset'
|
||||
import { AssetInfo } from '@shumai/dtos'
|
||||
import { SearchRequest } from '@shumai/dtos'
|
||||
import type { AssetInfo, ImageSearchRequest, SearchRequest } from '@shumai/dtos'
|
||||
import { PaginatedData, decodeCursor, encodeCursor, PageInfo } from '@shumai/core/src/pagination'
|
||||
import { generateSearchNgrams } from '@shumai/core/src/utils/ngram'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { getImageEmbeddingDimensions, imageEmbeddingService } from './image-embedding'
|
||||
import { SqlQueryBuilder } from './sql-query-builder'
|
||||
import { TextEmbeddingService, textEmbeddingService } from './text-embedding'
|
||||
|
||||
@@ -23,202 +23,37 @@ export class SearchService {
|
||||
const targetTypes =
|
||||
req.assetType === 'folder' ? [AssetType.folder] : [AssetType.file, AssetType.version_stack]
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// AI Semantic search
|
||||
// ----------------------------------------------------------------------
|
||||
if (req.query && req.isSemantic) {
|
||||
// 1. Check if embedding agent exists and is enabled
|
||||
const team = await this.prismaClient.asset.findUnique({
|
||||
const folder = await this.prismaClient.asset.findUnique({
|
||||
where: { id: folderId },
|
||||
select: { project: { select: { teamId: true } } },
|
||||
})
|
||||
const teamId = team?.project?.teamId
|
||||
const teamId = folder?.project?.teamId
|
||||
if (!teamId) throw new Error('Team ID not found for folder')
|
||||
await this.requireEmbeddingAgent(teamId)
|
||||
|
||||
if (process.env.ENABLE_EMBEDDING_AGENT === 'false') {
|
||||
throw new HTTPException(422, {
|
||||
message: 'Embedding agent not configured or disabled for this team.',
|
||||
})
|
||||
}
|
||||
|
||||
const embeddingAgent = await this.prismaClient.agent.findFirst({
|
||||
where: { teamId, type: 'embedding', enabled: true },
|
||||
})
|
||||
|
||||
if (!embeddingAgent) {
|
||||
throw new HTTPException(422, {
|
||||
message: 'Embedding agent not configured or disabled for this team.',
|
||||
})
|
||||
}
|
||||
|
||||
// 2. Generate query embedding directly using configured environment provider
|
||||
let queryVector: number[]
|
||||
let vector: number[]
|
||||
try {
|
||||
const result = await this.embeddingSvc.generateEmbedding(req.query, {
|
||||
teamId,
|
||||
})
|
||||
queryVector = result.embedding
|
||||
const result = await this.embeddingSvc.generateEmbedding(req.query, { teamId })
|
||||
vector = result.embedding
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
throw new HTTPException(502, {
|
||||
message: `Failed to generate query embedding: ${msg}`,
|
||||
})
|
||||
}
|
||||
|
||||
if (!queryVector || queryVector.length === 0) {
|
||||
if (!vector || vector.length === 0) {
|
||||
throw new HTTPException(502, {
|
||||
message: 'Failed to generate query embedding: empty vector returned',
|
||||
})
|
||||
}
|
||||
|
||||
// 3. Construct raw SQL using SqlQueryBuilder
|
||||
const vectorJson = JSON.stringify(queryVector)
|
||||
const is768 = queryVector.length === 768
|
||||
const distanceExpr = is768
|
||||
? Prisma.sql`(ae.embedding_768 <=> ${vectorJson}::vector)`
|
||||
: Prisma.sql`(ae.embedding <=> ${vectorJson}::vector)`
|
||||
const notNullCond = is768
|
||||
? Prisma.sql`ae.embedding_768 IS NOT NULL`
|
||||
: Prisma.sql`ae.embedding IS NOT NULL`
|
||||
|
||||
const builder = new SqlQueryBuilder()
|
||||
.select(
|
||||
Prisma.sql`a.id as "assetId", ae.start_time as "startTime", ae.end_time as "endTime", ${distanceExpr} as "distance"`,
|
||||
)
|
||||
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
|
||||
.addWhere(Prisma.sql`a.is_deleted = false`)
|
||||
.addWhere(notNullCond)
|
||||
|
||||
if (targetFolderIds.length > 0) {
|
||||
builder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
|
||||
}
|
||||
|
||||
if (req.showSymlink) {
|
||||
builder.addWhere(Prisma.sql`
|
||||
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
|
||||
`)
|
||||
} else {
|
||||
builder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
|
||||
}
|
||||
|
||||
if (req.conditions && req.conditions.length > 0) {
|
||||
builder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
|
||||
}
|
||||
|
||||
const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains')
|
||||
if (nameCond) {
|
||||
const valStr = String(nameCond.value)
|
||||
const ngrams = generateSearchNgrams(valStr)
|
||||
|
||||
if (ngrams.length > 0) {
|
||||
builder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
|
||||
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
|
||||
} else {
|
||||
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
|
||||
}
|
||||
}
|
||||
|
||||
builder.orderBy(Prisma.sql`distance ASC`)
|
||||
|
||||
// 4. Paginate in SQL using limit/offset
|
||||
let limit = req.first || 20
|
||||
if (limit <= 0 || limit > 200) {
|
||||
limit = 20
|
||||
}
|
||||
|
||||
let offset = 0
|
||||
if (req.after) {
|
||||
offset = decodeCursor(req.after)
|
||||
}
|
||||
|
||||
builder.limit(limit + 1).offset(offset)
|
||||
|
||||
// 5. Execute raw SQL query
|
||||
const query = builder.build()
|
||||
const semanticMatches = await this.prismaClient.$queryRaw<
|
||||
{
|
||||
assetId: string
|
||||
startTime: number | null
|
||||
endTime: number | null
|
||||
distance: number
|
||||
}[]
|
||||
>(query)
|
||||
|
||||
const hasNextPage = semanticMatches.length > limit
|
||||
const finalMatches = hasNextPage ? semanticMatches.slice(0, limit) : semanticMatches
|
||||
|
||||
// 6. Map back to full rich metadata and return time-based duplicate segments
|
||||
const uniqueIds = Array.from(new Set(finalMatches.map((m) => m.assetId)))
|
||||
const fetchedInfos = await this.assetSvc.listAssetsByIds(uniqueIds, req.previewFormat)
|
||||
const assetInfosMap = new Map<string, AssetInfo>()
|
||||
for (const info of fetchedInfos) {
|
||||
assetInfosMap.set(info.id, info)
|
||||
}
|
||||
|
||||
const data: AssetInfo[] = []
|
||||
for (const match of finalMatches) {
|
||||
const baseInfo = assetInfosMap.get(match.assetId)
|
||||
if (baseInfo) {
|
||||
data.push({
|
||||
...baseInfo,
|
||||
startTime: match.startTime,
|
||||
endTime: match.endTime,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const pageInfo: PageInfo = {}
|
||||
const countBuilder = new SqlQueryBuilder()
|
||||
.select(Prisma.sql`COUNT(*)`)
|
||||
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
|
||||
.addWhere(Prisma.sql`a.is_deleted = false`)
|
||||
.addWhere(notNullCond)
|
||||
|
||||
if (targetFolderIds.length > 0) {
|
||||
countBuilder.addWhere(Prisma.sql`a.parent_id = ANY(${targetFolderIds})`)
|
||||
}
|
||||
if (req.showSymlink) {
|
||||
countBuilder.addWhere(Prisma.sql`
|
||||
(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))
|
||||
`)
|
||||
} else {
|
||||
countBuilder.addWhere(Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`)
|
||||
}
|
||||
|
||||
if (req.conditions && req.conditions.length > 0) {
|
||||
countBuilder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
|
||||
}
|
||||
|
||||
if (nameCond) {
|
||||
const valStr = String(nameCond.value)
|
||||
const ngrams = generateSearchNgrams(valStr)
|
||||
if (ngrams.length > 0) {
|
||||
countBuilder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
|
||||
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
|
||||
} else {
|
||||
countBuilder.addWhere(Prisma.sql`a.name ILIKE ${'%' + valStr + '%'}`)
|
||||
}
|
||||
}
|
||||
|
||||
const countRes = await this.prismaClient.$queryRaw<{ count: bigint }[]>(countBuilder.build())
|
||||
const totalCount = Number(countRes[0]?.count || 0)
|
||||
pageInfo.total = totalCount
|
||||
|
||||
if (totalCount < 2000) {
|
||||
countBuilder.select(Prisma.sql`SUM(COALESCE(a.size_byte, 0))::bigint as sum`)
|
||||
const sumRes = await this.prismaClient.$queryRaw<{ sum: bigint | null }[]>(
|
||||
countBuilder.build(),
|
||||
)
|
||||
pageInfo.totalSize = Number(sumRes[0]?.sum || 0)
|
||||
} else {
|
||||
pageInfo.totalSize = -1
|
||||
}
|
||||
|
||||
if (hasNextPage) {
|
||||
pageInfo.cursor = encodeCursor(offset + limit)
|
||||
}
|
||||
|
||||
return { data, pageInfo }
|
||||
return this.searchByEmbedding(
|
||||
targetFolderIds,
|
||||
req,
|
||||
JSON.stringify(vector),
|
||||
vector.length === 768 ? 768 : 1536,
|
||||
)
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
@@ -447,6 +282,168 @@ export class SearchService {
|
||||
|
||||
return { data, pageInfo }
|
||||
}
|
||||
|
||||
async searchByImage(
|
||||
folderId: string,
|
||||
req: ImageSearchRequest,
|
||||
): Promise<PaginatedData<AssetInfo[]>> {
|
||||
const folder = await this.prismaClient.asset.findFirst({
|
||||
where: { id: folderId, type: { in: [AssetType.root, AssetType.folder] }, isDeleted: false },
|
||||
select: { project: { select: { id: true, teamId: true, rootFolderId: true } } },
|
||||
})
|
||||
const project = folder?.project
|
||||
if (!project) throw new HTTPException(404, { message: 'Project folder not found.' })
|
||||
|
||||
await this.requireEmbeddingAgent(project.teamId)
|
||||
const dimensions = getImageEmbeddingDimensions()
|
||||
let vector: string
|
||||
if (req.sourceAssetId) {
|
||||
if (folderId !== project.rootFolderId) {
|
||||
throw new HTTPException(400, { message: 'Find similar requires the project root folder.' })
|
||||
}
|
||||
|
||||
const column = dimensions === 768 ? Prisma.sql`embedding_768` : Prisma.sql`embedding`
|
||||
const [source] = await this.prismaClient.$queryRaw<{ vector: string | null }[]>`
|
||||
SELECT (
|
||||
SELECT ${column}::text
|
||||
FROM asset_embeddings
|
||||
WHERE asset_id = a.id AND ${column} IS NOT NULL
|
||||
ORDER BY id DESC
|
||||
LIMIT 1
|
||||
) AS vector
|
||||
FROM assets a
|
||||
WHERE a.id = ${req.sourceAssetId} AND a.project_id = ${project.id}
|
||||
AND a.type = 'file' AND a.media_type LIKE 'image/%' AND a.is_deleted = false
|
||||
`
|
||||
if (!source) throw new HTTPException(404, { message: 'Source image not found.' })
|
||||
if (!source.vector) {
|
||||
throw new HTTPException(409, { message: 'The source image is waiting to be indexed.' })
|
||||
}
|
||||
vector = source.vector
|
||||
} else if (req.image) {
|
||||
vector = JSON.stringify(
|
||||
await imageEmbeddingService.generateEmbedding(req.image, project.teamId),
|
||||
)
|
||||
} else {
|
||||
throw new HTTPException(400, { message: 'Provide a search image or source asset.' })
|
||||
}
|
||||
|
||||
const folders = await this.assetSvc.getDescendantFolderIds(folderId)
|
||||
return this.searchByEmbedding(folders, req, vector, dimensions, {
|
||||
projectId: project.id,
|
||||
mediaType: req.mediaType,
|
||||
sourceAssetId: req.sourceAssetId,
|
||||
})
|
||||
}
|
||||
|
||||
private async requireEmbeddingAgent(teamId: string): Promise<void> {
|
||||
const agent =
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
|
||||
? null
|
||||
: await this.prismaClient.agent.findFirst({
|
||||
where: { teamId, type: 'embedding', enabled: true },
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
if (!agent) {
|
||||
throw new HTTPException(422, {
|
||||
message: 'Embedding agent not configured or disabled for this team.',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private async searchByEmbedding(
|
||||
folderIds: string[],
|
||||
req: Pick<
|
||||
SearchRequest,
|
||||
'assetType' | 'showSymlink' | 'conditions' | 'operator' | 'first' | 'after' | 'previewFormat'
|
||||
>,
|
||||
vector: string,
|
||||
dimensions: 768 | 1536,
|
||||
visual?: {
|
||||
projectId: string
|
||||
mediaType?: ImageSearchRequest['mediaType']
|
||||
sourceAssetId?: string
|
||||
},
|
||||
): Promise<PaginatedData<AssetInfo[]>> {
|
||||
const column = dimensions === 768 ? Prisma.sql`ae.embedding_768` : Prisma.sql`ae.embedding`
|
||||
const distance = Prisma.sql`(${column} <=> ${vector}::vector)`
|
||||
const builder = new SqlQueryBuilder()
|
||||
.from(Prisma.sql`assets a JOIN asset_embeddings ae ON a.id = ae.asset_id`)
|
||||
.addWhere(Prisma.sql`a.is_deleted = false`)
|
||||
.addWhere(Prisma.sql`${column} IS NOT NULL`)
|
||||
|
||||
if (folderIds.length > 0) {
|
||||
builder.addWhere(Prisma.sql`a.parent_id = ANY(${folderIds})`)
|
||||
}
|
||||
|
||||
if (visual) {
|
||||
builder
|
||||
.addWhere(Prisma.sql`a.project_id = ${visual.projectId} AND a.type = 'file'`)
|
||||
.addWhere(
|
||||
visual.mediaType
|
||||
? Prisma.sql`a.media_type LIKE ${visual.mediaType + '/%'}`
|
||||
: Prisma.sql`(a.media_type LIKE 'image/%' OR a.media_type LIKE 'video/%')`,
|
||||
)
|
||||
if (visual.sourceAssetId) {
|
||||
builder.addWhere(Prisma.sql`a.id <> ${visual.sourceAssetId}`)
|
||||
}
|
||||
} else {
|
||||
const targetTypes =
|
||||
req.assetType === 'folder' ? [AssetType.folder] : [AssetType.file, AssetType.version_stack]
|
||||
builder.addWhere(
|
||||
req.showSymlink
|
||||
? Prisma.sql`(a.type = ANY(${targetTypes}::"AssetType"[]) OR (a.type = 'symlink' AND a.target_id IN (SELECT id FROM assets WHERE type = ANY(${targetTypes}::"AssetType"[]))))`
|
||||
: Prisma.sql`a.type = ANY(${targetTypes}::"AssetType"[])`,
|
||||
)
|
||||
}
|
||||
|
||||
builder.addSearchConditions(req.operator, req.conditions, { skipNameContains: true })
|
||||
const nameCond = req.conditions?.find((c) => c.field === 'name' && c.operator === 'contains')
|
||||
if (nameCond) {
|
||||
const name = String(nameCond.value)
|
||||
const ngrams = generateSearchNgrams(name)
|
||||
if (ngrams.length > 0) builder.addWhere(Prisma.sql`a.name_ngram @> ${ngrams}::text[]`)
|
||||
builder.addWhere(Prisma.sql`a.name ILIKE ${'%' + name + '%'}`)
|
||||
}
|
||||
|
||||
const countQuery = builder.select(Prisma.sql`COUNT(*)`).build()
|
||||
const sizeQuery = builder
|
||||
.select(Prisma.sql`SUM(COALESCE(a.size_byte, 0))::bigint as sum`)
|
||||
.build()
|
||||
const requestedLimit = req.first || 20
|
||||
const limit = requestedLimit <= 0 || requestedLimit > 200 ? 20 : requestedLimit
|
||||
const offset = req.after ? decodeCursor(req.after) : 0
|
||||
const resultQuery = builder
|
||||
.select(
|
||||
Prisma.sql`a.id as "assetId", ae.start_time as "startTime", ae.end_time as "endTime", ${distance} as "distance"`,
|
||||
)
|
||||
.orderBy(visual ? Prisma.sql`distance ASC, ae.id ASC` : Prisma.sql`distance ASC`)
|
||||
.limit(limit + 1)
|
||||
.offset(offset)
|
||||
.build()
|
||||
|
||||
const matches =
|
||||
await this.prismaClient.$queryRaw<
|
||||
{ assetId: string; startTime: number | null; endTime: number | null }[]
|
||||
>(resultQuery)
|
||||
const page = matches.slice(0, limit)
|
||||
const assetIds = [...new Set(page.map((match) => match.assetId))]
|
||||
const infos = await this.assetSvc.listAssetsByIds(assetIds, req.previewFormat)
|
||||
const byId = new Map(infos.map((item) => [item.id, item]))
|
||||
const data = page.flatMap(({ assetId, startTime, endTime }) => {
|
||||
const item = byId.get(assetId)
|
||||
return item ? [{ ...item, startTime, endTime }] : []
|
||||
})
|
||||
|
||||
const counts = await this.prismaClient.$queryRaw<{ count: bigint }[]>(countQuery)
|
||||
const total = Number(counts[0]?.count ?? 0)
|
||||
const sizes =
|
||||
total < 2000 ? await this.prismaClient.$queryRaw<{ sum: bigint | null }[]>(sizeQuery) : []
|
||||
const pageInfo: PageInfo = { total, totalSize: total < 2000 ? Number(sizes[0]?.sum ?? 0) : -1 }
|
||||
if (matches.length > limit) pageInfo.cursor = encodeCursor(offset + limit)
|
||||
return { data, pageInfo }
|
||||
}
|
||||
}
|
||||
|
||||
export const searchService = new SearchService()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { GoogleGenAI } from '@google/genai'
|
||||
import { LruTtlCache } from '@shumai/core/src/cache/lru-ttl-cache'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { getGemmaEmbeddingEndpoint } from './gemma-embedding-endpoint'
|
||||
|
||||
export interface TextEmbeddingUsage {
|
||||
model: string
|
||||
@@ -143,15 +144,7 @@ export class TextEmbeddingService {
|
||||
model: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<TextEmbeddingResult> {
|
||||
const rawBaseUrl = process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL || 'http://localhost:9379/v1'
|
||||
const normalized = rawBaseUrl.replace(/\/+$/, '')
|
||||
const endpoint = normalized.endsWith('/embeddings')
|
||||
? normalized
|
||||
: normalized.endsWith('/v1')
|
||||
? `${normalized}/embeddings`
|
||||
: `${normalized}/v1/embeddings`
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
const response = await fetch(getGemmaEmbeddingEndpoint(), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
|
||||
@@ -63,3 +63,21 @@ export type SearchFilter = z.infer<typeof searchFilterSchema>
|
||||
|
||||
export const searchRequestSchema = searchFilterSchema.extend(paginationParamsSchema.shape)
|
||||
export type SearchRequest = z.infer<typeof searchRequestSchema>
|
||||
|
||||
export const MAX_SEARCH_IMAGE_BASE64_LENGTH = 1_500_000
|
||||
export const imageSearchMediaTypeSchema = z.enum(['image', 'video'])
|
||||
export type ImageSearchMediaType = z.infer<typeof imageSearchMediaTypeSchema>
|
||||
|
||||
export const imageSearchRequestSchema = searchFilterSchema
|
||||
.pick({ conditions: true, operator: true, previewFormat: true })
|
||||
.extend({
|
||||
...paginationParamsSchema.shape,
|
||||
mediaType: imageSearchMediaTypeSchema.optional(),
|
||||
image: z.base64().min(1).max(MAX_SEARCH_IMAGE_BASE64_LENGTH).optional(),
|
||||
sourceAssetId: z.string().min(1).optional(),
|
||||
})
|
||||
.refine(({ image, sourceAssetId }) => Boolean(image) !== Boolean(sourceAssetId), {
|
||||
message: 'Provide one search image or source asset.',
|
||||
})
|
||||
|
||||
export type ImageSearchRequest = z.infer<typeof imageSearchRequestSchema>
|
||||
|
||||
@@ -25,9 +25,10 @@ import {
|
||||
ArrowRight,
|
||||
Copy,
|
||||
Layers,
|
||||
ScanSearch,
|
||||
} from 'lucide-react'
|
||||
import { CopyContextMenuSub } from './copy-submenu'
|
||||
import type { CopyKind } from './copy-options'
|
||||
import { isImageItem, type CopyKind } from './copy-options'
|
||||
|
||||
interface FileBrowserContextMenuProps {
|
||||
item: AssetInfo | null
|
||||
@@ -36,6 +37,7 @@ interface FileBrowserContextMenuProps {
|
||||
onDelete: (items: AssetInfo[]) => void
|
||||
onDownload: (items: AssetInfo[]) => void
|
||||
onCopy?: (kind: CopyKind, items: AssetInfo[]) => void
|
||||
onFindSimilar?: (item: AssetInfo) => void
|
||||
onRestore: (items: AssetInfo[]) => void
|
||||
onArchive?: (items: AssetInfo[]) => void
|
||||
onRestoreArchive?: (items: AssetInfo[]) => void
|
||||
@@ -69,6 +71,7 @@ export function FileBrowserContextMenu({
|
||||
onDelete,
|
||||
onDownload,
|
||||
onCopy,
|
||||
onFindSimilar,
|
||||
onRestore,
|
||||
onArchive,
|
||||
onRestoreArchive,
|
||||
@@ -222,6 +225,15 @@ export function FileBrowserContextMenu({
|
||||
)
|
||||
}
|
||||
|
||||
const findSimilarItem = onFindSimilar &&
|
||||
(item.type === 'file' || item.type === 'version_stack') &&
|
||||
isImageItem(item) && (
|
||||
<ContextMenuItem onSelect={() => onFindSimilar(item)}>
|
||||
<ScanSearch className="mr-2 h-4 w-4" />
|
||||
<span>{m.find_similar()}</span>
|
||||
</ContextMenuItem>
|
||||
)
|
||||
|
||||
const contextMenuContent =
|
||||
isItemSelected && selectedIds.size > 1 ? (
|
||||
<ContextMenuContent
|
||||
@@ -234,6 +246,7 @@ export function FileBrowserContextMenu({
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
<span>{m.download()}</span>
|
||||
</ContextMenuItem>
|
||||
{findSimilarItem}
|
||||
<CopyContextMenuSub
|
||||
items={itemsToModify}
|
||||
context={{
|
||||
@@ -331,6 +344,7 @@ export function FileBrowserContextMenu({
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
<span>{m.download()}</span>
|
||||
</ContextMenuItem>
|
||||
{findSimilarItem}
|
||||
<CopyContextMenuSub
|
||||
items={itemsToModify}
|
||||
context={{
|
||||
|
||||
@@ -29,6 +29,8 @@ import { ManageVersionsDialog } from '../manage-versions-dialog'
|
||||
import { FilePreviewDialog } from '../file-preview-dialog'
|
||||
import { FileBrowserContentSkeleton } from '../loading-skeletons'
|
||||
import { FileBrowserContextMenu } from './context-menu'
|
||||
import { FindSimilarDialog } from '../search/find-similar-dialog'
|
||||
import { useSemanticSearchEnabled } from '../search/use-semantic-search-enabled'
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
@@ -156,6 +158,13 @@ export function FileBrowser({
|
||||
allowDownload = true,
|
||||
}: FileBrowserProps) {
|
||||
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
|
||||
const [similarImage, setSimilarImage] = useState<AssetInfo | null>(null)
|
||||
const semanticSearchEnabled = useSemanticSearchEnabled(
|
||||
teamId,
|
||||
Boolean(
|
||||
rootFolderId && !isShareView && !isPublic && !isRecents && !isRecentlyDeleted && !collection,
|
||||
),
|
||||
)
|
||||
const [manageVersionsStackId, setManageVersionsStackId] = useState<string | null>(null)
|
||||
const [moveCopyMode, setMoveCopyMode] = useState<'move' | 'copy' | null>(null)
|
||||
const [itemsToMoveCopy, setItemsToMoveCopy] = useState<AssetInfo[]>([])
|
||||
@@ -1179,6 +1188,7 @@ export function FileBrowser({
|
||||
onDelete={handleDelete}
|
||||
onDownload={handleDownload}
|
||||
onCopy={handleCopy}
|
||||
onFindSimilar={semanticSearchEnabled && rootFolderId ? setSimilarImage : undefined}
|
||||
onNewFolder={handleNewFolder}
|
||||
onUploadFile={handleUploadFilesClick}
|
||||
onUploadFolder={handleUploadFolderClick}
|
||||
@@ -1239,6 +1249,16 @@ export function FileBrowser({
|
||||
)}
|
||||
{renderContent()}
|
||||
|
||||
{semanticSearchEnabled && similarImage && rootFolderId && (
|
||||
<FindSimilarDialog
|
||||
image={similarImage}
|
||||
folderId={rootFolderId}
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
onClose={() => setSimilarImage(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{moveCopyMode && (
|
||||
<MoveCopyDialog
|
||||
isOpen={!!moveCopyMode}
|
||||
|
||||
@@ -112,8 +112,9 @@ export const FilePreview = ({ item, showDuration = false, matchDuration }: FileP
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full h-full flex items-center justify-center">
|
||||
<div className="relative w-full h-full flex items-center justify-center">
|
||||
<File className="w-8 h-8 fill-primary/60 stroke-0" />
|
||||
{overlay}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { AssetInfo, ImageSearchMediaType } from '@shumai/dtos'
|
||||
import { useInfiniteQuery } from '@tanstack/react-query'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/ui/components/ui/toggle-group'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { searchByImage } from './search-by-image'
|
||||
import { SearchResultCards } from './search-result-cards'
|
||||
|
||||
type MediaFilter = ImageSearchMediaType | 'all'
|
||||
|
||||
export function FindSimilarDialog({
|
||||
image,
|
||||
folderId,
|
||||
teamId,
|
||||
projectId,
|
||||
onClose,
|
||||
}: {
|
||||
image: AssetInfo
|
||||
folderId: string
|
||||
teamId: string
|
||||
projectId: string
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [filter, setFilter] = useState<MediaFilter>('all')
|
||||
const sourceAssetId =
|
||||
image.versionStack?.versions.find((version) => version.current)?.id ?? image.id
|
||||
const { ref, inView } = useInView()
|
||||
const { data, error, isLoading, hasNextPage, isFetchingNextPage, fetchNextPage } =
|
||||
useInfiniteQuery({
|
||||
queryKey: ['find-similar', folderId, sourceAssetId, filter],
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
searchByImage(
|
||||
folderId,
|
||||
{
|
||||
sourceAssetId,
|
||||
conditions: [],
|
||||
operator: 'AND',
|
||||
mediaType: filter === 'all' ? undefined : filter,
|
||||
first: 20,
|
||||
after: pageParam,
|
||||
},
|
||||
signal,
|
||||
),
|
||||
initialPageParam: undefined as string | undefined,
|
||||
getNextPageParam: (page) => page.pageInfo.cursor,
|
||||
retry: false,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage && !error) void fetchNextPage()
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage, error])
|
||||
|
||||
const results = data?.pages.flatMap((page) => page.data) ?? []
|
||||
const total = data?.pages[0]?.pageInfo.total
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onClose()
|
||||
}}
|
||||
>
|
||||
<DialogContent className="flex h-[85vh] flex-col overflow-hidden p-0 sm:max-w-4xl">
|
||||
<DialogHeader className="px-6 pt-5 pr-12">
|
||||
<DialogTitle>{m.find_similar()}</DialogTitle>
|
||||
<DialogDescription className="truncate">{image.name}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 border-b px-6 pb-4">
|
||||
<ToggleGroup
|
||||
aria-label={m.image_search_media_filter()}
|
||||
type="single"
|
||||
variant="outline"
|
||||
value={filter}
|
||||
onValueChange={(value) => {
|
||||
if (value === 'all' || value === 'image' || value === 'video') setFilter(value)
|
||||
}}
|
||||
>
|
||||
<ToggleGroupItem value="all">{m.all()}</ToggleGroupItem>
|
||||
<ToggleGroupItem value="image">{m.image_search_images()}</ToggleGroupItem>
|
||||
<ToggleGroupItem value="video">{m.image_search_videos()}</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
{total != null && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{m.matched_items({ count: String(total) })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<ScrollArea className="min-h-0 flex-1 [&>div>div]:block!">
|
||||
<div className="p-6">
|
||||
{(isLoading || isFetchingNextPage) && (
|
||||
<p
|
||||
role="status"
|
||||
className="flex items-center gap-2 py-2 text-sm text-muted-foreground"
|
||||
>
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
{m.loading()}
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="py-2 text-sm text-destructive">
|
||||
{error.message}
|
||||
</p>
|
||||
)}
|
||||
{!isLoading && !error && results.length === 0 && (
|
||||
<p className="py-2 text-sm text-muted-foreground">{m.no_records_matched()}</p>
|
||||
)}
|
||||
<SearchResultCards teamId={teamId} projectId={projectId} results={results} />
|
||||
{hasNextPage && !error && <div ref={ref} className="h-1" />}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { ImageSearchRequest } from '@shumai/dtos'
|
||||
|
||||
export async function searchByImage(
|
||||
folderId: string,
|
||||
request: ImageSearchRequest,
|
||||
signal: AbortSignal,
|
||||
) {
|
||||
const res = await client.api.folders[':folderId']['image-search'].$post(
|
||||
{ param: { folderId }, json: request },
|
||||
{ init: { signal } },
|
||||
)
|
||||
if (!res.ok) {
|
||||
if (res.status === 409) throw new Error(m.image_search_waiting_for_index())
|
||||
if (res.status === 422) throw new Error(m.enable_embedding_agent_hint())
|
||||
if (res.status === 400 || res.status === 413) throw new Error(m.image_search_invalid_image())
|
||||
throw new Error(m.search_failed())
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
@@ -9,15 +9,17 @@ import { Input } from '@/ui/components/ui/input'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { AlertCircle, ChevronDown, ChevronUp, Loader2, Search, X } from 'lucide-react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { toast } from 'sonner'
|
||||
import { FileCard } from '@/ui/components/file-browser/file-card'
|
||||
import { FolderCard } from '@/ui/components/file-browser/folder-card'
|
||||
import { FilterPanel } from './filter-panel'
|
||||
import { SearchImagePicker, type SearchImage } from './search-image-picker'
|
||||
import { SearchResultCards } from './search-result-cards'
|
||||
import { useSemanticSearchEnabled } from './use-semantic-search-enabled'
|
||||
import { searchByImage } from './search-by-image'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
interface SearchFilterDialogProps {
|
||||
@@ -59,22 +61,15 @@ export function SearchFilterDialog({
|
||||
const [triggerQuery, setTriggerQuery] = useState(initialKeyword)
|
||||
const [isSemantic, setIsSemantic] = useState<boolean>(false)
|
||||
|
||||
const { data: teamSettings } = useQuery({
|
||||
queryKey: ['team-settings', teamId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].settings.$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error(m.failed_load_settings())
|
||||
return (await res.json()) as { semanticSearchEnabled: boolean }
|
||||
},
|
||||
enabled: open,
|
||||
})
|
||||
|
||||
const semanticSearchEnabled = teamSettings?.semanticSearchEnabled ?? false
|
||||
const [attachedImage, setAttachedImage] = useState<SearchImage | null>(null)
|
||||
const [imageSubmitted, setImageSubmitted] = useState(false)
|
||||
const submittedImage = imageSubmitted ? attachedImage : null
|
||||
const semanticSearchEnabled = useSemanticSearchEnabled(teamId, open)
|
||||
|
||||
// Sync back if changed from outside, clear on close
|
||||
useEffect(() => {
|
||||
setAttachedImage(null)
|
||||
setImageSubmitted(false)
|
||||
if (open) {
|
||||
setSearchInput(initialKeyword)
|
||||
setTriggerQuery(initialKeyword)
|
||||
@@ -101,10 +96,9 @@ export function SearchFilterDialog({
|
||||
return result
|
||||
}, [isSemantic, triggerQuery, conditions])
|
||||
|
||||
const hasActiveCriteria = useMemo(() => {
|
||||
const activeText = triggerQuery
|
||||
return activeText.trim() !== '' || conditions.some((c) => String(c.value || '').trim() !== '')
|
||||
}, [triggerQuery, conditions])
|
||||
const hasActiveCriteria = attachedImage
|
||||
? Boolean(submittedImage && semanticSearchEnabled)
|
||||
: triggerQuery.trim() !== '' || conditions.some((c) => String(c.value || '').trim() !== '')
|
||||
|
||||
const { mutate: saveAsCollection, isPending: isSaving } = useMutation({
|
||||
mutationFn: async () => {
|
||||
@@ -157,11 +151,33 @@ export function SearchFilterDialog({
|
||||
isLoading,
|
||||
isFetchingNextPage,
|
||||
fetchNextPage,
|
||||
refetch,
|
||||
hasNextPage,
|
||||
error: searchError,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: ['search-preview', teamId, assetId, combinedConditions, isSemantic, triggerQuery],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
queryKey: [
|
||||
'search-preview',
|
||||
teamId,
|
||||
assetId,
|
||||
combinedConditions,
|
||||
isSemantic,
|
||||
triggerQuery,
|
||||
submittedImage?.id,
|
||||
],
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
if (submittedImage) {
|
||||
return searchByImage(
|
||||
assetId,
|
||||
{
|
||||
image: submittedImage.base64,
|
||||
conditions: combinedConditions,
|
||||
operator: 'AND',
|
||||
first: 20,
|
||||
after: pageParam || undefined,
|
||||
},
|
||||
signal,
|
||||
)
|
||||
}
|
||||
const activeText = triggerQuery
|
||||
const res = await client.api.folders[':folderId'].search.$post({
|
||||
param: { folderId: assetId },
|
||||
@@ -186,16 +202,17 @@ export function SearchFilterDialog({
|
||||
},
|
||||
enabled: open && hasActiveCriteria,
|
||||
staleTime: 500,
|
||||
gcTime: submittedImage ? 0 : undefined,
|
||||
retry: false,
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||
if (inView && hasNextPage && !isFetchingNextPage && !searchError) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage, searchError])
|
||||
|
||||
const flattenedResults = useMemo(() => {
|
||||
return searchResults?.pages.flatMap((page) => page.data) || []
|
||||
@@ -217,20 +234,6 @@ export function SearchFilterDialog({
|
||||
setConditions([])
|
||||
}
|
||||
|
||||
const handleResultClick = (item: AssetInfo) => {
|
||||
if (item.type === 'folder') {
|
||||
window.open(`/projects/${projectId}/folders/${item.id}`, '_blank', 'noopener,noreferrer')
|
||||
} else {
|
||||
const fileId = item.versionStack ? item.versionStack.id : item.id!
|
||||
const searchParams = new URLSearchParams()
|
||||
if (item.startTime !== undefined && item.startTime !== null && item.startTime > 0) {
|
||||
searchParams.set('start', String(item.startTime))
|
||||
}
|
||||
const query = searchParams.toString() ? `?${searchParams.toString()}` : ''
|
||||
window.open(`/projects/${projectId}/files/${fileId}${query}`, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
}
|
||||
|
||||
const activeFiltersCount = conditions.filter((c) => c.value !== '').length
|
||||
|
||||
return (
|
||||
@@ -244,37 +247,72 @@ export function SearchFilterDialog({
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
setTriggerQuery(searchInput.trim())
|
||||
if (attachedImage) {
|
||||
if (!semanticSearchEnabled) return
|
||||
if (imageSubmitted) void refetch()
|
||||
else setImageSubmitted(true)
|
||||
} else {
|
||||
setTriggerQuery(searchInput.trim())
|
||||
}
|
||||
}}
|
||||
className="flex flex-col gap-3 mt-2"
|
||||
>
|
||||
<div className="relative">
|
||||
<Input
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
placeholder={
|
||||
isSemantic ? m.search_by_content_placeholder() : m.search_by_name_placeholder()
|
||||
}
|
||||
className="w-full pl-4 pr-24 py-3 bg-background border-border rounded-xl text-sm h-12 focus-visible:ring-2 focus-visible:ring-primary/20 shadow-sm"
|
||||
/>
|
||||
{searchInput && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSearchInput('')
|
||||
setTriggerQuery('')
|
||||
}}
|
||||
className="absolute right-20 top-1/2 -translate-y-1/2 p-1 rounded-md text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
{attachedImage ? (
|
||||
<div className="flex h-12 items-center gap-2 rounded-xl border bg-background pl-2 pr-36 shadow-sm">
|
||||
<img
|
||||
alt=""
|
||||
src={`data:image/jpeg;base64,${attachedImage.base64}`}
|
||||
className="size-8 rounded-sm object-cover"
|
||||
/>
|
||||
<span className="truncate text-sm">{attachedImage.name}</span>
|
||||
</div>
|
||||
) : (
|
||||
<Input
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
placeholder={
|
||||
isSemantic ? m.search_by_content_placeholder() : m.search_by_name_placeholder()
|
||||
}
|
||||
className={cn(
|
||||
'h-12 w-full rounded-xl border-border bg-background py-3 pl-4 text-sm shadow-sm focus-visible:ring-2 focus-visible:ring-primary/20',
|
||||
isSemantic && semanticSearchEnabled ? 'pr-36' : 'pr-28',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className="absolute right-1.5 top-1.5 bottom-1.5 px-4 bg-primary hover:bg-primary/90 text-primary-foreground text-xs font-semibold rounded-lg flex items-center justify-center transition-colors shadow-sm"
|
||||
>
|
||||
{m.search_button()}
|
||||
</button>
|
||||
<div className="absolute inset-y-1.5 right-1.5 flex items-center gap-1">
|
||||
{(searchInput || attachedImage) && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={attachedImage ? m.image_search_remove() : m.clear_search()}
|
||||
onClick={() => {
|
||||
setAttachedImage(null)
|
||||
setImageSubmitted(false)
|
||||
setSearchInput('')
|
||||
setTriggerQuery('')
|
||||
}}
|
||||
className="rounded-md p-1 text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</button>
|
||||
)}
|
||||
{isSemantic && semanticSearchEnabled && (
|
||||
<SearchImagePicker
|
||||
onSelect={(image) => {
|
||||
setAttachedImage(image)
|
||||
setImageSubmitted(false)
|
||||
setSearchInput('')
|
||||
setTriggerQuery('')
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className="flex h-full items-center justify-center rounded-lg bg-primary px-4 text-xs font-semibold text-primary-foreground transition-colors hover:bg-primary/90"
|
||||
>
|
||||
{m.search_button()}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 py-1">
|
||||
@@ -286,6 +324,8 @@ export function SearchFilterDialog({
|
||||
setIsSemantic(checked)
|
||||
setSearchInput('')
|
||||
setTriggerQuery('')
|
||||
setAttachedImage(null)
|
||||
setImageSubmitted(false)
|
||||
setConditions([])
|
||||
}}
|
||||
disabled={!semanticSearchEnabled}
|
||||
@@ -380,9 +420,9 @@ export function SearchFilterDialog({
|
||||
<Search className="w-10 h-10 text-muted-foreground/30 mb-2" />
|
||||
<h3 className="text-sm font-semibold text-foreground/80">{m.ready_to_search()}</h3>
|
||||
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
|
||||
{m.type_query_instruction()}
|
||||
{attachedImage ? m.image_search_submit_instruction() : m.type_query_instruction()}
|
||||
</p>
|
||||
{isSemantic && (
|
||||
{isSemantic && !attachedImage && (
|
||||
<p className="text-xs text-muted-foreground/80 max-w-md mt-4 mx-auto border-t border-border/60 pt-3">
|
||||
{m.semantic_search_note()}
|
||||
</p>
|
||||
@@ -420,42 +460,16 @@ export function SearchFilterDialog({
|
||||
{m.no_records_matched()}
|
||||
</h3>
|
||||
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
|
||||
{m.try_adjusting_spelling()}
|
||||
{!attachedImage && m.try_adjusting_spelling()}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
{flattenedResults.map((record) => {
|
||||
const itemKey =
|
||||
record.startTime != null && record.endTime != null
|
||||
? `${record.id}-${record.startTime}-${record.endTime}`
|
||||
: record.id
|
||||
if (record.type === 'folder') {
|
||||
return (
|
||||
<FolderCard
|
||||
key={itemKey}
|
||||
item={record}
|
||||
hideCheckbox
|
||||
hideActions
|
||||
disabled
|
||||
onSelect={() => handleResultClick(record)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<FileCard
|
||||
key={itemKey}
|
||||
teamId={teamId}
|
||||
item={record}
|
||||
hideCheckbox
|
||||
hideActions
|
||||
disabled
|
||||
onSelect={() => handleResultClick(record)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<SearchResultCards
|
||||
results={flattenedResults}
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
/>
|
||||
{(hasNextPage || isFetchingNextPage) && (
|
||||
<div ref={ref} className="p-4 flex justify-center items-center">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { MAX_SEARCH_IMAGE_BASE64_LENGTH } from '@shumai/dtos'
|
||||
import { ImagePlus, Loader2 } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { ulid } from 'ulid'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
export interface SearchImage {
|
||||
id: string
|
||||
name: string
|
||||
base64: string
|
||||
}
|
||||
|
||||
async function resizeImage(file: File): Promise<SearchImage> {
|
||||
if (file.type && !file.type.startsWith('image/')) throw new Error('Invalid file type')
|
||||
|
||||
const bitmap = await createImageBitmap(file)
|
||||
try {
|
||||
const landscape = bitmap.width >= bitmap.height
|
||||
const scale = Math.min(
|
||||
1,
|
||||
(landscape ? 1280 : 720) / bitmap.width,
|
||||
(landscape ? 720 : 1280) / bitmap.height,
|
||||
)
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = Math.max(1, Math.round(bitmap.width * scale))
|
||||
canvas.height = Math.max(1, Math.round(bitmap.height * scale))
|
||||
const context = canvas.getContext('2d')
|
||||
if (!context) throw new Error('Unable to resize image')
|
||||
|
||||
context.fillStyle = '#fff'
|
||||
context.fillRect(0, 0, canvas.width, canvas.height)
|
||||
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height)
|
||||
const dataUrl = canvas.toDataURL('image/jpeg', 0.85)
|
||||
const base64 = dataUrl.split(',')[1]
|
||||
if (!base64 || base64.length > MAX_SEARCH_IMAGE_BASE64_LENGTH) {
|
||||
throw new Error('Invalid resized image')
|
||||
}
|
||||
return { id: ulid(), name: file.name, base64 }
|
||||
} finally {
|
||||
bitmap.close()
|
||||
}
|
||||
}
|
||||
|
||||
export function SearchImagePicker({ onSelect }: { onSelect: (image: SearchImage) => void }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [error, setError] = useState(false)
|
||||
const [processing, setProcessing] = useState(false)
|
||||
const input = useRef<HTMLInputElement>(null)
|
||||
const pending = useRef<AbortController | null>(null)
|
||||
|
||||
useEffect(() => () => pending.current?.abort(), [])
|
||||
|
||||
function setPickerOpen(next: boolean) {
|
||||
if (!next) {
|
||||
pending.current?.abort()
|
||||
pending.current = null
|
||||
setError(false)
|
||||
setProcessing(false)
|
||||
}
|
||||
setOpen(next)
|
||||
}
|
||||
|
||||
async function selectFile(file: File) {
|
||||
if (pending.current) return
|
||||
const controller = new AbortController()
|
||||
pending.current = controller
|
||||
setError(false)
|
||||
setProcessing(true)
|
||||
try {
|
||||
const image = await resizeImage(file)
|
||||
if (controller.signal.aborted) return
|
||||
onSelect(image)
|
||||
setPickerOpen(false)
|
||||
} catch {
|
||||
if (!controller.signal.aborted) setError(true)
|
||||
} finally {
|
||||
if (pending.current === controller) {
|
||||
pending.current = null
|
||||
setProcessing(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setPickerOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="icon-sm" aria-label={m.image_search_attach()}>
|
||||
<ImagePlus className="size-4" />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent
|
||||
onPaste={(event) => {
|
||||
event.stopPropagation()
|
||||
const image = Array.from(event.clipboardData.files).find((file) =>
|
||||
file.type.startsWith('image/'),
|
||||
)
|
||||
if (!image) return
|
||||
event.preventDefault()
|
||||
void selectFile(image)
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{m.image_search_attach()}</DialogTitle>
|
||||
<DialogDescription>{m.image_search_select_description()}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<input
|
||||
ref={input}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
hidden
|
||||
onChange={(event) => {
|
||||
const file = event.currentTarget.files?.[0]
|
||||
event.currentTarget.value = ''
|
||||
if (file) void selectFile(file)
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-28 w-full border-dashed"
|
||||
disabled={processing}
|
||||
onClick={() => input.current?.click()}
|
||||
onDragOver={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
}}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
const files = event.dataTransfer.files
|
||||
if (files.length === 1) void selectFile(files[0])
|
||||
else setError(true)
|
||||
}}
|
||||
>
|
||||
{processing && <Loader2 className="size-4 animate-spin" />}
|
||||
{m.image_search_choose_image()}
|
||||
</Button>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{m.image_search_invalid_image()}
|
||||
</p>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { FileCard } from '@/ui/components/file-browser/file-card'
|
||||
import { FolderCard } from '@/ui/components/file-browser/folder-card'
|
||||
|
||||
export function SearchResultCards({
|
||||
results,
|
||||
teamId,
|
||||
projectId,
|
||||
}: {
|
||||
results: AssetInfo[]
|
||||
teamId: string
|
||||
projectId: string
|
||||
}) {
|
||||
function openResult(item: AssetInfo) {
|
||||
const projectPath = `/projects/${projectId}`
|
||||
if (item.type === 'folder') {
|
||||
window.open(`${projectPath}/folders/${item.id}`, '_blank', 'noopener,noreferrer')
|
||||
return
|
||||
}
|
||||
const fileId = item.versionStack?.id ?? item.id
|
||||
const query = item.startTime != null && item.startTime > 0 ? `?start=${item.startTime}` : ''
|
||||
window.open(`${projectPath}/files/${fileId}${query}`, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
{results.map((item) => {
|
||||
const key =
|
||||
item.startTime != null && item.endTime != null
|
||||
? `${item.id}-${item.startTime}-${item.endTime}`
|
||||
: item.id
|
||||
return item.type === 'folder' ? (
|
||||
<FolderCard
|
||||
key={key}
|
||||
item={item}
|
||||
hideCheckbox
|
||||
hideActions
|
||||
disabled
|
||||
onSelect={() => openResult(item)}
|
||||
/>
|
||||
) : (
|
||||
<FileCard
|
||||
key={key}
|
||||
teamId={teamId}
|
||||
item={item}
|
||||
hideCheckbox
|
||||
hideActions
|
||||
disabled
|
||||
onSelect={() => openResult(item)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
|
||||
export function useSemanticSearchEnabled(teamId: string, enabled: boolean): boolean {
|
||||
const { data } = useQuery({
|
||||
queryKey: ['team-settings', teamId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].settings.$get({ param: { teamId } })
|
||||
if (!res.ok) throw new Error(m.failed_load_settings())
|
||||
return await res.json()
|
||||
},
|
||||
enabled,
|
||||
})
|
||||
|
||||
return data?.semanticSearchEnabled ?? false
|
||||
}
|
||||
@@ -1100,6 +1100,17 @@
|
||||
"search_by_content_placeholder": "Search records by content...",
|
||||
"search_by_name_placeholder": "Search records by name...",
|
||||
"search_button": "Search",
|
||||
"find_similar": "Find similar",
|
||||
"image_search_images": "Images",
|
||||
"image_search_videos": "Videos",
|
||||
"image_search_media_filter": "Media type",
|
||||
"image_search_attach": "Attach an image",
|
||||
"image_search_select_description": "Choose an image, drag it here, or paste it from your clipboard.",
|
||||
"image_search_choose_image": "Choose image",
|
||||
"image_search_remove": "Remove image",
|
||||
"image_search_invalid_image": "Choose a supported image file.",
|
||||
"image_search_waiting_for_index": "This image is waiting to be indexed. Try again after processing finishes.",
|
||||
"image_search_submit_instruction": "Select Search to find matches for this image.",
|
||||
"semantic_search": "Semantic Search",
|
||||
"semantic_search_requires_embedding": "* Semantic search requires an enabled embedding agent.",
|
||||
"active_filters": "active",
|
||||
|
||||
@@ -1055,6 +1055,17 @@
|
||||
"search_by_content_placeholder": "콘텐츠로 레코드 검색...",
|
||||
"search_by_name_placeholder": "이름으로 레코드 검색...",
|
||||
"search_button": "검색",
|
||||
"find_similar": "유사한 미디어 찾기",
|
||||
"image_search_images": "이미지",
|
||||
"image_search_videos": "동영상",
|
||||
"image_search_media_filter": "미디어 유형",
|
||||
"image_search_attach": "이미지 첨부",
|
||||
"image_search_select_description": "이미지를 선택하거나 여기로 끌어다 놓거나 클립보드에서 붙여넣으세요.",
|
||||
"image_search_choose_image": "이미지 선택",
|
||||
"image_search_remove": "이미지 제거",
|
||||
"image_search_invalid_image": "지원되는 이미지 파일을 선택하세요.",
|
||||
"image_search_waiting_for_index": "이미지가 인덱싱 대기 중입니다. 처리가 끝나면 다시 시도하세요.",
|
||||
"image_search_submit_instruction": "검색을 선택하여 이 이미지와 유사한 미디어를 찾으세요.",
|
||||
"semantic_search": "시맨틱 검색",
|
||||
"semantic_search_requires_embedding": "* 시맨틱 검색을 사용하려면 임베딩 에이전트를 활성화해야 합니다.",
|
||||
"active_filters": "개 적용됨",
|
||||
|
||||
@@ -1100,6 +1100,17 @@
|
||||
"search_by_content_placeholder": "按内容搜索记录...",
|
||||
"search_by_name_placeholder": "按名称搜索记录...",
|
||||
"search_button": "搜索",
|
||||
"find_similar": "查找相似素材",
|
||||
"image_search_images": "图片",
|
||||
"image_search_videos": "视频",
|
||||
"image_search_media_filter": "媒体类型",
|
||||
"image_search_attach": "添加图片",
|
||||
"image_search_select_description": "选择图片、将图片拖到此处,或从剪贴板粘贴图片。",
|
||||
"image_search_choose_image": "选择图片",
|
||||
"image_search_remove": "移除图片",
|
||||
"image_search_invalid_image": "请选择支持的图片文件。",
|
||||
"image_search_waiting_for_index": "此图片正在等待建立索引。请在处理完成后重试。",
|
||||
"image_search_submit_instruction": "点击搜索以查找与此图片相似的素材。",
|
||||
"semantic_search": "语义搜索",
|
||||
"semantic_search_requires_embedding": "* 语义搜索需要启用嵌入智能体。",
|
||||
"active_filters": "个激活",
|
||||
|
||||
Reference in New Issue
Block a user