diff --git a/frontend/src/api/auth/index.ts b/frontend/src/api/auth/index.ts index 2cd3f706..247eff20 100644 --- a/frontend/src/api/auth/index.ts +++ b/frontend/src/api/auth/index.ts @@ -102,6 +102,12 @@ export interface UserPreferences { last_active_tenant_id?: number | null // oidc_only_login 为 true 表示账号由 OIDC 自动开通且用户尚未设置已知密码。 oidc_only_login?: boolean + // gallery 记录图库的个人状态:搜索激活模式与逐字段开/关(按属性 ID)。 + // 每次变更整体覆盖该块;后端会校验 mode 与 status 取值。 + gallery?: { + mode?: 'all' | 'custom' + status?: Record + } } // 用户信息接口 diff --git a/frontend/src/api/image-gallery/index.ts b/frontend/src/api/image-gallery/index.ts new file mode 100644 index 00000000..a7c0fc6f --- /dev/null +++ b/frontend/src/api/image-gallery/index.ts @@ -0,0 +1,206 @@ +import { get } from '@/utils/request'; + +// --------------------------------------------------------------------------- +// Image Gallery API +// +// The gallery lists every image asset inside a knowledge base. An "asset" is a +// single rendered image projected from a chunk's `image_info` array (a document +// chunk can carry several images). The backend de-duplicates, filters by +// keyword / attribute / enabled state, sorts and paginates in the database, so +// a page costs the same however many images the KB holds. +// +// What the gallery shows (filters, searchable fields, sort options) is NOT +// hardcoded here: GET /knowledge-bases/:id/gallery-config returns the +// self-describing contract (attribute sources, resolved per-attribute usage, +// the caller's search activation state) and the UI renders from it. New +// backend attributes therefore light up with no frontend change. +// --------------------------------------------------------------------------- + +/** One image projected from a chunk, as returned by the backend. */ +export interface ImageAsset { + /** Stable id: "#". */ + id: string; + /** Owning chunk id. */ + chunk_id: string; + /** Owning knowledge (document) id. */ + knowledge_id: string; + /** Human-readable name of the source knowledge item (document title). */ + source_name: string; + /** Owning chunk type; empty for images discovered on a text (document) chunk. */ + chunk_type: string; + /** Rendered image URL. */ + url: string; + /** Pre-transform source reference, when different. */ + original_url: string; + /** Model-generated image description. */ + caption: string; + /** Extracted OCR text, if any. */ + ocr_text: string; + /** Observed attribute map keyed by source-local attribute name. */ + attrs: Record; + /** Mirrors the owning chunk's enabled flag. */ + is_enabled: boolean; + /** Mirrors the owning chunk's index status. */ + status: number; + /** Owning chunk creation time (ISO 8601). */ + created_at: string; + /** Owning chunk last-update time (ISO 8601). */ + updated_at: string; +} + +export type ImageSortOrder = 'asc' | 'desc'; + +/** Query parameters accepted by GET /knowledge-bases/:id/images. */ +export interface ImageListParams { + /** Case-insensitive substring match against the union of searchIn fields. */ + keyword?: string; + /** + * Namespaced attribute ids to search ("builtin:caption"). Must be + * in_searchfield=true in the contract; the backend drops anything else. + * Omit to use the backend default (builtin caption + ocr_text). + */ + searchIn?: string[]; + /** Namespaced attribute id to sort by; must be in_sortfield=true. */ + sortBy?: string; + sortOrder?: ImageSortOrder; + /** Restrict to chunks with this enabled state. Omit to include both. */ + isEnabled?: boolean; + /** + * Attribute filters keyed by namespaced attribute id. Values within one + * attribute are OR-ed; attributes are AND-ed. Sent as one `attr_filters` + * JSON query param. + */ + attrFilters?: Record; + /** + * Per-value verdicts keyed by namespaced attribute id, each mapping a value + * to "off" (hide images carrying it) or "on" (show them regardless). An + * omitted value stays neutral. Sent as one `attr_rules` JSON query param; + * "on" outranks "off" when both speak about the same image. + */ + attrRules?: Record>; + page?: number; + pageSize?: number; +} + +export interface ImageListResult { + items: ImageAsset[]; + total: number; + page: number; + pageSize: number; +} + +/** + * List image assets for a knowledge base. Attribute references use the + * namespaced ids from the gallery contract; the backend validates them + * against the contract and silently drops ineligible ones. + */ +export async function listGalleryImages( + kbId: string, + params: ImageListParams = {}, +): Promise { + const query = new URLSearchParams(); + if (params.keyword) query.set('keyword', params.keyword); + if (params.searchIn && params.searchIn.length) { + query.set('search_in', params.searchIn.join(',')); + } + if (params.sortBy) query.set('sort_by', params.sortBy); + if (params.sortOrder) query.set('sort_order', params.sortOrder); + if (typeof params.isEnabled === 'boolean') { + query.set('is_enabled', String(params.isEnabled)); + } + if (params.attrFilters && Object.keys(params.attrFilters).length) { + query.set('attr_filters', JSON.stringify(params.attrFilters)); + } + if (params.attrRules && Object.keys(params.attrRules).length) { + query.set('attr_rules', JSON.stringify(params.attrRules)); + } + if (params.page) query.set('page', String(params.page)); + if (params.pageSize) query.set('page_size', String(params.pageSize)); + + const qs = query.toString(); + const res = await get<{ + success: boolean; + data: ImageAsset[]; + total: number; + page: number; + page_size: number; + }>(`/api/v1/knowledge-bases/${kbId}/images${qs ? `?${qs}` : ''}`); + + return { + items: res.data, + total: res.total, + page: res.page, + pageSize: res.page_size, + }; +} + +// --------------------------------------------------------------------------- +// Gallery contract (GET /knowledge-bases/:id/gallery-config) +// --------------------------------------------------------------------------- + +/** Resolved per-attribute usage flags after all config tiers merged. */ +export interface GalleryAttrUsage { + in_filter: boolean; + in_searchfield: boolean; + in_sortfield: boolean; +} + +/** + * One attribute as the contract serves it: the source's declaration with + * every config tier's overrides merged in. `id` is namespaced + * (":"); `usage_from` names the highest tier that touched + * the usage ("source" | "system" | "kb" | "user"). + */ +/** + * One allowed value of an attribute. + * + * Display text is deliberately split: `label` is the short name that fits a + * filter checkbox, `description` is the sentence shown where there is room + * (a tooltip). `value` stays the raw machine value — it is what gets + * filtered and searched, and it is never localized. + */ +export interface GalleryAttrValue { + value: string; + label: string; + description?: string; +} + +export interface GalleryResolvedAttr { + id: string; + source: string; + /** Source-local attribute name, as stored in image_info attrs. */ + name: string; + /** "text" | "date" | "extent" | "presence" | "keywords" */ + type: string; + values?: GalleryAttrValue[]; + /** Short on-screen name; falls back to the attribute id when absent. */ + label: string; + /** Sentence explaining the attribute; shown where there is room. */ + description?: string; + usage: GalleryAttrUsage; + usage_from: string; +} + +/** The self-describing contract the gallery UI renders from. */ +export interface GalleryConfig { + /** Live source ids in priority order. */ + attribute_sources: string[]; + attributes: GalleryResolvedAttr[]; + /** Search activation mode: "all" (default) or "custom". */ + mode: 'all' | 'custom'; + /** Per-attribute search toggles ("on"/"off"); consulted in custom mode. */ + status: Record; +} + +/** Fetch the gallery contract for a knowledge base. */ +export async function fetchGalleryConfig(kbId: string): Promise { + const res = await get<{ success: boolean; data: GalleryConfig }>( + `/api/v1/knowledge-bases/${kbId}/gallery-config`, + ); + return { + attribute_sources: res.data.attribute_sources ?? [], + attributes: res.data.attributes ?? [], + mode: res.data.mode === 'custom' ? 'custom' : 'all', + status: res.data.status ?? {}, + }; +} diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.ts index 26af0d99..c4ae43a6 100644 --- a/frontend/src/api/knowledge-base/index.ts +++ b/frontend/src/api/knowledge-base/index.ts @@ -72,6 +72,156 @@ export function listKnowledgeBases(params?: { // (deleted row, registry miss, transient infra // failure). Operators recover via the global // Vector Stores settings page. +// --------------------------------------------------------------------------- +// Image attribute observation (route 3). Mirrors backend types in +// internal/types/image_attrs.go. The backend registry is the single source of +// truth; the frontend fetches it from GET /image-attrs/schema and renders the +// attribute panel dynamically. The types/constants below mirror the v1 shape +// so the UI still compiles and can render a fallback before the schema loads. +// --------------------------------------------------------------------------- + +// One allowed value of an image attribute. +// +// Display text is split for the same reasons the gallery splits it: `label` is +// what fits on a checkbox or a table cell, `description` is the sentence that +// explains the value where there is room. `value` stays the raw machine value. +export interface ImageAttrValue { + value: string; + label: string; + description?: string; +} + +// One observable image attribute, as returned by the schema endpoint. The +// registry is authoritative for both the behaviour and the wording: label, +// description and the per-value texts are what the settings panel shows to an +// operator who does not read identifiers like "contain.text". +export interface ImageAttrSpec { + name: string; + type: 'extent' | 'presence'; + values?: ImageAttrValue[]; + question: string; + label: string; + description?: string; + consumers?: string[]; +} + +// One attribute match: attribute `prop` equals `is`. +export interface ImageAttrCondition { + prop: string; + is: string; +} + +// The OCR clause of the attribute -> work policy. +export interface ImageOCRAction { + on: ImageAttrCondition[]; + on_unobserved: boolean; +} + +// The attribute -> work policy sent back to the API (snake_case JSON). +export interface ImageActionsConfig { + ocr: ImageOCRAction; +} + +// Canonical registry + built-in actions returned by GET /image-attrs/schema. +export interface ImageAttrSchema { + version: string; + prompt: string; + attributes: ImageAttrSpec[]; + default_actions: ImageActionsConfig; +} + +// Mirrors backend types.DefaultImageActions. The schema endpoint returns the +// authoritative copy; this is the fallback used before the schema loads (e.g. +// in create mode, where no knowledge base id exists yet to query). +export const DEFAULT_IMAGE_ACTIONS: ImageActionsConfig = { + ocr: { + on: [ + { prop: 'contain.text', is: 'block' }, + { prop: 'contain.data_visual', is: 'true' }, + ], + on_unobserved: true, + }, +}; + +// Display-only fallback used before a KB exists (create mode) so the panel can +// render without a network call. It mirrors the registry for layout and wording +// only; the endpoint response is authoritative whenever it loads. +export const FALLBACK_IMAGE_ATTR_SCHEMA: ImageAttrSchema = { + version: 'attrs/2', + prompt: 'observe/1', + attributes: [ + { + name: 'contain.text', + type: 'extent', + values: [ + { value: 'none', label: 'None', description: 'no text at all' }, + { value: 'sparse', label: 'Sparse', description: 'a few words — a logo, a road sign, a single label' }, + { value: 'block', label: 'Block', description: 'a block of body text — a screenshot, a table, a document page' }, + ], + question: '', + label: 'Text in the image', + description: 'How much body text the picture itself carries.', + consumers: ['ocr'], + }, + { + name: 'contain.data_visual', + type: 'presence', + values: [ + { value: 'true', label: 'Yes', description: 'a chart, graph or diagram with plotted values' }, + { value: 'false', label: 'No', description: 'a photo, drawing, icon or decoration' }, + ], + question: '', + label: 'Data visual', + description: 'Whether the picture conveys data as a chart, graph, diagram or infographic.', + consumers: ['ocr'], + }, + ], + default_actions: DEFAULT_IMAGE_ACTIONS, +}; + +// Mirrors backend types.MergeImageActions: a custom OCR.On replaces the default +// OCR.On wholesale (the "on" list is a unit); a config that only sets +// on_unobserved keeps the default On. The result is what the form seeds with +// and what makes an empty custom table safe to open. +export function mergeImageActions( + custom?: ImageActionsConfig | null, +): ImageActionsConfig { + if (custom && custom.ocr && custom.ocr.on && custom.ocr.on.length > 0) { + return { ocr: { on: custom.ocr.on, on_unobserved: custom.ocr.on_unobserved } }; + } + return { + ocr: { + on: DEFAULT_IMAGE_ACTIONS.ocr.on.map((c) => ({ ...c })), + on_unobserved: DEFAULT_IMAGE_ACTIONS.ocr.on_unobserved, + }, + }; +} + +// Fetch the canonical image-attribute registry + default actions from the +// backend. The registry drives the attribute panel; the default actions seed +// the OCR-condition display. +export async function fetchImageAttrSchema(kbId: string): Promise { + // The registry is global, not per-KB. The backend exposes it at a top-level + // route, the same shape as the other read-only KB-editor helpers + // (GET /api/v1/chunker/preview, GET /api/v1/system/parser-engines). kbId is + // kept in the signature for callers that pass KB context. + void kbId; + const res = await get<{ success: boolean; data: ImageAttrSchema }>( + `/api/v1/image-attrs/schema`, + ); + return res.data; +} + +// Mirrors backend types.ImageProcessingConfig (snake_case JSON). The UI edits +// the attribute-observation switch and the on_unobserved toggle; saving sends +// the snapshot back with those fields updated so API-side settings survive a +// UI edit. +export interface ImageProcessingConfig { + model_id?: string; + image_actions?: ImageActionsConfig; + image_attrs_enabled?: boolean; +} + export type VectorStoreSource = 'env' | 'user' | 'shared' | 'unavailable'; export type VectorStoreStatus = 'available' | 'unavailable'; @@ -88,6 +238,7 @@ export function createKnowledgeBase(data: { description?: string; type?: 'document' | 'faq'; chunking_config?: any; + image_processing_config?: ImageProcessingConfig; embedding_model_id?: string; summary_model_id?: string; auto_tag_config?: { enabled: boolean; model_id?: string; max_tags?: number; skip_if_tagged?: boolean }; @@ -144,7 +295,7 @@ export function updateKnowledgeBase(id: string, data: { description?: string; config?: { chunking_config?: any; - image_processing_config?: any; + image_processing_config?: ImageProcessingConfig; faq_config?: any; wiki_config?: { synthesis_model_id?: string; diff --git a/frontend/src/i18n/localeKeyAudit.ts b/frontend/src/i18n/localeKeyAudit.ts index 952afdae..c3079374 100644 --- a/frontend/src/i18n/localeKeyAudit.ts +++ b/frontend/src/i18n/localeKeyAudit.ts @@ -104,6 +104,17 @@ const EXTRA_PREFIXES = [ 'organization.role.', 'inviteRegister.', 'modelSettings.builtinModels.', + // Image-attribute display text is keyed by the backend attribute registry + // (imageAttr.contain_text.label …), built from the schema response at runtime, + // so it is registered as a whole prefix: a new backend attribute must keep + // being translated without touching the audit. + 'imageAttr.', + // Gallery attribute labels are keyed by the namespaced attribute id from + // the gallery contract, likewise runtime-built; static labels for the few + // builtin attributes ship in the locale files as + // knowledgeEditor.wikiBrowser.gallery.attr.builtin_caption …, and + // everything else falls back to the contract wording. + 'knowledgeEditor.wikiBrowser.gallery.attr.', ] as const /** Keys that must survive pruning even when static analysis misses them. */ diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 98320984..5c0d877a 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -2999,8 +2999,8 @@ export default { duplicate: 'Duplicate' }, pin: { - pin: 'Pin to Top', - unpin: 'Unpin', + pin: 'Pin to Top', + unpin: 'Unpin', pinSuccess: 'Pinned', unpinSuccess: 'Unpinned', failed: 'Operation failed' @@ -3462,6 +3462,71 @@ export default { editingBadge: 'Editing', pageActions: 'Page actions', tabDocuments: 'Documents', + tabGallery: 'Gallery', + gallery: { + panelFilter: 'Filter', + panelSearch: 'Search', + enableFilter: 'Enable filter', + searchAll: 'Search all fields', + verdictDefault: '-', + verdictOff: 'off', + verdictOn: 'on', + searchScope: 'Search scope', + scopeAll: 'All', + scopeCustom: 'Custom', + filterScope: 'Filter', + filterOff: 'Show all', + filterOn: 'Custom', + editSearch: 'Open search settings', + editFilter: 'Open filter settings', + pin: 'Pin to the right', + unpin: 'Unpin', + title: 'Gallery', + searchPlaceholder: 'Search image content', + sortByLabel: 'Sort by', + orderAsc: 'Ascending', + orderDesc: 'Descending', + filtersTitle: 'Filters', + searchFields: 'Search fields', + modeAll: 'All fields', + modeCustom: 'Custom', + keywordsPlaceholder: 'Separate keywords with commas', + applyAll: 'Apply to all attributes', + count: '{count} images', + empty: 'No images in this knowledge base yet', + emptyFiltered: 'No images match the current filters', + attrSection: 'Image attributes', + noAttrs: 'No image attributes available', + attributes: 'Attributes', + caption: 'Caption', + ocr: 'OCR text', + source: 'Source', + noCaption: 'No caption', + noOcr: 'No OCR text', + chunkType: 'Type', + viewerClose: 'Close', + prev: 'Previous', + next: 'Next', + openSource: 'Open source document', + imageLoadError: 'Image failed to load', + // Display names for the builtin attributes the gallery itself + // declares. Attributes contributed by other sources fall back to the + // pipeline's own wording (see the imageAttr namespace). + attr: { + builtin_caption: 'Caption', + builtin_caption_description: 'The model-generated description of the image.', + builtin_ocr_text: 'OCR text', + builtin_ocr_text_description: 'Text extracted from the image by OCR.', + builtin_created_at: 'Created time', + builtin_created_at_description: 'When the owning document chunk was created.', + builtin_updated_at: 'Updated time', + builtin_updated_at_description: 'When the owning document chunk was last updated.', + builtin_is_enabled: 'Enabled', + builtin_is_enabled_description: 'Whether the owning document chunk takes part in retrieval.', + builtin_is_enabled_value_true: 'Enabled', + builtin_is_enabled_value_false: 'Disabled', + }, + }, tabGraph: 'Graph', tabGraphTip: 'A graph of links between Wiki pages (page-link graph). This is NOT the same as the LLM-extracted entity-relationship Knowledge Graph configured under "KB Settings → Knowledge Graph".', searchPlaceholder: 'Search wiki pages...', @@ -3879,7 +3944,16 @@ export default { descriptionLanguageAuto: 'Follow document language', customInstructionsLabel: 'Image Processing Instructions', customInstructionsDescription: 'Add visual priorities while OCR and Markdown output contracts remain fixed', - customInstructionsPlaceholder: 'For example: prioritize nameplates, model numbers, alarm codes, and table units…' + customInstructionsPlaceholder: 'For example: prioritize nameplates, model numbers, alarm codes, and table units…', + imageAttrsLabel: 'Image attribute observation', + imageAttrsDescription: 'When on, each image is first observed for attributes and described, then the attributes decide whether an OCR round runs for the text in the image. When off, the basic mode applies: every image is described and OCR runs for all of them', + imageAttrsSchemaLabel: 'Observable image attributes', + imageAttrsSchemaDescription: 'The model observes the attributes below (defined by the backend registry) to drive the OCR policy', + imageAttrsOcrConditions: 'Trigger OCR based on the observed attribute conditions', + imageAttrsOcrConditionsDesc: 'When the observed attributes match the conditions below, OCR runs on the image', + imageAttrsOcrOnUnobserved: 'Run OCR when image-attribute observation fails', + imageAttrsOcrOnUnobservedDesc: 'When the model fails to observe the image attributes correctly, OCR runs by default so body text is never lost; turn off to skip. (A small vision model such as 4B, or custom image-instruction prompts that conflict with the system prompt, can cause the observation to fail; 8B and above rarely fail, so leaving this on is recommended)', + imagePipelineKbNote: 'Defaults follow the knowledge base settings; adjust them for this task' } } }, @@ -7009,7 +7083,7 @@ export default { empty: 'No MCP endpoints yet', disabled: 'Disabled', cardSummary: '{tools} tools · {scope}', - scopeAll: 'All knowledge bases', + scopeAll: 'All knowledge bases', scopeCount: '{count} knowledge bases', create: 'New endpoint', editTitle: 'Edit MCP endpoint', @@ -7657,5 +7731,34 @@ export default { capabilityRequired: 'Select at least one capability', loadFailed: 'Failed to load platform API keys', createFailed: 'Failed to create platform API key' + }, + // Display text for the observed image attributes, keyed by attribute name. + // Attribute names escape their dots (contain.text → contain_text) because + // vue-i18n walks a key segment by segment on the dots, so a literal + // 'contain.text' key would never resolve. An attribute without a translation + // falls back to the registry's own wording. + // + // Every value carries a short label for compact controls (a filter + // checkbox) and a description for wherever there is room (a tooltip). One + // bundle therefore serves both the settings panel and the image gallery, + // including the gallery's fallback for attributes it does not declare. + imageAttr: { + contain_text: { + label: 'Text in the image', + description: 'How much body text the picture itself carries. Decides whether reading its text is worth a separate OCR pass.', + values: { + none: { label: 'None', description: 'no text at all' }, + sparse: { label: 'Sparse', description: 'a few words — a logo, a road sign, a single label' }, + block: { label: 'Block', description: 'a block of body text — a screenshot, a table, a document page' } + } + }, + contain_data_visual: { + label: 'Data visual', + description: 'Whether the picture conveys data as a chart, graph, diagram or infographic. Such images keep their labels on the OCR path even when the text looks sparse.', + values: { + 'true': { label: 'Yes', description: 'a chart, graph or diagram with plotted values' }, + 'false': { label: 'No', description: 'a photo, drawing, icon or decoration' } + } + } } } diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index baed7c5f..cb3c6938 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -2999,8 +2999,8 @@ export default { duplicate: '複製' }, pin: { - pin: '先頭に固定', - unpin: '固定を解除', + pin: '先頭に固定', + unpin: '固定を解除', pinSuccess: '固定しました', unpinSuccess: '固定を解除しました', failed: '操作に失敗しました' @@ -3462,6 +3462,71 @@ export default { editingBadge: '編集中', pageActions: 'ページ操作', tabDocuments: 'ドキュメント', + tabGallery: 'ギャラリー', + gallery: { + panelFilter: 'フィルター設定', + panelSearch: '検索設定', + enableFilter: 'フィルター有効', + searchAll: '全フィールド検索', + verdictDefault: '-', + verdictOff: 'off', + verdictOn: 'on', + searchScope: '検索範囲', + scopeAll: 'すべて', + scopeCustom: 'カスタム', + filterScope: 'フィルター', + filterOff: 'すべて表示', + filterOn: 'カスタム', + editSearch: '検索設定を開く', + editFilter: 'フィルター設定を開く', + pin: '右側に固定', + unpin: '固定を解除', + title: 'ギャラリー', + searchPlaceholder: '画像の内容を検索', + sortByLabel: '並べ替え', + orderAsc: '昇順', + orderDesc: '降順', + filtersTitle: 'フィルター', + searchFields: '検索フィールド', + modeAll: 'すべてのフィールド', + modeCustom: 'カスタム', + keywordsPlaceholder: 'キーワードはカンマで区切る', + applyAll: '全属性に一括設定', + count: '{count} 枚の画像', + empty: 'このナレッジベースに画像はまだありません', + emptyFiltered: '現在のフィルターに一致する画像はありません', + attrSection: '画像属性', + noAttrs: '画像属性はありません', + attributes: '属性', + caption: '説明', + ocr: 'OCR テキスト', + source: 'ソース', + noCaption: '説明なし', + noOcr: 'OCR テキストなし', + chunkType: '種類', + viewerClose: '閉じる', + prev: '前へ', + next: '次へ', + openSource: 'ソース文書を開く', + imageLoadError: '画像の読み込みに失敗しました', + // Display names for the builtin attributes the gallery itself + // declares. Attributes contributed by other sources fall back to the + // pipeline's own wording (see the imageAttr namespace). + attr: { + builtin_caption: '説明', + builtin_caption_description: 'モデルが生成した画像の説明', + builtin_ocr_text: 'OCR テキスト', + builtin_ocr_text_description: 'OCR で画像から抽出した文字', + builtin_created_at: '作成日時', + builtin_created_at_description: '所属ドキュメントチャンクの作成日時', + builtin_updated_at: '更新日時', + builtin_updated_at_description: '所属ドキュメントチャンクの最終更新日時', + builtin_is_enabled: '有効状態', + builtin_is_enabled_description: '所属ドキュメントチャンクが検索対象かどうか', + builtin_is_enabled_value_true: '有効', + builtin_is_enabled_value_false: '無効', + }, + }, tabGraph: 'グラフ', tabGraphTip: 'Wikiページ間のリンクを表したグラフ(ページリンクグラフ)です。「ナレッジベース設定 → ナレッジグラフ」で設定する、LLMが抽出するエンティティ・リレーションのナレッジグラフとは異なります。', searchPlaceholder: 'Wikiページを検索...', @@ -3879,7 +3944,16 @@ export default { descriptionLanguageAuto: 'ドキュメントの言語に従う', customInstructionsLabel: '画像処理の指示', customInstructionsDescription: 'OCRとMarkdown出力の仕様は固定したまま、視覚的に優先する対象を追加できます', - customInstructionsPlaceholder: '例: 銘板、型番、アラームコード、表の単位を優先する…' + customInstructionsPlaceholder: '例: 銘板、型番、アラームコード、表の単位を優先する…', + imageAttrsLabel: '画像属性の観察', + imageAttrsDescription: 'オンにすると各画像を先に「属性観察+説明」し、その属性で画像内テキストへの OCR 実行可否を決定します。オフは基本モード:全画像を1枚ずつ説明し全て OCR します', + imageAttrsSchemaLabel: '観察可能な画像属性', + imageAttrsSchemaDescription: 'モデルは以下の属性(バックエンドのレジストリで定義)を観察して OCR ポリシーを決めます', + imageAttrsOcrConditions: '観察した属性条件に基づいて OCR を実行', + imageAttrsOcrConditionsDesc: '観察した属性が以下の条件を満たす場合、その画像に OCR を実行します', + imageAttrsOcrOnUnobserved: '画像属性の観察に失敗した場合も OCR を実行', + imageAttrsOcrOnUnobservedDesc: 'モデルが画像属性を正しく観察できなかった場合、本文テキストを逃さないようデフォルトで OCR を実行します。オフにするとスキップします。(4B など小規模な視覚モデルを使う場合や、カスタムの画像指示がシステムプロンプトと衝突する場合に観察が失敗することがあります。8B 以上は失敗の可能性が低く、オフは推奨しません)', + imagePipelineKbNote: 'デフォルトはナレッジベースの設定に従い、今回のタスク向けに調整できます' } } }, @@ -7009,7 +7083,7 @@ export default { empty: 'MCP エンドポイントはまだありません', disabled: '停止中', cardSummary: '{tools} 個のツール · {scope}', - scopeAll: 'すべてのナレッジベース', + scopeAll: 'すべてのナレッジベース', scopeCount: '{count} 個のナレッジベース', create: 'エンドポイントを作成', editTitle: 'MCP エンドポイントを編集', @@ -7657,5 +7731,28 @@ export default { capabilityRequired: '権限を1つ以上選択してください', loadFailed: 'プラットフォームAPIキーの読み込みに失敗しました', createFailed: 'プラットフォームAPIキーの作成に失敗しました' + }, + // 観察属性の表示文言。属性名で索引し、ここでは翻訳のみを担当します。 + // 属性名のドットはアンダースコアにエスケープします(contain.text → contain_text)—— + // vue-i18n はキーをドットで辿るため、リテラルの 'contain.text' は解決できません。 + // 未翻訳の属性はバックエンド登録表の説明にフォールバックします。 + imageAttr: { + contain_text: { + label: '画像内のテキスト量', + description: '画像自体がどれだけ本文テキストを含むか。テキスト読み取りのために別途 OCR を行う価値があるかを判断します。', + values: { + none: { label: 'テキストなし', description: 'テキストは一切含まれていません' }, + sparse: { label: 'わずかな文字', description: 'わずかな文字のみ —— ロゴ、道路標識、単一のラベル' }, + block: { label: 'まとまった本文', description: 'まとまった本文 —— スクリーンショット、表、文書ページ' } + } + }, + contain_data_visual: { + label: 'データ可視化', + description: '画像がグラフ・図表・ダイアグラム・インフォグラフィックとしてデータを伝えているか。文字が少なく見えても OCR の対象に残します。', + values: { + 'true': { label: 'はい', description: 'はい —— グラフ・図表・ダイアグラム' }, + 'false': { label: 'いいえ', description: 'いいえ —— 写真・イラスト・アイコン・装飾' } + } + } } } diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index cfa180c6..32256a35 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -845,7 +845,7 @@ export default { empty: '아직 MCP 엔드포인트가 없습니다', disabled: '비활성', cardSummary: '도구 {tools}개 · {scope}', - scopeAll: '모든 지식 베이스', + scopeAll: '모든 지식 베이스', scopeCount: '지식 베이스 {count}개', create: '새 엔드포인트', editTitle: 'MCP 엔드포인트 편집', @@ -4067,7 +4067,16 @@ export default { descriptionLanguageAuto: '문서 언어 자동 사용', customInstructionsLabel: '이미지 처리 지침', customInstructionsDescription: 'OCR 및 Markdown 형식은 유지하면서 시각적 우선순위를 추가합니다', - customInstructionsPlaceholder: '예: 명판, 모델 번호, 경고 코드 및 표 단위를 중점적으로 인식…' + customInstructionsPlaceholder: '예: 명판, 모델 번호, 경고 코드 및 표 단위를 중점적으로 인식…', + imageAttrsLabel: '이미지 속성 관찰', + imageAttrsDescription: '켜면 각 이미지를 먼저 속성 관찰+설명한 뒤, 속성에 따라 이미지 내 텍스트에 OCR을 실행할지 결정합니다. 끄면 기본 모드: 모든 이미지를 하나씩 설명하고 모두 OCR합니다', + imageAttrsSchemaLabel: '관찰 가능한 이미지 속성', + imageAttrsSchemaDescription: '모델은 아래 속성(백엔드 레지스트리 정의)을 관찰해 OCR 정책을 결정합니다', + imageAttrsOcrConditions: '관찰된 속성 조건에 따라 OCR 실행', + imageAttrsOcrConditionsDesc: '관찰된 속성이 아래 조건을 충족하면 해당 이미지에 OCR을 실행합니다', + imageAttrsOcrOnUnobserved: '이미지 속성 관찰에 실패해도 OCR 실행', + imageAttrsOcrOnUnobservedDesc: '모델이 이미지 속성을 올바르게 관찰하지 못하면 본문 텍스트 손실을 막기 위해 기본적으로 OCR을 실행합니다. 끄면 건너뜁니다. (4B 등 소형 비전 모델을 쓰거나, 사용자 지정 이미지 지시문이 시스템 프롬프트와 충돌할 때 관찰에 실패할 수 있습니다. 8B 이상은 실패 가능성이 낮아 끄지 않는 것을 권장합니다)', + imagePipelineKbNote: '기본값은 지식베이스 설정을 따르며 이번 작업에 맞게 조정할 수 있습니다' }, tableMetadataInstructions: { label: '테이블 메타데이터 지침', @@ -4433,6 +4442,71 @@ export default { editingBadge: '편집 중', pageActions: '페이지 작업', tabDocuments: '문서', + tabGallery: '갤러리', + gallery: { + panelFilter: '필터 설정', + panelSearch: '검색 설정', + enableFilter: '필터 사용', + searchAll: '전체 필드 검색', + verdictDefault: '-', + verdictOff: 'off', + verdictOn: 'on', + searchScope: '검색 범위', + scopeAll: '전체', + scopeCustom: '사용자 지정', + filterScope: '필터', + filterOff: '전체 표시', + filterOn: '사용자 지정', + editSearch: '검색 설정 열기', + editFilter: '필터 설정 열기', + pin: '오른쪽에 고정', + unpin: '고정 해제', + title: '갤러리', + searchPlaceholder: '이미지 내용 검색', + sortByLabel: '정렬', + orderAsc: '오름차순', + orderDesc: '내림차순', + filtersTitle: '필터', + searchFields: '검색 필드', + modeAll: '전체 필드', + modeCustom: '사용자 지정', + keywordsPlaceholder: '쉼표로 키워드 구분', + applyAll: '모든 속성에 일괄 적용', + count: '{count}개의 이미지', + empty: '이 지식 베이스에는 아직 이미지가 없습니다', + emptyFiltered: '현재 필터와 일치하는 이미지가 없습니다', + attrSection: '이미지 속성', + noAttrs: '사용 가능한 이미지 속성이 없습니다', + attributes: '속성', + caption: '설명', + ocr: 'OCR 텍스트', + source: '출처', + noCaption: '설명 없음', + noOcr: 'OCR 텍스트 없음', + chunkType: '유형', + viewerClose: '닫기', + prev: '이전', + next: '다음', + openSource: '출처 문서 열기', + imageLoadError: '이미지를 불러오지 못했습니다', + // Display names for the builtin attributes the gallery itself + // declares. Attributes contributed by other sources fall back to the + // pipeline's own wording (see the imageAttr namespace). + attr: { + builtin_caption: '설명', + builtin_caption_description: '모델이 생성한 이미지 설명', + builtin_ocr_text: 'OCR 텍스트', + builtin_ocr_text_description: 'OCR 로 이미지에서 추출한 텍스트', + builtin_created_at: '생성 시간', + builtin_created_at_description: '소유 문서 조각이 생성된 시각', + builtin_updated_at: '수정 시간', + builtin_updated_at_description: '소유 문서 조각이 마지막으로 수정된 시각', + builtin_is_enabled: '활성 상태', + builtin_is_enabled_description: '소유 문서 조각이 검색에 참여하는지 여부', + builtin_is_enabled_value_true: '활성화', + builtin_is_enabled_value_false: '비활성화', + }, + }, tabGraph: '그래프', tabGraphTip: 'Wiki 페이지 간의 링크 관계 그래프(페이지 링크 그래프)입니다. \'지식 베이스 설정 → 지식 그래프\'에서 구성하는 LLM 기반 엔티티-관계 지식 그래프와는 다른 개념입니다.', searchPlaceholder: 'Wiki 페이지 검색...', @@ -4933,8 +5007,8 @@ export default { sharedReadonly: '공유받음 · 읽기 전용' }, pin: { - pin: '상단 고정', - unpin: '고정 해제', + pin: '상단 고정', + unpin: '고정 해제', pinSuccess: '상단에 고정됨', unpinSuccess: '고정 해제됨', failed: '작업 실패' @@ -7657,5 +7731,28 @@ export default { myChats: '내 대화', apiChats: 'API 세션', noSessions: '대화가 없습니다' + }, + // 관찰 속성의 표시 문구. 속성 이름으로 색인하며 여기서는 번역만 담당합니다. + // 속성 이름의 점은 밑줄로 이스케이프합니다(contain.text → contain_text) —— vue-i18n 은 + // 키를 점 단위로 순회하므로 리터럴 'contain.text' 키는 해석되지 않습니다. + // 번역이 없는 속성은 백엔드 등록표의 설명으로 대체됩니다. + imageAttr: { + contain_text: { + label: '이미지 내 텍스트 양', + description: '이미지 자체가 담고 있는 본문 텍스트의 양입니다. 텍스트를 읽기 위해 별도 OCR을 돌릴 가치가 있는지 판단합니다.', + values: { + none: { label: '텍스트 없음', description: '텍스트가 전혀 없습니다' }, + sparse: { label: '약간의 글자', description: '약간의 글자만 —— 로고, 도로 표지판, 단일 라벨' }, + block: { label: '문단 단위 본문', description: '문단 단위 본문 —— 스크린샷, 표, 문서 페이지' } + } + }, + contain_data_visual: { + label: '데이터 시각화', + description: '이미지가 차트, 그래프, 도표, 인포그래픽으로 데이터를 전달하는지 여부입니다. 글자가 적어 보여도 OCR 대상으로 유지합니다.', + values: { + 'true': { label: '예', description: '예 —— 차트, 그래프, 도표' }, + 'false': { label: '아니오', description: '아니오 —— 사진, 삽화, 아이콘, 장식' } + } + } } } diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 3a3281df..b05603bf 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -845,7 +845,7 @@ export default { empty: 'Конечных точек MCP пока нет', disabled: 'Отключена', cardSummary: 'Инструментов: {tools} · {scope}', - scopeAll: 'Все базы знаний', + scopeAll: 'Все базы знаний', scopeCount: 'Баз знаний: {count}', create: 'Новая конечная точка', editTitle: 'Изменить конечную точку MCP', @@ -4067,7 +4067,16 @@ export default { descriptionLanguageAuto: 'Следовать языку документа', customInstructionsLabel: 'Инструкции обработки изображений', customInstructionsDescription: 'Добавьте визуальные приоритеты, сохраняя правила OCR и Markdown', - customInstructionsPlaceholder: 'Например: распознавать шильдики, модели, коды ошибок и единицы таблиц…' + customInstructionsPlaceholder: 'Например: распознавать шильдики, модели, коды ошибок и единицы таблиц…', + imageAttrsLabel: 'Наблюдение атрибутов изображений', + imageAttrsDescription: 'Когда включено, каждое изображение сначала наблюдается на атрибуты и описывается, затем атрибуты решают, нужен ли OCR текста в изображении. Когда выключено — базовый режим: каждое изображение описывается и распознаётся', + imageAttrsSchemaLabel: 'Наблюдаемые атрибуты изображений', + imageAttrsSchemaDescription: 'Модель наблюдает перечисленные ниже атрибуты (определены реестром бэкенда), чтобы управлять политикой OCR', + imageAttrsOcrConditions: 'Запуск OCR по наблюдаемым условиям атрибутов', + imageAttrsOcrConditionsDesc: 'Когда наблюдаемые атрибуты соответствуют условиям ниже, для изображения выполняется OCR', + imageAttrsOcrOnUnobserved: 'Запускать OCR при сбое наблюдения атрибутов изображения', + imageAttrsOcrOnUnobservedDesc: 'Если модель не смогла корректно наблюдать атрибуты изображения, OCR по умолчанию всё равно выполняется, чтобы не потерять текст; выключите, чтобы пропустить. (Небольшая визуальная модель вроде 4B или пользовательские инструкции к изображениям, конфликтующие с системным промптом, могут привести к сбою наблюдения; модели 8B и выше ошибаются редко, поэтому отключать не рекомендуется)', + imagePipelineKbNote: 'По умолчанию следуют настройкам базы знаний; можно изменить для этой задачи' }, tableMetadataInstructions: { label: 'Инструкции метаданных таблиц', @@ -4433,6 +4442,71 @@ export default { editingBadge: 'Редактирование', pageActions: 'Действия со страницей', tabDocuments: 'Документы', + tabGallery: 'Галерея', + gallery: { + panelFilter: 'Фильтр', + panelSearch: 'Поиск', + enableFilter: 'Включить фильтр', + searchAll: 'Искать во всех полях', + verdictDefault: '-', + verdictOff: 'off', + verdictOn: 'on', + searchScope: 'Область поиска', + scopeAll: 'Все', + scopeCustom: 'Вручную', + filterScope: 'Фильтр', + filterOff: 'Показывать все', + filterOn: 'Вручную', + editSearch: 'Открыть настройки поиска', + editFilter: 'Открыть настройки фильтра', + pin: 'Закрепить справа', + unpin: 'Открепить', + title: 'Галерея', + searchPlaceholder: 'Поиск по содержимому изображений', + sortByLabel: 'Сортировка', + orderAsc: 'По возрастанию', + orderDesc: 'По убыванию', + filtersTitle: 'Фильтры', + searchFields: 'Поля поиска', + modeAll: 'Все поля', + modeCustom: 'Свои поля', + keywordsPlaceholder: 'Разделяйте ключевые слова запятыми', + applyAll: 'Применить ко всем атрибутам', + count: '{count} изображений', + empty: 'В этой базе знаний пока нет изображений', + emptyFiltered: 'Нет изображений, соответствующих фильтрам', + attrSection: 'Атрибуты изображения', + noAttrs: 'Атрибуты изображения отсутствуют', + attributes: 'Атрибуты', + caption: 'Описание', + ocr: 'OCR-текст', + source: 'Источник', + noCaption: 'Нет описания', + noOcr: 'Нет OCR-текста', + chunkType: 'Тип', + viewerClose: 'Закрыть', + prev: 'Назад', + next: 'Вперёд', + openSource: 'Открыть исходный документ', + imageLoadError: 'Не удалось загрузить изображение', + // Display names for the builtin attributes the gallery itself + // declares. Attributes contributed by other sources fall back to the + // pipeline's own wording (see the imageAttr namespace). + attr: { + builtin_caption: 'Описание', + builtin_caption_description: 'Описание изображения, сгенерированное моделью.', + builtin_ocr_text: 'OCR-текст', + builtin_ocr_text_description: 'Текст, извлечённый из изображения OCR.', + builtin_created_at: 'Время создания', + builtin_created_at_description: 'Когда был создан фрагмент исходного документа.', + builtin_updated_at: 'Время изменения', + builtin_updated_at_description: 'Когда фрагмент исходного документа был изменён последний раз.', + builtin_is_enabled: 'Состояние', + builtin_is_enabled_description: 'Участвует ли фрагмент исходного документа в поиске.', + builtin_is_enabled_value_true: 'Включено', + builtin_is_enabled_value_false: 'Отключено', + }, + }, tabGraph: 'Граф', tabGraphTip: 'Граф связей между Wiki-страницами (граф ссылок страниц). Это НЕ то же самое, что граф знаний на основе сущностей и отношений, настраиваемый в «Настройки БЗ → Граф знаний».', searchPlaceholder: 'Поиск Wiki-страниц...', @@ -4933,8 +5007,8 @@ export default { sharedReadonly: 'Доступно мне · Только просмотр' }, pin: { - pin: 'Закрепить', - unpin: 'Открепить', + pin: 'Закрепить', + unpin: 'Открепить', pinSuccess: 'Закреплено', unpinSuccess: 'Откреплено', failed: 'Операция не удалась' @@ -7657,5 +7731,28 @@ export default { myChats: 'Мои чаты', apiChats: 'Сессии API', noSessions: 'Пока нет диалогов' + }, + // Тексты для наблюдаемых атрибутов изображения, с ключом по имени атрибута. + // Точки в имени атрибута экранируются подчёркиванием (contain.text → contain_text): + // vue-i18n разбирает ключ по точкам, поэтому литеральный ключ 'contain.text' + // никогда не найдётся. Атрибут без перевода отображается описанием из реестра. + imageAttr: { + contain_text: { + label: 'Количество текста на изображении', + description: 'Сколько основного текста содержит само изображение. Определяет, стоит ли запускать для него отдельный проход OCR.', + values: { + none: { label: 'Нет текста', description: 'текста нет' }, + sparse: { label: 'Немного текста', description: 'несколько слов —— логотип, дорожный знак, одна надпись' }, + block: { label: 'Блок текста', description: 'блок основного текста —— скриншот, таблица, страница документа' } + } + }, + contain_data_visual: { + label: 'Визуализация данных', + description: 'Передаёт ли изображение данные в виде графика, диаграммы, схемы или инфографики. Такие изображения остаются в очереди OCR, даже если текста на вид немного.', + values: { + 'true': { label: 'Да', description: 'да —— график, диаграмма или схема' }, + 'false': { label: 'Нет', description: 'нет —— фото, рисунок, значок или декор' } + } + } } } diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 0b76196f..504cf33a 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -845,7 +845,7 @@ export default { empty: '暂无 MCP 端点', disabled: '已停用', cardSummary: '{tools} 个工具 · {scope}', - scopeAll: '全部知识库', + scopeAll: '全部知识库', scopeCount: '{count} 个知识库', create: '新建端点', editTitle: '编辑 MCP 端点', @@ -4069,7 +4069,16 @@ export default { descriptionLanguageAuto: '自动跟随文档语言', customInstructionsLabel: '图片解析要求', customInstructionsDescription: '补充需要重点识别的视觉信息,OCR 和 Markdown 格式协议保持不变', - customInstructionsPlaceholder: '例如:重点识别设备铭牌、型号、告警代码和表格中的单位…' + customInstructionsPlaceholder: '例如:重点识别设备铭牌、型号、告警代码和表格中的单位…', + imageAttrsLabel: '图片属性观察', + imageAttrsDescription: '开启后,解析时对每张图片先「观察属性+描述」,再按属性决定是否对图内文字再跑一轮 OCR;关闭则沿用基础模式:所有图片逐张描述并全部 OCR', + imageAttrsSchemaLabel: '可观察的图片属性', + imageAttrsSchemaDescription: '模型会观察以下属性(由后端注册表定义)以驱动 OCR 策略', + imageAttrsOcrConditions: '根据观察到的属性条件触发 OCR', + imageAttrsOcrConditionsDesc: '当观察到的属性满足以下条件时,对图片进行 OCR', + imageAttrsOcrOnUnobserved: '图片属性观察失败时仍执行 OCR', + imageAttrsOcrOnUnobservedDesc: '当模型未能正确观察到图片属性时,默认仍执行 OCR 兜底,以免漏掉正文文字;关闭则跳过。(采用 4B 等小参数视觉模型,或自定义的图片解析提示词与系统提示词冲突时,可能造成观察失败;8B 及以上模型的失败概率很低,不建议关闭)', + imagePipelineKbNote: '默认跟随知识库设置,可针对本次任务调整' }, tableMetadataInstructions: { label: '表格元数据生成要求', @@ -4435,6 +4444,71 @@ export default { editingBadge: '编辑中', pageActions: '页面操作', tabDocuments: '文档', + tabGallery: '图库', + gallery: { + panelFilter: '筛选设置', + panelSearch: '搜索设置', + enableFilter: '开启筛选', + searchAll: '搜索全部字段', + verdictDefault: '-', + verdictOff: 'off', + verdictOn: 'on', + searchScope: '搜索范围', + scopeAll: '全部', + scopeCustom: '自定义', + filterScope: '筛选', + filterOff: '全显示', + filterOn: '自定义', + editSearch: '打开搜索设置', + editFilter: '打开筛选设置', + pin: '固定到右侧', + unpin: '取消固定', + title: '图库', + searchPlaceholder: '搜索图片内容', + sortByLabel: '排序', + orderAsc: '升序', + orderDesc: '降序', + filtersTitle: '筛选', + searchFields: '搜索字段', + modeAll: '全部字段', + modeCustom: '自定义', + keywordsPlaceholder: '多个关键词用逗号分隔', + applyAll: '全部属性统一设置', + count: '{count} 张图片', + empty: '该知识库暂无可浏览的图片', + emptyFiltered: '没有符合当前筛选条件的图片', + attrSection: '图片属性', + noAttrs: '暂无图片属性', + attributes: '属性', + caption: '描述', + ocr: 'OCR 文本', + source: '来源', + noCaption: '无描述', + noOcr: '无 OCR 文本', + chunkType: '类型', + viewerClose: '关闭', + prev: '上一张', + next: '下一张', + openSource: '打开来源文档', + imageLoadError: '图片加载失败', + // Display names for the builtin attributes the gallery itself + // declares. Attributes contributed by other sources fall back to the + // pipeline's own wording (see the imageAttr namespace). + attr: { + builtin_caption: '描述', + builtin_caption_description: '模型生成的图片描述', + builtin_ocr_text: 'OCR 文本', + builtin_ocr_text_description: 'OCR 从图片中提取的文字', + builtin_created_at: '创建时间', + builtin_created_at_description: '所属文档片段的创建时间', + builtin_updated_at: '更新时间', + builtin_updated_at_description: '所属文档片段的最后更新时间', + builtin_is_enabled: '启用状态', + builtin_is_enabled_description: '所属文档片段是否参与检索', + builtin_is_enabled_value_true: '已启用', + builtin_is_enabled_value_false: '已停用', + }, + }, tabGraph: '图谱', tabGraphTip: 'Wiki 页面之间的引用关系图(即页面链接图谱),与「知识库设置 → 知识图谱」中基于 LLM 抽取的实体-关系图谱不是同一个概念', searchPlaceholder: '搜索 Wiki 页面...', @@ -4935,8 +5009,8 @@ export default { sharedReadonly: '共享给我 · 仅查看' }, pin: { - pin: '置顶', - unpin: '取消置顶', + pin: '置顶', + unpin: '取消置顶', pinSuccess: '已置顶', unpinSuccess: '已取消置顶', failed: '操作失败' @@ -7659,5 +7733,28 @@ export default { myChats: '我的对话', apiChats: 'API 会话', noSessions: '暂无对话' + }, + // 图片属性的展示文案,按属性名索引(后端注册表给出属性名,这里只做翻译)。 + // 注意:属性名里的点号要转义成下划线(contain.text → contain_text)——vue-i18n 按点号 + // 逐段下钻,写成字面量 'contain.text' 的键永远取不到。 + // 未翻译的属性会回落到后端注册表自带的说明,所以新增属性不会显示成空行。 + imageAttr: { + contain_text: { + label: '图中文字量', + description: '图片自身承载多少正文文字,决定是否值得为它单独跑一轮 OCR。', + values: { + none: { label: '无文字', description: '完全没有文字' }, + sparse: { label: '少量文字', description: '只有少量文字 —— 图标、路牌、单个标签' }, + block: { label: '成段正文', description: '成段正文 —— 截图、表格、文档页面' } + } + }, + contain_data_visual: { + label: '数据可视化', + description: '图片是否以图表、曲线、示意图或信息图的方式承载数据;这类图即使看起来文字很少,也会保留在 OCR 路径上。', + values: { + 'true': { label: '是', description: '是 —— 图表、曲线或示意图' }, + 'false': { label: '否', description: '否 —— 照片、插画、图标或装饰图' } + } + } } } diff --git a/frontend/src/types/knowledgeProcess.ts b/frontend/src/types/knowledgeProcess.ts index 386528e9..8f5e3f32 100644 --- a/frontend/src/types/knowledgeProcess.ts +++ b/frontend/src/types/knowledgeProcess.ts @@ -1,5 +1,7 @@ /** Matches backend types.KnowledgeProcessOverrides (snake_case JSON). */ +import type { ImageActionsConfig } from '@/api/knowledge-base' + export interface ParserEngineRule { file_types: string[] engine: string @@ -69,5 +71,11 @@ export interface KnowledgeProcessOverrides { question_generation_config?: QuestionGenerationConfigOverride graph_enabled?: boolean extract_config?: ExtractConfigOverride + // Per-upload override of the knowledge base's attribute-observed image + // pipeline switch. + image_attrs_enabled?: boolean + // Per-task attribute -> work table; merged per action key on top of the + // knowledge base's table. + image_actions?: ImageActionsConfig parser_engine_overrides?: Record } diff --git a/frontend/src/utils/imageAttrDisplay.test.ts b/frontend/src/utils/imageAttrDisplay.test.ts new file mode 100644 index 00000000..11ece6bc --- /dev/null +++ b/frontend/src/utils/imageAttrDisplay.test.ts @@ -0,0 +1,257 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { createI18n } from 'vue-i18n' + +import type { ImageAttrSchema, ImageAttrSpec } from '@/api/knowledge-base' +import enUS from '../i18n/locales/en-US.ts' +import jaJP from '../i18n/locales/ja-JP.ts' +import koKR from '../i18n/locales/ko-KR.ts' +import ruRU from '../i18n/locales/ru-RU.ts' +import zhCN from '../i18n/locales/zh-CN.ts' +import { imageAttrConditionDisplay, imageAttrDisplay, imageAttrKeyBase } from './imageAttrDisplay.ts' + +const SPEC: ImageAttrSpec = { + name: 'contain.text', + type: 'extent', + values: [ + { value: 'none', label: 'no text at all', description: 'the image carries no text at all' }, + { value: 'sparse', label: 'a few words', description: 'a logo, a road sign, a single label' }, + { value: 'block', label: 'a block of body text', description: 'a screenshot, a table, a document page' }, + ], + question: '', + label: 'Text in the image', + description: 'How much body text the picture carries.', +} + +const PRESENCE: ImageAttrSpec = { + name: 'contain.data_visual', + type: 'presence', + question: '', + label: 'Data visual', + description: 'Whether the picture conveys data as a chart.', + values: [ + { value: 'true', label: 'yes' }, + { value: 'false', label: 'no' }, + ], +} + +const SCHEMA: ImageAttrSchema = { + version: 'attrs/2', + prompt: 'observe/1', + attributes: [SPEC, PRESENCE], + default_actions: { + ocr: { + on: [ + { prop: 'contain.text', is: 'block' }, + { prop: 'contain.data_visual', is: 'true' }, + ], + on_unobserved: true, + }, + }, +} + +/** No translations at all: the registry's own wording has to carry the panel. */ +const noI18n = { t: (key: string) => key, te: () => false } + +test('falls back to the registry wording when nothing is translated', () => { + const display = imageAttrDisplay(SPEC, noI18n.t, noI18n.te) + + assert.equal(display.name, 'contain.text') + assert.equal(display.label, 'Text in the image') + assert.equal(display.description, 'How much body text the picture carries.') + assert.deepEqual( + display.values.map((value) => value.value), + ['none', 'sparse', 'block'], + ) + assert.equal(display.values[2].label, 'a block of body text') +}) + +test('prefers the translation overlay, keyed by attribute name', () => { + // Keys escape the dots in the attribute name (see imageAttrKeyBase). + const zh: Record = { + 'imageAttr.contain_text.label': '图中文字量', + 'imageAttr.contain_text.values.block.label': '成段正文', + 'imageAttr.contain_text.values.block.description': '成段正文 —— 截图、表格或文档页面', + } + const display = imageAttrDisplay(SPEC, (key) => zh[key] ?? key, (key) => key in zh) + + assert.equal(display.label, '图中文字量') + // Untranslated pieces keep the registry wording instead of exposing the key. + assert.equal(display.description, 'How much body text the picture carries.') + assert.equal(display.values[0].label, 'no text at all') + assert.equal(display.values[2].label, '成段正文') + // The same split applies to a value's longer text. + assert.equal(display.values[2].description, '成段正文 —— 截图、表格或文档页面') + assert.equal(display.values[0].description, 'the image carries no text at all') +}) + +test('never shows a blank label when the registry omits display text', () => { + const bare: ImageAttrSpec = { + ...SPEC, + label: '', + description: undefined, + values: [ + { value: 'none', label: '', description: '' }, + { value: 'sparse', label: '', description: '' }, + { value: 'block', label: '', description: '' }, + ], + } + const display = imageAttrDisplay(bare, noI18n.t, noI18n.te) + + assert.equal(display.label, 'contain.text') + assert.equal(display.description, '') + assert.deepEqual( + display.values.map((value) => value.label), + ['none', 'sparse', 'block'], + ) +}) + +test('a presence attribute without an explicit value list offers true/false', () => { + const display = imageAttrDisplay(PRESENCE, noI18n.t, noI18n.te) + + assert.deepEqual( + display.values.map((value) => value.value), + ['true', 'false'], + ) + assert.equal(display.values[0].label, 'yes') +}) + +test('renders a policy condition in words next to its raw pair', () => { + const zh: Record = { + 'imageAttr.contain_text.label': '图中文字量', + 'imageAttr.contain_text.values.block.label': '成段正文', + } + const condition = imageAttrConditionDisplay( + { prop: 'contain.text', is: 'block' }, + SCHEMA, + (key) => zh[key] ?? key, + (key) => key in zh, + ) + + assert.equal(condition.label, '图中文字量 = 成段正文') + assert.equal(condition.raw, 'contain.text = block') +}) + +test('an unknown attribute or value degrades to its raw form', () => { + const unknownProp = imageAttrConditionDisplay( + { prop: 'contain.mystery', is: 'x' }, + SCHEMA, + noI18n.t, + noI18n.te, + ) + assert.equal(unknownProp.label, 'contain.mystery = x') + assert.equal(unknownProp.raw, 'contain.mystery = x') + + const unknownValue = imageAttrConditionDisplay( + { prop: 'contain.text', is: 'huge' }, + SCHEMA, + noI18n.t, + noI18n.te, + ) + assert.equal(unknownValue.label, 'Text in the image = huge') +}) + +// --------------------------------------------------------------------------- +// The real bundles, resolved by the real vue-i18n. +// +// The faked translators above answer a flat key lookup, so they would happily +// "translate" a key the real bundle can never resolve — which is exactly how a +// literal `'contain.text'` message key slipped through once (vue-i18n walks a +// key segment by segment on the dots, so it looked for `imageAttr` → `contain`). +// These tests therefore use createI18n, the same resolver the app runs. +// --------------------------------------------------------------------------- + +// Each bundle is wired with a literal locale key, the same shape the app's own +// createI18n call uses, so the messages argument keeps a checkable type. +const MESSAGES_BY_LOCALE = { + 'zh-CN': { 'zh-CN': zhCN }, + 'en-US': { 'en-US': enUS }, + 'ja-JP': { 'ja-JP': jaJP }, + 'ko-KR': { 'ko-KR': koKR }, + 'ru-RU': { 'ru-RU': ruRU }, +} + +type TestLocale = keyof typeof MESSAGES_BY_LOCALE + +const LOCALES = Object.keys(MESSAGES_BY_LOCALE) as TestLocale[] + +function translator(locale: TestLocale) { + const i18n = createI18n({ + legacy: false, + locale, + fallbackLocale: locale, + warnHtmlMessage: false, + messages: MESSAGES_BY_LOCALE[locale], + }) + const global = i18n.global as unknown as { + t: (key: string) => string + te: (key: string) => boolean + } + return { + t: (key: string) => global.t(key), + te: (key: string) => global.te(key), + } +} + +test('every shipped locale translates every attribute key', () => { + for (const locale of LOCALES) { + const { te, t } = translator(locale) + + for (const spec of SCHEMA.attributes) { + const base = imageAttrKeyBase(spec.name) + const keys = [ + `${base}.label`, + `${base}.description`, + ...imageAttrDisplay(spec, t, te).values.map( + (value) => `${base}.values.${value.value}.label`, + ), + ] + for (const key of keys) { + assert.equal(te(key), true, `${locale}: ${key} does not resolve`) + assert.ok(t(key).length > 0, `${locale}: ${key} is empty`) + } + } + } +}) + +test('every shipped locale translates every OCR condition key', () => { + for (const locale of LOCALES) { + const { te } = translator(locale) + + for (const cond of SCHEMA.default_actions.ocr.on) { + const base = imageAttrKeyBase(cond.prop) + assert.equal(te(`${base}.label`), true, `${locale}: ${base}.label does not resolve`) + assert.equal( + te(`${base}.values.${cond.is}.label`), + true, + `${locale}: ${base}.values.${cond.is}.label does not resolve`, + ) + } + } +}) + +test('the panel actually renders the translated text, not the registry fallback', () => { + const { t, te } = translator('zh-CN') + + for (const spec of SCHEMA.attributes) { + const display = imageAttrDisplay(spec, t, te) + + assert.match(display.label, /[\u4e00-\u9fa5]/, `${spec.name}: label is not Chinese`) + assert.match(display.description, /[\u4e00-\u9fa5]/, `${spec.name}: description is not Chinese`) + for (const value of display.values) { + assert.match( + value.label, + /[\u4e00-\u9fa5]/, + `${spec.name}.${value.value}: value is not Chinese`, + ) + } + } + + for (const cond of SCHEMA.default_actions.ocr.on) { + const display = imageAttrConditionDisplay(cond, SCHEMA, t, te) + assert.match(display.label, /[\u4e00-\u9fa5]/, `${cond.prop}=${cond.is}: condition is not Chinese`) + // The raw pair stays alongside, so the panel still lines up with the trace. + assert.equal(display.raw, `${cond.prop} = ${cond.is}`) + } +}) diff --git a/frontend/src/utils/imageAttrDisplay.ts b/frontend/src/utils/imageAttrDisplay.ts new file mode 100644 index 00000000..4894aa33 --- /dev/null +++ b/frontend/src/utils/imageAttrDisplay.ts @@ -0,0 +1,135 @@ +import type { + ImageAttrCondition, + ImageAttrSchema, + ImageAttrSpec, + ImageAttrValue, +} from '@/api/knowledge-base' + +// --------------------------------------------------------------------------- +// Display text for the image-attribute panel. +// +// The registry returned by GET /image-attrs/schema is the single source of +// truth — it carries the attribute's name, what it measures, and what each of +// its values means. That is what lets a non-technical operator read +// "Text in the image: a block of body text" instead of +// "contain.text: block", and it is why adding an attribute to the backend shows +// up here with no frontend change. +// +// Translations are an overlay keyed by the attribute name, applied on top of +// the registry text. Anything not translated yet falls back to the registry +// wording, so a brand-new attribute still reads as words rather than as a bare +// key. (The i18n keys are built at runtime from the attribute name, which is +// why the `imageAttr.` prefix is registered in localeKeyAudit's EXTRA_PREFIXES.) +// --------------------------------------------------------------------------- + +type Translate = (key: string) => string +type HasTranslation = (key: string) => boolean + +/** One allowed value of an attribute, with its meaning in words. */ +export interface ImageAttrValueDisplay { + /** The raw value as it appears in the registry and the processing trace. */ + value: string + /** The short, on-screen name for this value. */ + label: string + /** The sentence explaining the value; empty when the registry has none. */ + description: string +} + +/** One attribute as the settings panel shows it. */ +export interface ImageAttrDisplay { + /** Stable attribute key, e.g. "contain.text". Shown small, to line up with the trace. */ + name: string + /** Human-readable name, e.g. "Text in the image". */ + label: string + /** One line saying what the attribute measures. Empty when unavailable. */ + description: string + /** Every allowed value with its meaning, in the registry's order. */ + values: ImageAttrValueDisplay[] +} + +/** One OCR policy condition, in words plus the raw pair. */ +export interface ImageAttrConditionDisplay { + /** e.g. "Text in the image = a block of body text" */ + label: string + /** e.g. "contain.text = block" — keeps the panel aligned with the trace. */ + raw: string +} + +/** The values a spec declares; presence attributes list true/false implicitly. */ +function specValues(attr: ImageAttrSpec): ImageAttrValue[] { + if (attr.values && attr.values.length) return attr.values + return attr.type === 'presence' ? [{ value: 'true', label: 'true' }, { value: 'false', label: 'false' }] : [] +} + +/** + * The i18n namespace for one attribute. + * + * vue-i18n resolves a key by walking it segment by segment on the dots, so a + * literal `'contain.text'` message key is unreachable through + * `imageAttr.contain.text.label` — the lookup goes looking for `imageAttr` → + * `contain` → `text` and stops. Attribute names therefore escape their dots + * (`contain.text` → `contain_text`) to become a single resolvable segment. The + * same mapping is applied in every locale bundle, so a new attribute only needs + * its name spelled the same way. + */ +export function imageAttrKeyBase(name: string): string { + return `imageAttr.${name.replace(/\./g, '_')}` +} + +/** Look up `key`, falling back to the registry's own wording. */ +function pick(key: string, fallback: string, t: Translate, te: HasTranslation): string { + return te(key) ? t(key) : fallback +} + +/** + * Render one registry attribute for the settings panel. Never returns an empty + * label: an attribute that arrives without display text still shows its name, + * so the panel degrades to identifiers rather than to blanks. + */ +export function imageAttrDisplay( + attr: ImageAttrSpec, + t: Translate, + te: HasTranslation, +): ImageAttrDisplay { + const base = imageAttrKeyBase(attr.name) + return { + name: attr.name, + label: pick(`${base}.label`, attr.label || attr.name, t, te), + description: pick(`${base}.description`, attr.description ?? '', t, te), + values: specValues(attr).map((value) => ({ + value: value.value, + label: pick( + `${base}.values.${value.value}.label`, + value.label || value.value, + t, + te, + ), + description: pick( + `${base}.values.${value.value}.description`, + value.description ?? '', + t, + te, + ), + })), + } +} + +/** + * Render one OCR policy condition in the same words as the attribute list, + * keeping the raw `prop = value` pair so an operator can still match the panel + * against the processing trace. + */ +export function imageAttrConditionDisplay( + cond: ImageAttrCondition, + schema: ImageAttrSchema, + t: Translate, + te: HasTranslation, +): ImageAttrConditionDisplay { + const raw = `${cond.prop} = ${cond.is}` + const attr = schema.attributes.find((candidate) => candidate.name === cond.prop) + if (!attr) return { label: raw, raw } + + const display = imageAttrDisplay(attr, t, te) + const value = display.values.find((candidate) => candidate.value === cond.is) + return { label: `${display.label} = ${value ? value.label : cond.is}`, raw } +} diff --git a/frontend/src/utils/imageProcessingConfig.test.ts b/frontend/src/utils/imageProcessingConfig.test.ts new file mode 100644 index 00000000..56178c21 --- /dev/null +++ b/frontend/src/utils/imageProcessingConfig.test.ts @@ -0,0 +1,48 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { buildImageProcessingConfig } from './imageProcessingConfig.ts' + +const DEFAULT_ON = [ + { prop: 'contain.text', is: 'block' }, + { prop: 'contain.data_visual', is: 'true' }, +] + +test('saving keeps OCR conditions customised through the API', () => { + // Regression: the editor always wrote the registry default into `on`, so an + // unrelated edit replaced a KB's custom OCR conditions with the default table. + const custom = [{ prop: 'contain.text', is: 'sparse' }] + const built = buildImageProcessingConfig( + { model_id: 'vlm-1', image_attrs_enabled: true, image_actions: { ocr: { on: custom, on_unobserved: true } } }, + { imageAttrsEnabled: true, onUnobserved: false, defaultOn: DEFAULT_ON }, + ) + + assert.deepEqual(built, { + model_id: 'vlm-1', + image_attrs_enabled: true, + image_actions: { ocr: { on: custom, on_unobserved: false } }, + }) +}) + +test('a KB without custom conditions gets the registry default alongside on_unobserved', () => { + const built = buildImageProcessingConfig( + { model_id: 'vlm-1' }, + { imageAttrsEnabled: true, onUnobserved: false, defaultOn: DEFAULT_ON }, + ) + + assert.deepEqual(built, { + model_id: 'vlm-1', + image_attrs_enabled: true, + image_actions: { ocr: { on: DEFAULT_ON, on_unobserved: false } }, + }) +}) + +test('an unchanged configuration is not sent', () => { + const custom = [{ prop: 'contain.text', is: 'sparse' }] + const snapshot = { image_attrs_enabled: true, image_actions: { ocr: { on: custom, on_unobserved: true } } } + + assert.equal( + buildImageProcessingConfig(snapshot, { imageAttrsEnabled: true, onUnobserved: true, defaultOn: DEFAULT_ON }), + null, + ) +}) diff --git a/frontend/src/utils/imageProcessingConfig.ts b/frontend/src/utils/imageProcessingConfig.ts new file mode 100644 index 00000000..400b0619 --- /dev/null +++ b/frontend/src/utils/imageProcessingConfig.ts @@ -0,0 +1,44 @@ +/** One OCR trigger condition: attribute `prop` equals `is`. */ +export interface ImageAttrConditionLike { + prop: string + is: string +} + +/** The fields of the KB editor that feed image_processing_config. */ +export interface ImageProcessingEdits { + imageAttrsEnabled: boolean + onUnobserved: boolean + /** The registry's current default OCR conditions (GET /image-attrs/schema). */ + defaultOn: ImageAttrConditionLike[] +} + +/** + * Builds the image_processing_config the KB editor saves, or null when nothing + * changed. The backend replaces the whole object, so every field the editor + * does not own (model_id, ...) is carried over from the snapshot. + * + * The editor only edits the observation switch and on_unobserved, but + * on_unobserved must travel with a non-empty `on`: the backend adopts a custom + * OCR clause only when `on` is set. A knowledge base whose `on` was customised + * through the API keeps it; one without a custom list gets the registry's + * current default, so it still follows the default as it evolves. + */ +export function buildImageProcessingConfig( + snapshot: Record | null | undefined, + edits: ImageProcessingEdits, +): Record | null { + const snap = snapshot || {} + const storedOn = (snap.image_actions as { ocr?: { on?: unknown } } | undefined)?.ocr?.on + const on = Array.isArray(storedOn) && storedOn.length > 0 ? storedOn : edits.defaultOn + const built = { + ...snap, + image_attrs_enabled: edits.imageAttrsEnabled, + image_actions: { + ocr: { + on, + on_unobserved: edits.onUnobserved, + }, + }, + } + return JSON.stringify(built) === JSON.stringify(snap) ? null : built +} diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue index f93198a3..d97984c5 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -4010,4 +4010,10 @@ const handleAddToKnowledge = (answerEvent: any) => { } - + + diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue index d39564ae..d8170d67 100644 --- a/frontend/src/views/knowledge/KnowledgeBase.vue +++ b/frontend/src/views/knowledge/KnowledgeBase.vue @@ -54,6 +54,7 @@ import type { KnowledgeProcessOverrides } from '@/types/knowledgeProcess'; import { useUploadConfirmStore, type UploadConfirmResult } from '@/stores/uploadConfirm'; import { useUploadTasksStore } from '@/stores/uploadTasks'; import WikiBrowser from './wiki/WikiBrowser.vue'; +import ImageGallery from './gallery/ImageGallery.vue'; import { getWikiStats } from '@/api/wiki'; import { isKnowledgeParseInFlight, @@ -91,7 +92,7 @@ const kbLoading = ref(false); const docListLoading = ref(true); const isFAQ = computed(() => (kbInfo.value?.type || '') === 'faq'); const isWiki = computed(() => !!kbInfo.value?.indexing_strategy?.wiki_enabled); -const validTabs = ['documents', 'wiki', 'graph'] as const +const validTabs = ['documents', 'wiki', 'graph', 'gallery'] as const type KbTab = typeof validTabs[number] const initTab = validTabs.includes(route.query.tab as any) ? (route.query.tab as KbTab) : 'documents' const activeKbTab = ref(initTab); @@ -2257,9 +2258,9 @@ const handleKBEditorSuccess = (kbIdValue: string) => { + {{ $t('knowledgeEditor.wikiBrowser.tabDocuments') }} - {{ $t('knowledgeEditor.document.title') }} + + {{ $t('knowledgeEditor.wikiBrowser.tabGallery') }} +
@@ -2316,7 +2321,12 @@ const handleKBEditorSuccess = (kbIdValue: string) => { @view-graph="onViewWikiInGraph" />
-