import React, { useState, useEffect, useRef } from 'react'; import { Row, Col, Card, Button, Tag, Typography, Space, Statistic, message, Divider, Input, Select, Switch, Upload, Progress, Tabs, Empty, InputNumber, Radio, Spin } from 'antd'; import { ReloadOutlined, InfoCircleOutlined, ThunderboltOutlined, AppstoreOutlined, CheckCircleOutlined, CloudOutlined, AimOutlined, FireOutlined, InboxOutlined, PlayCircleOutlined, FileTextOutlined, HistoryOutlined, SearchOutlined, SettingOutlined, FullscreenOutlined, UploadOutlined, LoadingOutlined, CheckOutlined, SyncOutlined, DatabaseOutlined } from '@ant-design/icons'; import { getDetectModels, submitDetectJob, getDetectJobStatus, getDetectJobResult, submitSegmentationAnalyze } from '../api/aiAnalysis'; import utils from '../lib/utils'; const { Title, Text } = Typography; const { Dragger } = Upload; const { Option } = Select; // 算法列表定义 const algorithmList = [ { id: 'detect', name: '目标检测', alias: 'waterway-trt', desc: '图片/视频检测,创建任务后轮询结果。', icon: , status: '运行中' }, { id: 'segmentation', name: '热成像分割', alias: 'v1.0.0', desc: '热成像热点、面板分区和温度统计。', icon: , status: '运行中' } ]; export default function Agri() { const [activeAlgo, setActiveAlgo] = useState('detect'); const [models, setModels] = useState([]); const [loadingModels, setLoadingModels] = useState(false); const [history, setHistory] = useState([]); // 检测任务状态 const [detectForm, setDetectForm] = useState({ modelAlias: '', inputType: 'image', conf: 0.25, iou: 0.45, imgsz: 1280, device: 'auto', maxDet: 300, vidStride: 1, half: false, speedPreset: 'speed' }); const [detectFiles, setDetectFiles] = useState([]); const [detectJobId, setDetectJobId] = useState(null); const [detectStatus, setDetectStatus] = useState(null); const [detectResult, setDetectResult] = useState(null); const [polling, setPolling] = useState(false); // 分割任务状态 const [segForm, setSegForm] = useState({ threshold_c: 48, min_area_px: 25, max_regions: 120, include_panel_segments: true }); const [thermalFile, setThermalFile] = useState(null); const [maskFile, setMaskFile] = useState(null); const [geojsonFile, setGeojsonFile] = useState(null); const [segResult, setSegResult] = useState(null); const [segLoading, setSegLoading] = useState(false); const pollTimer = useRef(null); // 初始化:加载模型列表 useEffect(() => { fetchModels(); }, []); const fetchModels = async () => { setLoadingModels(true); try { const res = await getDetectModels(); if (res && res.list) { setModels(res.list); const defaultModel = res.list.find(m => m.default) || res.list[0]; if (defaultModel) { setDetectForm(prev => ({ ...prev, modelAlias: defaultModel.alias })); } } } catch (err) { utils.message.error('获取模型列表失败'); } finally { setLoadingModels(false); } }; // --- 目标检测逻辑 --- const handleSubmitDetect = async () => { if (detectFiles.length === 0) { utils.message.warning('请先上传图片或视频'); return; } const formData = new FormData(); detectFiles.forEach(file => { formData.append('files', file.originFileObj); }); formData.append('inputType', detectForm.inputType); formData.append('modelAlias', detectForm.modelAlias); formData.append('conf', detectForm.conf.toString()); formData.append('iou', detectForm.iou.toString()); formData.append('imgsz', detectForm.imgsz.toString()); formData.append('device', detectForm.device); formData.append('maxDet', detectForm.maxDet.toString()); formData.append('vidStride', detectForm.vidStride.toString()); formData.append('half', detectForm.half.toString()); try { setDetectStatus('submitting'); const res = await submitDetectJob(formData); if (res && res.jobId) { setDetectJobId(res.jobId); setDetectStatus('queued'); setPolling(true); startPolling(res.jobId); // 添加到历史 addToHistory('detect', res.jobId); } } catch (err) { utils.message.error('提交任务失败'); setDetectStatus(null); } }; const startPolling = (jobId) => { if (pollTimer.current) clearInterval(pollTimer.current); pollTimer.current = setInterval(async () => { try { const statusRes = await getDetectJobStatus(jobId); setDetectStatus(statusRes.status); if (statusRes.status === 'succeeded') { clearInterval(pollTimer.current); setPolling(false); const resultRes = await getDetectJobResult(jobId); setDetectResult(resultRes); utils.message.success('任务执行成功'); } else if (['failed', 'cancelled'].includes(statusRes.status)) { clearInterval(pollTimer.current); setPolling(false); utils.message.error(`任务执行${statusRes.status === 'failed' ? '失败' : '被取消'}`); } } catch (err) { console.error('轮询失败', err); } }, 2000); }; // --- 热成像分割逻辑 --- const handleSubmitSeg = async () => { if (!thermalFile) { utils.message.warning('请先上传热成像文件'); return; } const formData = new FormData(); formData.append('thermal_file', thermalFile.originFileObj); if (maskFile) formData.append('array_mask_file', maskFile.originFileObj); if (geojsonFile) formData.append('panel_geojson_file', geojsonFile.originFileObj); formData.append('threshold_c', segForm.threshold_c.toString()); formData.append('min_area_px', segForm.min_area_px.toString()); formData.append('max_regions', segForm.max_regions.toString()); formData.append('include_panel_segments', segForm.include_panel_segments.toString()); setSegLoading(true); try { const res = await submitSegmentationAnalyze(formData); setSegResult(res); utils.message.success('热成像分析完成'); addToHistory('segmentation', res.analysisId || 'seg-' + Date.now()); } catch (err) { utils.message.error('热成像分析失败'); } finally { setSegLoading(false); } }; const addToHistory = (type, id) => { const newItem = { id, type, time: new Date().toLocaleString(), name: type === 'detect' ? '目标检测任务' : '热成像分割分析' }; setHistory(prev => [newItem, ...prev]); }; // 替换成这个 renderStats const renderStats = () => ( {[ { title: '算法数量', value: '2', unit: '检测 + 分割', icon: , color: '#165DFF', bg: '#E8F3FF', }, { title: '在线服务', value: '2', unit: 'health 实时检查', icon: , color: '#00B42A', bg: '#E8FFEA', }, { title: '模型数量', value: models.length || 3, unit: '检测模型 registry', icon: , color: '#165DFF', bg: '#E8F3FF', }, { title: '历史记录', value: history.length, unit: '本页联调记录', icon: , color: '#722ED1', bg: '#F3E8FF', }, ].map((item, index) => (
{item.title}
{item.value} {item.unit && ( {item.unit} )}
{React.cloneElement(item.icon, { style: { fontSize: 22, color: item.color }, })}
))}
); // 渲染检测工作区 const renderDetectWorkspace = () => (
检测模型
输入类型 setDetectForm(prev => ({ ...prev, inputType: e.target.value }))} buttonStyle="solid" size="small" > 图片 视频 推理预设 setDetectForm(prev => ({ ...prev, speedPreset: e.target.value }))} size="small" > 质量 速度 conf setDetectForm(prev => ({ ...prev, conf: val }))} style={{ width: '100%' }} /> iou setDetectForm(prev => ({ ...prev, iou: val }))} style={{ width: '100%' }} /> imgsz setDetectForm(prev => ({ ...prev, imgsz: val }))} style={{ width: '100%' }} /> device max_det setDetectForm(prev => ({ ...prev, maxDet: val }))} style={{ width: '100%' }} /> vid_stride setDetectForm(prev => ({ ...prev, vidStride: val }))} style={{ width: '100%' }} /> half setDetectForm(prev => ({ ...prev, half: val }))} />
setDetectFiles(info.fileList)} beforeUpload={() => false} style={{ background: '#fafafa', borderRadius: 8 }} >

拖拽文件到此处,或点击选择

支持 jpg/png/webp/mp4 等格式

); // 渲染分割工作区 const renderSegWorkspace = () => (
threshold_c setSegForm(prev => ({ ...prev, threshold_c: val }))} style={{ width: '100%' }} /> min_area_px setSegForm(prev => ({ ...prev, min_area_px: val }))} style={{ width: '100%' }} /> max_regions setSegForm(prev => ({ ...prev, max_regions: val }))} style={{ width: '100%' }} /> include_panel_segments setSegForm(prev => ({ ...prev, include_panel_segments: val }))} />
热成像文件 thermal_file setThermalFile(info.fileList[0])} beforeUpload={() => false} maxCount={1} style={{ background: '#fafafa', borderRadius: 8, height: 120 }} >

上传 TIFF / PNG / JPG 热成像文件

setMaskFile(info.fileList[0])} beforeUpload={() => false} maxCount={1} > setGeojsonFile(info.fileList[0])} beforeUpload={() => false} maxCount={1} >
); // 渲染结果展示 const renderResults = () => { const result = activeAlgo === 'detect' ? detectResult : segResult; const inputFiles = activeAlgo === 'detect' ? detectFiles : (thermalFile ? [thermalFile] : []); return ( 结果展示} bordered={false} style={{ marginTop: 12, borderRadius: 8 }} bodyStyle={{ padding: '12px' }} > 原始预览、结果图与完整 JSON 同屏查看 {activeAlgo === 'segmentation' && segResult && (
)}
{result ? ( activeAlgo === 'detect' ? ( detectForm.inputType === 'image' ? ( result ) : (
分析结果视图
点位详情 {activeAlgo === 'segmentation' && segResult ? (
热点 GPS 样例
{segResult.hotspots?.[0]?.gps?.text || '暂无 GPS 信息'}
热点/面板列表
{segResult.panel_overview?.slice(0, 10).map((p, i) => (
面板 #{i + 1}: {p.gps_text}
))}
) : ( )}
结果 JSON {result ? (
{JSON.stringify(result, null, 2)}
) : }
详细数据
); }; return (
算法分析中心
{renderStats()} {/* 左侧:算法列表 */} 算法列表} bordered={false} bodyStyle={{ padding: '8px' }} style={{ borderRadius: 8, height: '100%' }} extra={已接入 2 套} > {algorithmList.map(algo => (
setActiveAlgo(algo.id)} style={{ padding: '12px', borderRadius: 8, cursor: 'pointer', marginBottom: 8, border: `1px solid ${activeAlgo === algo.id ? '#1677ff' : '#f0f0f0'}`, background: activeAlgo === algo.id ? '#e6f4ff' : '#fff', transition: 'all 0.3s' }} >
{algo.icon} {algo.name} {algo.status}
{algo.alias}
{algo.desc}
))}
{/* 中间:工作区 */} {activeAlgo === 'detect' ? '检测任务工作区' : '热成像分割工作区'} {activeAlgo === 'detect' ? '异步任务' : '同步分析'} } bordered={false} bodyStyle={{ padding: '16px' }} style={{ borderRadius: 8 }} > {activeAlgo === 'detect' ? '提交图片或视频检测任务,轮询状态并查看检测结果图。' : '上传热成像图与可选 mask/geojson,同步返回叠加图和热点 JSON。'} {activeAlgo === 'detect' ? renderDetectWorkspace() : renderSegWorkspace()} {renderResults()} {/* 右侧:历史记录 */} 历史分析记录} bordered={false} bodyStyle={{ padding: '8px' }} style={{ borderRadius: 8, height: '100%' }} extra={{history.length} 条} > {history.length === 0 ? ( ) : ( history.map(item => (
{item.name} {item.type === 'detect' ? '检测' : '分割'}
ID: {item.id.substring(0, 12)}...
{item.time}
)) )}
); }