cmvr-visual/frontend/src/views/ToolsView.vue

526 lines
18 KiB
Vue
Raw Normal View History

<script setup lang="ts">
import FolderSelect from '../components/FolderSelect.vue'
import FolderManager from '../components/FolderManager.vue'
import { useCreationFolder } from '../composables/creationFolder'
const outputFolder = useCreationFolder()
import { computed, onMounted, ref, watch } from 'vue'
import { useTaskHistory } from '../composables/taskHistory'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
ArrowRight,
MagicStick,
CopyDocument,
Document,
Headset,
DataAnalysis,
RefreshRight,
} from '@element-plus/icons-vue'
import { useCapabilitiesStore } from '../stores/capabilities'
import { useDraftsStore } from '../stores/drafts'
import { useJobsStore } from '../stores/jobs'
import { useAssetsStore } from '../stores/assets'
import { copyText, formatDate, phaseLabel, stateLabel } from '../utils/format'
import { errorMessage } from '../api'
import { buildToolRequest } from '../domain/creation/taskForms'
import type { Asset, TaskType } from '../types'
import AssetInput from '../components/AssetInput.vue'
import AssetPreview from '../components/AssetPreview.vue'
import JobDetail from '../components/JobDetail.vue'
import MathText from '../components/MathText.vue'
const route = useRoute(),
caps = useCapabilitiesStore(),
drafts = useDraftsStore(),
jobs = useJobsStore(),
assets = useAssetsStore()
const audioMode = ref<'transcribe' | 'speech'>('transcribe')
const kind = computed(() =>
route.path === '/math' ? 'math' : route.path === '/analyze' ? 'analyze' : 'audio',
)
const taskType = computed<TaskType>(() =>
kind.value === 'math'
? 'math.solve'
: kind.value === 'analyze'
? 'media.structure'
: audioMode.value === 'speech'
? 'audio.speech'
: 'audio.transcribe',
)
const capability = computed(() => caps.forTask(taskType.value)),
draft = computed(() => drafts.forTask(taskType.value, capability.value?.defaults))
const reference = computed({
get: () => (draft.value.imageAssetId ? assets.byId[draft.value.imageAssetId] || null : null),
set: (asset: Asset | null) => {
draft.value.imageAssetId = asset?.id || null
},
}),
busy = ref(false),
selectedId = ref<string | null>(null),
detailId = ref<string | null>(null),
preview = ref<Asset | null>(null)
const taskHistory = useTaskHistory(taskType),
history = taskHistory.items
const current = computed(() => (selectedId.value ? jobs.byId[selectedId.value] : history.value[0]))
const title = computed(() =>
kind.value === 'math'
? '让每一步推演,都清晰可见。'
: kind.value === 'analyze'
? '读懂画面,也读懂素材。'
: '让声音,成为创作的一部分。',
)
const subtitle = computed(() =>
kind.value === 'math'
? '数学问题交给推理,把精力留给理解与思考。'
: kind.value === 'analyze'
? '提取主体、场景和画面文字,把存量素材变成可理解的信息。'
: '从音频和视频中整理文字,或使用已配置的真实配音服务。',
)
const textResult = computed(() =>
current.value?.result?.text ? String(current.value.result.text) : '',
)
const analysis = computed(() => current.value?.result || {})
const languages = computed(
() => capability.value?.constraints.language?.values || ['zh', 'en', 'auto'],
)
const voices = computed(() => capability.value?.constraints.voice?.values || [])
function limit(key: string, edge: string, fallback: number) {
return capability.value?.constraints[key]?.[edge] ?? fallback
}
function renderValue(value: unknown) {
return typeof value === 'string' ? value : JSON.stringify(value)
}
async function submit() {
if (busy.value) return
if (!capability.value?.available) {
ElMessage.warning('此能力尚未配置,请先使用已就绪的功能')
return
}
if (['math.solve', 'audio.speech'].includes(taskType.value) && !draft.value.prompt.trim()) {
ElMessage.warning('请输入需要处理的文字')
return
}
if (['audio.transcribe', 'media.structure'].includes(taskType.value) && !reference.value) {
ElMessage.warning('请先选择或上传素材')
return
}
if (taskType.value === 'audio.speech' && !draft.value.parameters.voice?.trim()) {
ElMessage.warning('请填写真实服务支持的音色名称')
return
}
busy.value = true
try {
const created = await jobs.submit({
...buildToolRequest(
taskType.value,
draft.value.prompt,
draft.value.parameters,
reference.value,
),
folder_id: outputFolder.value,
output_folder_id: outputFolder.value,
})
selectedId.value = created[0]?.id || null
void taskHistory.load()
ElMessage.success('任务已提交,结果将在此同步')
} catch (error) {
ElMessage.error(errorMessage(error))
} finally {
busy.value = false
}
}
async function copy() {
if (!textResult.value) return
try {
await copyText(textResult.value)
ElMessage.success('结果已复制')
} catch {
ElMessage.warning('请手动选择文本复制')
}
}
async function importAsset() {
if (typeof route.query.asset !== 'string') return
try {
const asset = await assets.get(route.query.asset)
if (asset) reference.value = asset
} catch (error) {
ElMessage.error(errorMessage(error))
}
}
watch(
() => kind.value,
() => {
selectedId.value = null
if (kind.value !== 'audio') audioMode.value = 'transcribe'
void importAsset()
},
)
watch(
() => audioMode.value,
() => {
selectedId.value = null
},
)
watch(() => route.query.asset, importAsset)
watch(
() => draft.value.imageAssetId,
(id) => {
if (id) void assets.get(id).catch(() => undefined)
},
{ immediate: true },
)
onMounted(() => {
void jobs.refresh().catch(() => undefined)
void importAsset()
})
</script>
<template>
<div class="tool-page">
<div class="folder-destination">
<FolderSelect
v-model="outputFolder"
label="成果保存到"
/><FolderManager v-model:folder-id="outputFolder" />
</div>
<header class="page-heading">
<span class="eyebrow">{{
kind === 'math'
? 'REASONING SPACE'
: kind === 'analyze'
? 'UNDERSTAND YOUR MEDIA'
: 'AUDIO WORKSPACE'
}}</span>
<h1>{{ title }}</h1>
<p>{{ subtitle }}</p>
</header>
<div
v-if="kind === 'audio'"
class="mode-switch audio-tabs"
>
<button
:class="{ active: audioMode === 'transcribe' }"
@click="audioMode = 'transcribe'"
>
语音转写</button
><button
:class="{ active: audioMode === 'speech' }"
@click="audioMode = 'speech'"
>
配音生成 <small v-if="!caps.forTask('audio.speech')?.available">待配置</small>
</button>
</div>
<div class="tool-columns">
<section class="tool-input-panel surface">
<div class="panel-heading">
<h2>
{{
kind === 'math'
? '写下你的问题'
: kind === 'analyze'
? '添加待解析素材'
: audioMode === 'speech'
? '写下配音文本'
: '添加声音素材'
}}
</h2>
<span class="tiny-model">{{ capability?.model || '本地服务' }}</span>
</div>
<textarea
v-if="kind === 'math' || (kind === 'audio' && audioMode === 'speech')"
v-model="draft.prompt"
class="tool-textarea ui-field--full"
:placeholder="
kind === 'math'
? '例如:一个圆的半径增加20%,面积增加多少?请说明解题步骤。'
: '输入希望转为声音的文字…'
"
:maxlength="taskType === 'audio.speech' ? limit('text', 'max', 2000) : 8000"
aria-label="任务输入文本"
@keydown.ctrl.enter.prevent="submit"
/>
<AssetInput
v-else
v-model="reference"
:kinds="kind === 'analyze' ? ['image', 'video'] : ['audio', 'video']"
:label="kind === 'analyze' ? '上传图片或视频' : '上传音频或视频'"
:hint="kind === 'analyze' ? '识别主体、场景和画面文字' : '支持从视频中提取音轨后转写'"
/>
<audio
v-if="reference && kind === 'audio'"
class="source-audio"
:src="reference.preview_url"
controls
/>
<div
v-if="kind === 'math'"
class="prompt-suggestions"
>
<button
@click="draft.prompt = '一个圆的半径增加20%,面积增加多少?请给出清晰的解题过程。'"
>
比例与面积</button
><button @click="draft.prompt = '解方程 x² − 5x + 6 = 0,并验证两个解。'">
方程求解
</button>
</div>
<div class="tool-parameters parameter-form ui-form-grid">
<template v-if="kind === 'math'"
><label
>最大输出长度<el-input-number
v-model="draft.parameters.max_tokens"
:min="limit('max_tokens', 'min', 128)"
:max="limit('max_tokens', 'max', 8192)"
:step="128" /></label
><small class="ui-field--full"
>返回可阅读的解题内容;专业题目请按实际业务需要复核。</small
></template
><template v-else-if="kind === 'analyze' && reference?.kind !== 'image'"
><label
>视频采样帧数<el-input-number
v-model="draft.parameters.frame_count"
:min="limit('frame_count', 'min', 1)"
:max="limit('frame_count', 'max', 12)" /></label
><small class="ui-field--full"
>时间点对应实际采样帧,不等同于完整镜头切分。</small
></template
><template v-else-if="kind === 'audio' && audioMode === 'transcribe'"
><label
>转写语言<el-select v-model="draft.parameters.language"
><el-option
v-for="language in languages"
:key="language"
:value="language"
:label="
({ zh: '中文', en: '英文', auto: '自动识别' } as Record<string, string>)[
language
] || language
" /></el-select></label
><label
>音频上限(秒)<el-input-number
v-model="draft.parameters.max_audio_seconds"
:min="1"
:max="1800"
:step="30" /></label
><small class="ui-field--full"
>每30秒分块转写。结果时间为分块边界,不是逐词对齐。</small
></template
><template v-else-if="kind === 'audio' && audioMode === 'speech'"
><label
>音色<el-select
v-if="voices.length"
v-model="draft.parameters.voice"
><el-option
v-for="voice in voices"
:key="voice"
:label="voice"
:value="voice" /></el-select
><el-input
v-else
v-model="draft.parameters.voice"
placeholder="服务端真实音色名称" /></label
><label
>语速<el-input-number
v-model="draft.parameters.speed"
:min="limit('speed', 'min', 0.25)"
:max="limit('speed', 'max', 4)"
:step="0.1" /></label
></template>
</div>
<div
v-if="!capability?.available"
class="notice warning"
>
{{
capability?.description ||
(audioMode === 'speech'
? '语音生成尚未接入。当前可以使用 Whisper 语音转写。'
: '正在确认服务能力,请稍后重试。')
}}<el-button
text
:icon="RefreshRight"
@click="caps.load()"
>刷新能力</el-button
>
</div>
<el-button
type="primary"
class="tool-submit"
:icon="MagicStick"
:loading="busy"
:disabled="!capability?.available"
@click="submit"
>{{
kind === 'math'
? '开始推演'
: kind === 'analyze'
? '解析素材'
: audioMode === 'speech'
? '生成配音'
: '开始转写'
}}<el-icon><ArrowRight /></el-icon
></el-button>
</section>
<section class="tool-result-panel surface">
<div class="panel-heading">
<h2>{{ kind === 'math' ? '推演结果' : kind === 'analyze' ? '素材理解' : '处理结果' }}</h2>
<el-button
v-if="textResult"
text
:icon="CopyDocument"
@click="copy"
>复制</el-button
><button
v-if="current"
class="text-link"
@click="detailId = current.id"
>
任务详情
</button>
</div>
<template v-if="current"
><div class="inline-job-state">
<span
class="status-pill"
:class="current.state"
>{{ stateLabel(current) }}</span
><span>{{ phaseLabel(current) }}</span>
</div>
<MathText
v-if="textResult"
:text="textResult"
/>
<div
v-else-if="current.state === 'succeeded' && kind === 'analyze'"
class="analysis-result"
>
<h3>画面主体</h3>
<div class="tag-cloud">
<span
v-for="(subject, index) in analysis.subjects || []"
:key="index"
>{{ renderValue(subject) }}</span
>
</div>
<h3>场景描述</h3>
<p>{{ renderValue(analysis.scene || '未返回场景描述') }}</p>
<h3>画面文字</h3>
<p
v-for="(line, index) in analysis.ocr || []"
:key="index"
>
{{ renderValue(line) }}
</p>
<small
v-if="!analysis.ocr?.length"
class="muted"
>未识别到文字</small
>
<details v-if="analysis.frames?.length">
<summary>查看逐帧结果({{ analysis.frames.length }} 帧)</summary>
<pre class="json-output">{{ JSON.stringify(analysis.frames, null, 2) }}</pre>
</details>
</div>
<div
v-else-if="!current.result_assets.length"
class="empty-state compact"
>
<div
v-if="!['failed', 'cancelled', 'timed_out'].includes(current.state)"
class="generation-orbit"
/>
<p>{{ current.error?.message || '结果会在任务完成后出现在这里' }}</p>
</div>
<div
v-if="current.result_assets.length"
class="tool-output-assets"
>
<div
v-for="asset in current.result_assets"
:key="asset.id"
>
<audio
v-if="asset.kind === 'audio'"
:src="asset.preview_url"
controls
/><button
v-else
@click="preview = asset"
>
{{ asset.name }} <el-icon><ArrowRight /></el-icon></button
><a
:href="asset.download_url"
:download="asset.name"
class="text-link"
>下载</a
>
</div>
</div>
<details
v-if="current.result?.segments?.length"
class="segments"
>
<summary>查看转写分段</summary>
<div
v-for="(segment, index) in current.result.segments"
:key="index"
>
<code>{{ segment.start.toFixed(1) }}–{{ segment.end.toFixed(1) }}s</code>
<p>{{ segment.text }}</p>
<small
v-if="segment.truncated"
class="warning-text"
>此段输出达到长度上限</small
>
</div>
</details></template
>
<div
v-else
class="empty-state tool-empty"
>
<el-icon :size="38"
><Document v-if="kind === 'math'" /><DataAnalysis
v-else-if="kind === 'analyze'" /><Headset v-else
/></el-icon>
<h3>给灵感留一个位置</h3>
<p>提交任务后,这里会同步展示真实处理结果。</p>
</div>
</section>
</div>
<section
v-if="history.length"
class="tool-history"
>
<div class="section-heading"><h2>最近记录</h2></div>
<button
v-for="job in history"
:key="job.id"
:class="{ selected: current?.id === job.id }"
@click="selectedId = job.id"
>
<span
class="status-dot"
:class="job.state"
/><strong>{{ job.prompt || (kind === 'analyze' ? '素材解析' : '语音任务') }}</strong
><span>{{ stateLabel(job) }}</span
><small>{{ formatDate(job.created_at) }}</small>
</button>
</section>
<p
v-if="taskHistory.error.value"
class="notice warning"
>
{{ taskHistory.error.value }}
</p>
<el-pagination
v-if="taskHistory.total.value > 20"
v-model:current-page="taskHistory.page.value"
:page-size="20"
:total="taskHistory.total.value"
layout="total,prev,pager,next"
/>
<JobDetail v-model:job-id="detailId" /><AssetPreview v-model:asset="preview" />
</div>
</template>