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 [selectedHotspot, setSelectedHotspot] = useState(null); 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 => { console.log(file, "dsdsvc") 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.slice(-1)); }} beforeUpload={() => false} limit={1} 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} >
); // 1. 目标检测的结果布局(第一张图的样式:三列) const renderDetectResultLayout = () => { const inputFile = detectFiles[0]; const hasResult = !!detectResult; return ( 结果展示} bordered={false} style={{ marginTop: 12, borderRadius: 8 }} bodyStyle={{ padding: '12px' }} > 原始预览、结果图与完整 JSON 同屏查看 {/* 输入预览 */}
{inputFile && ( detectForm.inputType === 'image' ? ( input ) : (
{/* 结果图/视频 */}
{hasResult ? ( detectForm.inputType === 'image' ? ( result ) : (
{/* 结果JSON */}
{hasResult ? (
{JSON.stringify(detectResult, null, 2)}
) : ( 暂无结果 )}
); }; // 2. 热成像分割的结果布局(第二张图的样式:两列) // 2. 热成像分割的结果布局(第二张图的样式:两列 + 热点交互) const renderSegResultLayout = () => { const hasResult = !!segResult; const inputFile = thermalFile; const hotspots = segResult?.hotspots || []; const panels = segResult?.panel_overview || []; // 选中的点位详情 const selectedPoint = selectedHotspot ? hotspots.find(h => h.hotspot_id === selectedHotspot) : null; return ( 结果展示} bordered={false} style={{ marginTop: 12, borderRadius: 8 }} bodyStyle={{ padding: '12px' }} > 原始预览、结果图与完整 JSON 同屏查看 {/* 顶部统计卡片 */}
热成像交互分析视图 点击热点或面板查看温度、块号、GPS 与像素溯源信息
{/* 左侧:结果图 + 热点标记 */}
{/*{inputFile && ( thermal )}*/} {!inputFile && ( 请上传热成像文件} image={Empty.PRESENTED_IMAGE_SIMPLE} /> )} {/* 热点标记点 */} {hasResult && hotspots.map(hotspot => { // 计算图片缩放比例,把原始坐标转为百分比位置 const scaleX = 100 / (segResult.image?.source_width || 4000); const scaleY = 100 / (segResult.image?.source_height || 3000); const left = hotspot.peak_x * scaleX; const top = hotspot.peak_y * scaleY; const isSelected = selectedHotspot === hotspot.hotspot_id; return (
setSelectedHotspot(hotspot.hotspot_id)} style={{ position: 'absolute', left: `${left}%`, top: `${top}%`, transform: 'translate(-50%, -50%)', width: isSelected ? 36 : 28, height: isSelected ? 36 : 28, borderRadius: '50%', background: isSelected ? '#ff4d4f' : '#fa8c16', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 'bold', cursor: 'pointer', boxShadow: isSelected ? '0 0 0 4px rgba(255,77,79,0.4)' : '0 2px 8px rgba(0,0,0,0.3)', border: '2px solid white', transition: 'all 0.2s' }} > {hotspot.hotspot_id}
); })}
{/* 右侧:点位详情 + 列表 */} 请选择热点或面板} style={{ height: 400 }} bodyStyle={{ height: 350 }} > {/* 总容器:垂直布局,占满卡片内容区 */}
{/* --------------- 上半部分:点位详情 50% --------------- */}
{selectedPoint ? (
热点 {selectedPoint.hotspot_id} 热点
{[ { label: '温度', value: `${selectedPoint.peak_temp_c}℃` }, { label: '块号', value: selectedPoint.panel_id || '-' }, { label: 'GPS', value: selectedPoint.gps?.text || '-' }, { label: '原图像素', value: `${selectedPoint.peak_x}, ${selectedPoint.peak_y}` }, { label: '叠加图像素', value: `${selectedPoint.peak_x}, ${selectedPoint.peak_y}` }, { label: '面积', value: `${selectedPoint.area_px} px` } ].map((item, i) => (
{item.label} {item.value}
))}
) : ( 等待分割结果,完成后可点击热点/面板查看详情 )}
{/* 分割线 */}
{/* --------------- 下半部分:热点/面板列表 50% --------------- */}
热点/面板列表 {panels.map((p, i) => (
{ const matchHotspot = hotspots.find(h => h.hotspot_id === i + 1); if (matchHotspot) setSelectedHotspot(matchHotspot.hotspot_id); }} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 12px', borderRadius: 4, marginBottom: 4, background: selectedHotspot === i + 1 ? '#e6f4ff' : '#fafafa', cursor: 'pointer', fontSize: 12 }} > {p.label || `面板 #${i + 1}`} {p.peak_temp_c}℃
))}
); }; // 主渲染结果方法:根据算法选择不同布局 const renderResults = () => { if (activeAlgo === 'detect') { return renderDetectResultLayout(); } else { return renderSegResultLayout(); } }; 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}
)) )}
); }