feat: веб-клиент (React+Vite) — чат с базой + просмотр видео/документов
SPA: режимы Вопрос/Проверка схемы, выбор LLM (zai/claude), ответ с кликабельными [n]-цитатами; клик по видео-цитате → плеер на таймкоде, по док-цитате → PDF на нужной странице (нативный просмотрщик через iframe #page, без бандла pdf.js). MediaModal, Sources, api-клиент. Собирается vite (148 КБ), FastAPI отдаёт dist, API в приоритете над SPA-монтированием. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
dist/
|
||||
*.local
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>ИИ-инженер БТГ Романова</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+1680
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "romanov-btg-web",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-react": "^4.3.1",
|
||||
"vite": "^5.4.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import React, { useState } from 'react'
|
||||
import { ask, review } from './api.js'
|
||||
import { AnswerText, SourceList } from './Sources.jsx'
|
||||
import MediaModal from './MediaModal.jsx'
|
||||
|
||||
export default function App() {
|
||||
const [mode, setMode] = useState('ask') // 'ask' | 'review'
|
||||
const [backend, setBackend] = useState('zai') // 'zai' | 'claude'
|
||||
const [input, setInput] = useState('')
|
||||
const [items, setItems] = useState([]) // история {q, kind, ...result}
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [media, setMedia] = useState(null) // открытый медиа в модалке
|
||||
|
||||
async function submit(e) {
|
||||
e?.preventDefault()
|
||||
const text = input.trim()
|
||||
if (!text || busy) return
|
||||
setBusy(true)
|
||||
setInput('')
|
||||
try {
|
||||
if (mode === 'ask') {
|
||||
const r = await ask(text, { backend })
|
||||
setItems((p) => [...p, { kind: 'ask', q: text, ...r }])
|
||||
} else {
|
||||
const r = await review(text, { backend })
|
||||
setItems((p) => [...p, { kind: 'review', q: text, ...r }])
|
||||
}
|
||||
} catch (err) {
|
||||
setItems((p) => [...p, { kind: 'error', q: text, error: String(err) }])
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<header className="topbar">
|
||||
<h1>ИИ-инженер БТГ Романова</h1>
|
||||
<div className="controls">
|
||||
<div className="seg">
|
||||
<button className={mode === 'ask' ? 'on' : ''} onClick={() => setMode('ask')}>Вопрос</button>
|
||||
<button className={mode === 'review' ? 'on' : ''} onClick={() => setMode('review')}>Проверка схемы</button>
|
||||
</div>
|
||||
<label className="backend">
|
||||
LLM:
|
||||
<select value={backend} onChange={(e) => setBackend(e.target.value)}>
|
||||
<option value="zai">Z.AI (быстро)</option>
|
||||
<option value="claude">Claude (точнее)</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="feed">
|
||||
{items.length === 0 && (
|
||||
<div className="hint">
|
||||
{mode === 'ask'
|
||||
? 'Спроси по материалам Романова — ответ придёт со ссылками на видео (по таймкоду) и документы (по странице).'
|
||||
: 'Опиши предложение конструктора — проверю по инвариантам Романова и предупрежу о ВВ-опасности.'}
|
||||
</div>
|
||||
)}
|
||||
{items.map((it, i) => (
|
||||
<div key={i} className="turn">
|
||||
<div className="q">{it.q}</div>
|
||||
{it.kind === 'ask' && (
|
||||
<div className="a">
|
||||
<AnswerText text={it.answer} sources={it.sources} onOpen={setMedia} />
|
||||
<SourceList sources={it.sources} onOpen={setMedia} />
|
||||
</div>
|
||||
)}
|
||||
{it.kind === 'review' && <ReviewResult it={it} onOpen={setMedia} />}
|
||||
{it.kind === 'error' && <div className="err">Ошибка: {it.error}</div>}
|
||||
</div>
|
||||
))}
|
||||
{busy && <div className="busy">…думаю</div>}
|
||||
</main>
|
||||
|
||||
<form className="composer" onSubmit={submit}>
|
||||
<textarea
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) submit(e) }}
|
||||
placeholder={mode === 'ask' ? 'Вопрос к базе… (Ctrl/⌘+Enter)' : 'Описание схемы для проверки…'}
|
||||
rows={2}
|
||||
/>
|
||||
<button type="submit" disabled={busy}>{mode === 'ask' ? 'Спросить' : 'Проверить'}</button>
|
||||
</form>
|
||||
|
||||
<MediaModal media={media} onClose={() => setMedia(null)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ReviewResult({ it, onOpen }) {
|
||||
if (!it.parsed) return <div className="a"><pre className="raw">{it.raw}</pre></div>
|
||||
return (
|
||||
<div className="a">
|
||||
<div className="sources-head">Нарушения инвариантов</div>
|
||||
{(!it.violations || it.violations.length === 0) && <div className="ok">Нарушений не найдено.</div>}
|
||||
{it.violations?.map((v, i) => (
|
||||
<div key={i} className={'viol ' + (v.severity === 'критично' ? 'crit' : 'warn')}>
|
||||
<b>{v.severity}</b> · {v.invariant}: {v.explanation} {v.citation && <span className="cit-ref">{v.citation}</span>}
|
||||
</div>
|
||||
))}
|
||||
{it.safety_warnings?.length > 0 && (
|
||||
<div className="safety">
|
||||
<div className="sources-head">⚠️ ВВ-безопасность</div>
|
||||
{it.safety_warnings.map((w, i) => <div key={i} className="warn-line">{w}</div>)}
|
||||
</div>
|
||||
)}
|
||||
<SourceList sources={it.sources} onOpen={onOpen} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import React, { useEffect, useRef } from 'react'
|
||||
import { mediaUrl } from './api.js'
|
||||
|
||||
// Модалка просмотра оригинала: видео — нативный <video>, перемотанный на таймкод;
|
||||
// документ — нативный просмотрщик браузера через <iframe ...#page=N>.
|
||||
export default function MediaModal({ media, onClose }) {
|
||||
const videoRef = useRef(null)
|
||||
|
||||
useEffect(() => {
|
||||
const onEsc = (e) => e.key === 'Escape' && onClose()
|
||||
window.addEventListener('keydown', onEsc)
|
||||
return () => window.removeEventListener('keydown', onEsc)
|
||||
}, [onClose])
|
||||
|
||||
// подстрахуем перемотку программно (не все браузеры чтут #t= на src)
|
||||
useEffect(() => {
|
||||
if (media?.kind === 'video' && videoRef.current && media.seconds != null) {
|
||||
const el = videoRef.current
|
||||
const seek = () => { try { el.currentTime = media.seconds } catch {} }
|
||||
el.addEventListener('loadedmetadata', seek, { once: true })
|
||||
}
|
||||
}, [media])
|
||||
|
||||
if (!media) return null
|
||||
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose}>
|
||||
<div className="modal" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="modal-head">
|
||||
<span className="modal-title">{media.name}</span>
|
||||
<button className="modal-close" onClick={onClose}>✕</button>
|
||||
</div>
|
||||
{media.kind === 'video' ? (
|
||||
<video ref={videoRef} src={mediaUrl(media)} controls autoPlay
|
||||
style={{ width: '100%', maxHeight: '72vh', background: '#000' }} />
|
||||
) : (
|
||||
<iframe title={media.name} src={mediaUrl(media)}
|
||||
style={{ width: '100%', height: '78vh', border: 0, background: '#fff' }} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import React from 'react'
|
||||
|
||||
// Текст ответа с кликабельными ссылками [n] → открывают первый медиа-источник n.
|
||||
export function AnswerText({ text, sources, onOpen }) {
|
||||
const byN = Object.fromEntries(sources.map((s) => [s.n, s]))
|
||||
const parts = (text || '').split(/(\[\d+\])/g)
|
||||
return (
|
||||
<div className="answer">
|
||||
{parts.map((p, i) => {
|
||||
const m = p.match(/^\[(\d+)\]$/)
|
||||
if (m) {
|
||||
const s = byN[Number(m[1])]
|
||||
const media = s && s.media && s.media[0]
|
||||
return (
|
||||
<sup key={i}
|
||||
className={'cite' + (media ? ' cite-live' : '')}
|
||||
title={s ? s.citation : ''}
|
||||
onClick={() => media && onOpen(media)}>
|
||||
[{m[1]}]
|
||||
</sup>
|
||||
)
|
||||
}
|
||||
return <span key={i}>{p}</span>
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const layerLabel = { knowledge: 'видео', reference: 'документ', bench: 'стенд' }
|
||||
|
||||
// Список источников: цитата + кнопки открыть видео-момент / страницу документа.
|
||||
export function SourceList({ sources, onOpen }) {
|
||||
if (!sources || !sources.length) return null
|
||||
return (
|
||||
<div className="sources">
|
||||
<div className="sources-head">Источники</div>
|
||||
{sources.map((s) => (
|
||||
<div key={s.n} className="source">
|
||||
<span className="source-n">[{s.n}]</span>
|
||||
<div className="source-body">
|
||||
<div className="source-title">{s.title}</div>
|
||||
<div className="source-meta">
|
||||
<span className={'badge badge-' + s.layer}>{layerLabel[s.layer] || s.layer}</span>
|
||||
<span className="source-cit">{s.citation}</span>
|
||||
</div>
|
||||
{s.media && s.media.length > 0 && (
|
||||
<div className="media-btns">
|
||||
{s.media.map((m, i) => (
|
||||
<button key={i} className="media-btn" onClick={() => onOpen(m)}>
|
||||
{m.kind === 'video'
|
||||
? `▶ видео${m.seconds != null ? ' c ' + fmt(m.seconds) : ''}`
|
||||
: `📄 стр. ${m.page ?? '?'}`}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function fmt(sec) {
|
||||
const m = Math.floor(sec / 60), s = sec % 60
|
||||
return `${m}:${String(s).padStart(2, '0')}`
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Клиент API FastAPI-бэкенда (тот же origin; в dev — через vite-прокси).
|
||||
|
||||
async function post(path, body) {
|
||||
const r = await fetch(path, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
if (!r.ok) throw new Error(`${path}: HTTP ${r.status}`)
|
||||
return r.json()
|
||||
}
|
||||
|
||||
export const ask = (query, opts = {}) =>
|
||||
post('/api/ask', { query, k: opts.k ?? 8, layer: opts.layer ?? null, backend: opts.backend ?? null })
|
||||
|
||||
export const review = (design, opts = {}) =>
|
||||
post('/api/review', { design, backend: opts.backend ?? null })
|
||||
|
||||
export const mediaUrl = (m) =>
|
||||
m.kind === 'video'
|
||||
? `/api/media/video/${m.token}${m.seconds != null ? `#t=${m.seconds}` : ''}`
|
||||
: `/api/media/doc/${m.token}${m.page != null ? `#page=${m.page}` : ''}`
|
||||
@@ -0,0 +1,10 @@
|
||||
import React from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import App from './App.jsx'
|
||||
import './styles.css'
|
||||
|
||||
createRoot(document.getElementById('root')).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
)
|
||||
@@ -0,0 +1,68 @@
|
||||
:root {
|
||||
--bg: #0f1419; --panel: #1a2129; --panel2: #232c36; --fg: #e6edf3;
|
||||
--muted: #8b97a3; --accent: #4aa3ff; --crit: #ff5a5a; --warn: #ffb454;
|
||||
--ok: #4ec97a; --border: #2c3742;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body, html, #root { margin: 0; height: 100%; }
|
||||
body {
|
||||
background: var(--bg); color: var(--fg);
|
||||
font: 15px/1.5 -apple-system, Segoe UI, Roboto, sans-serif;
|
||||
}
|
||||
.app { display: flex; flex-direction: column; height: 100vh; max-width: 920px; margin: 0 auto; }
|
||||
|
||||
.topbar { display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 12px 16px; border-bottom: 1px solid var(--border); gap: 12px; flex-wrap: wrap; }
|
||||
.topbar h1 { font-size: 17px; margin: 0; }
|
||||
.controls { display: flex; gap: 12px; align-items: center; }
|
||||
.seg { display: flex; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
|
||||
.seg button { background: var(--panel); color: var(--muted); border: 0; padding: 6px 12px; cursor: pointer; }
|
||||
.seg button.on { background: var(--accent); color: #fff; }
|
||||
.backend { color: var(--muted); font-size: 13px; display: flex; gap: 6px; align-items: center; }
|
||||
.backend select { background: var(--panel); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; padding: 4px; }
|
||||
|
||||
.feed { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 18px; }
|
||||
.hint { color: var(--muted); text-align: center; margin-top: 40px; }
|
||||
.turn { display: flex; flex-direction: column; gap: 8px; }
|
||||
.q { align-self: flex-end; background: var(--accent); color: #fff; padding: 8px 12px; border-radius: 12px 12px 2px 12px; max-width: 80%; white-space: pre-wrap; }
|
||||
.a { background: var(--panel); border: 1px solid var(--border); border-radius: 12px 12px 12px 2px; padding: 12px 14px; }
|
||||
.answer { white-space: pre-wrap; }
|
||||
.err, .raw { color: var(--crit); }
|
||||
.busy { color: var(--muted); font-style: italic; }
|
||||
|
||||
.cite { color: var(--muted); cursor: default; font-size: 12px; }
|
||||
.cite-live { color: var(--accent); cursor: pointer; }
|
||||
.cite-live:hover { text-decoration: underline; }
|
||||
|
||||
.sources { margin-top: 12px; border-top: 1px solid var(--border); padding-top: 8px; }
|
||||
.sources-head { font-size: 12px; text-transform: uppercase; color: var(--muted); margin-bottom: 6px; letter-spacing: .04em; }
|
||||
.source { display: flex; gap: 8px; padding: 6px 0; border-bottom: 1px solid var(--border); }
|
||||
.source-n { color: var(--muted); font-size: 13px; }
|
||||
.source-body { flex: 1; }
|
||||
.source-title { font-weight: 600; }
|
||||
.source-meta { display: flex; gap: 8px; align-items: center; font-size: 12px; color: var(--muted); margin-top: 2px; flex-wrap: wrap; }
|
||||
.source-cit { word-break: break-word; }
|
||||
.badge { padding: 1px 7px; border-radius: 10px; font-size: 11px; color: #fff; }
|
||||
.badge-knowledge { background: #2f6fb0; } .badge-reference { background: #6b4fb0; } .badge-bench { background: #3f8f5f; }
|
||||
.media-btns { margin-top: 6px; display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.media-btn { background: var(--panel2); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; padding: 4px 10px; cursor: pointer; font-size: 13px; }
|
||||
.media-btn:hover { border-color: var(--accent); }
|
||||
|
||||
.viol { padding: 6px 10px; border-radius: 8px; margin: 4px 0; background: var(--panel2); }
|
||||
.viol.crit { border-left: 3px solid var(--crit); }
|
||||
.viol.warn { border-left: 3px solid var(--warn); }
|
||||
.cit-ref { color: var(--accent); }
|
||||
.ok { color: var(--ok); }
|
||||
.safety { margin-top: 10px; }
|
||||
.warn-line { color: var(--warn); padding: 2px 0; }
|
||||
|
||||
.composer { display: flex; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--border); }
|
||||
.composer textarea { flex: 1; resize: none; background: var(--panel); color: var(--fg); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; font: inherit; }
|
||||
.composer button { background: var(--accent); color: #fff; border: 0; border-radius: 8px; padding: 0 18px; cursor: pointer; font-weight: 600; }
|
||||
.composer button:disabled { opacity: .5; }
|
||||
|
||||
.modal-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,.7); display: flex; align-items: center; justify-content: center; z-index: 100; }
|
||||
.modal { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; width: min(1000px, 94vw); padding: 10px; }
|
||||
.modal-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
|
||||
.modal-title { font-size: 13px; color: var(--muted); word-break: break-word; }
|
||||
.modal-close { background: transparent; color: var(--fg); border: 0; font-size: 18px; cursor: pointer; }
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// dev: проксируем /api на FastAPI (uvicorn web.main:app на :8000)
|
||||
// build: статика в dist/, которую раздаёт FastAPI в проде
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
proxy: { '/api': 'http://localhost:8000' },
|
||||
},
|
||||
build: { outDir: 'dist', emptyOutDir: true },
|
||||
})
|
||||
Reference in New Issue
Block a user