大更新,架构调整,数据分析能力提升,
This commit is contained in:
212
web/main.py
212
web/main.py
@@ -5,6 +5,7 @@ import threading
|
||||
import glob
|
||||
import uuid
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Optional, Dict, List
|
||||
from fastapi import FastAPI, UploadFile, File, BackgroundTasks, HTTPException, Query
|
||||
@@ -12,6 +13,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from pydantic import BaseModel
|
||||
import pandas as pd
|
||||
|
||||
# Add parent directory to path to import agent modules
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
@@ -48,6 +50,8 @@ class SessionData:
|
||||
self.generated_report: Optional[str] = None
|
||||
self.log_file: Optional[str] = None
|
||||
self.analysis_results: List[Dict] = [] # Store analysis results for gallery
|
||||
self.rounds: List[Dict] = [] # Structured Round_Data objects
|
||||
self.data_files: List[Dict] = [] # File metadata dicts
|
||||
self.agent: Optional[DataAnalysisAgent] = None # Store the agent instance for follow-up
|
||||
|
||||
# 新增:进度跟踪
|
||||
@@ -128,7 +132,15 @@ class SessionManager:
|
||||
if os.path.exists(results_json):
|
||||
try:
|
||||
with open(results_json, "r") as f:
|
||||
session.analysis_results = json.load(f)
|
||||
data = json.load(f)
|
||||
# Support both old format (plain list) and new format (dict with rounds/data_files)
|
||||
if isinstance(data, dict):
|
||||
session.analysis_results = data.get("analysis_results", [])
|
||||
session.rounds = data.get("rounds", [])
|
||||
session.data_files = data.get("data_files", [])
|
||||
else:
|
||||
# Legacy format: data is the analysis_results list directly
|
||||
session.analysis_results = data
|
||||
except:
|
||||
pass
|
||||
|
||||
@@ -190,7 +202,7 @@ app.mount("/outputs", StaticFiles(directory="outputs"), name="outputs")
|
||||
|
||||
# --- Helper Functions ---
|
||||
|
||||
def run_analysis_task(session_id: str, files: list, user_requirement: str, is_followup: bool = False):
|
||||
def run_analysis_task(session_id: str, files: list, user_requirement: str, is_followup: bool = False, template_name: str = None):
|
||||
"""在后台线程中运行分析任务"""
|
||||
session = session_manager.get_session(session_id)
|
||||
if not session:
|
||||
@@ -220,11 +232,22 @@ def run_analysis_task(session_id: str, files: list, user_requirement: str, is_fo
|
||||
agent = DataAnalysisAgent(llm_config, force_max_rounds=False, output_dir=base_output_dir)
|
||||
session.agent = agent
|
||||
|
||||
# Wire progress callback to update session progress fields
|
||||
def progress_cb(current, total, message):
|
||||
session.current_round = current
|
||||
session.max_rounds = total
|
||||
session.progress_percentage = round((current / total) * 100, 1) if total > 0 else 0
|
||||
session.status_message = message
|
||||
|
||||
agent.set_progress_callback(progress_cb)
|
||||
agent.set_session_ref(session)
|
||||
|
||||
result = agent.analyze(
|
||||
user_input=user_requirement,
|
||||
files=files,
|
||||
session_output_dir=session_output_dir,
|
||||
reset_session=True,
|
||||
template_name=template_name,
|
||||
)
|
||||
else:
|
||||
agent = session.agent
|
||||
@@ -232,6 +255,16 @@ def run_analysis_task(session_id: str, files: list, user_requirement: str, is_fo
|
||||
print("Error: Agent not initialized for follow-up.")
|
||||
return
|
||||
|
||||
# Wire progress callback for follow-up sessions
|
||||
def progress_cb_followup(current, total, message):
|
||||
session.current_round = current
|
||||
session.max_rounds = total
|
||||
session.progress_percentage = round((current / total) * 100, 1) if total > 0 else 0
|
||||
session.status_message = message
|
||||
|
||||
agent.set_progress_callback(progress_cb_followup)
|
||||
agent.set_session_ref(session)
|
||||
|
||||
result = agent.analyze(
|
||||
user_input=user_requirement,
|
||||
files=None,
|
||||
@@ -246,7 +279,11 @@ def run_analysis_task(session_id: str, files: list, user_requirement: str, is_fo
|
||||
|
||||
# 持久化结果
|
||||
with open(os.path.join(session_output_dir, "results.json"), "w") as f:
|
||||
json.dump(session.analysis_results, f, default=str)
|
||||
json.dump({
|
||||
"analysis_results": session.analysis_results,
|
||||
"rounds": session.rounds,
|
||||
"data_files": session.data_files,
|
||||
}, f, default=str)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error during analysis: {e}")
|
||||
@@ -260,6 +297,7 @@ def run_analysis_task(session_id: str, files: list, user_requirement: str, is_fo
|
||||
|
||||
class StartRequest(BaseModel):
|
||||
requirement: str
|
||||
template: Optional[str] = None
|
||||
|
||||
class ChatRequest(BaseModel):
|
||||
session_id: str
|
||||
@@ -294,7 +332,7 @@ async def start_analysis(request: StartRequest, background_tasks: BackgroundTask
|
||||
|
||||
files = [os.path.abspath(f) for f in files] # Only use absolute paths
|
||||
|
||||
background_tasks.add_task(run_analysis_task, session_id, files, request.requirement, is_followup=False)
|
||||
background_tasks.add_task(run_analysis_task, session_id, files, request.requirement, is_followup=False, template_name=request.template)
|
||||
return {"status": "started", "session_id": session_id}
|
||||
|
||||
@app.post("/api/chat")
|
||||
@@ -309,6 +347,19 @@ async def chat_analysis(request: ChatRequest, background_tasks: BackgroundTasks)
|
||||
background_tasks.add_task(run_analysis_task, request.session_id, [], request.message, is_followup=True)
|
||||
return {"status": "started"}
|
||||
|
||||
import math as _math
|
||||
|
||||
def _sanitize_value(v):
|
||||
"""Replace NaN/inf with None for JSON safety."""
|
||||
if isinstance(v, float) and (_math.isnan(v) or _math.isinf(v)):
|
||||
return None
|
||||
if isinstance(v, dict):
|
||||
return {k: _sanitize_value(val) for k, val in v.items()}
|
||||
if isinstance(v, list):
|
||||
return [_sanitize_value(item) for item in v]
|
||||
return v
|
||||
|
||||
|
||||
@app.get("/api/status")
|
||||
async def get_status(session_id: str = Query(..., description="Session ID")):
|
||||
session = session_manager.get_session(session_id)
|
||||
@@ -320,13 +371,19 @@ async def get_status(session_id: str = Query(..., description="Session ID")):
|
||||
with open(session.log_file, "r", encoding="utf-8") as f:
|
||||
log_content = f.read()
|
||||
|
||||
return {
|
||||
response_data = {
|
||||
"is_running": session.is_running,
|
||||
"log": log_content,
|
||||
"has_report": session.generated_report is not None,
|
||||
"report_path": session.generated_report,
|
||||
"script_path": session.reusable_script # 新增:返回脚本路径
|
||||
"script_path": session.reusable_script,
|
||||
"current_round": session.current_round,
|
||||
"max_rounds": session.max_rounds,
|
||||
"progress_percentage": session.progress_percentage,
|
||||
"status_message": session.status_message,
|
||||
"rounds": _sanitize_value(session.rounds),
|
||||
}
|
||||
return JSONResponse(content=response_data)
|
||||
|
||||
@app.get("/api/export")
|
||||
async def export_session(session_id: str = Query(..., description="Session ID")):
|
||||
@@ -394,8 +451,11 @@ async def get_report(session_id: str = Query(..., description="Session ID")):
|
||||
|
||||
# 将报告按段落拆分,为前端润色功能提供结构化数据
|
||||
paragraphs = _split_report_to_paragraphs(content)
|
||||
|
||||
# Extract evidence annotations and build supporting_data mapping
|
||||
supporting_data = _extract_evidence_annotations(paragraphs, session)
|
||||
|
||||
return {"content": content, "base_path": web_base_path, "paragraphs": paragraphs}
|
||||
return {"content": content, "base_path": web_base_path, "paragraphs": paragraphs, "supporting_data": supporting_data}
|
||||
|
||||
@app.get("/api/figures")
|
||||
async def get_figures(session_id: str = Query(..., description="Session ID")):
|
||||
@@ -467,6 +527,120 @@ async def download_script(session_id: str = Query(..., description="Session ID")
|
||||
|
||||
# --- Tools API ---
|
||||
|
||||
@app.get("/api/templates")
|
||||
async def list_available_templates():
|
||||
from utils.analysis_templates import list_templates
|
||||
return {"templates": list_templates()}
|
||||
|
||||
|
||||
# --- Data Files API ---
|
||||
|
||||
@app.get("/api/data-files")
|
||||
async def list_data_files(session_id: str = Query(..., description="Session ID")):
|
||||
"""Return session.data_files merged with fallback directory scan for CSV/XLSX files."""
|
||||
session = session_manager.get_session(session_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Session not found")
|
||||
|
||||
# Start with known data_files from session
|
||||
known_files = {f["filename"]: f for f in session.data_files}
|
||||
|
||||
# Fallback directory scan for CSV/XLSX in output_dir
|
||||
if session.output_dir and os.path.exists(session.output_dir):
|
||||
# Collect original uploaded file basenames to exclude them
|
||||
uploaded_basenames = set()
|
||||
if hasattr(session, "file_list"):
|
||||
for fp in session.file_list:
|
||||
uploaded_basenames.add(os.path.basename(fp))
|
||||
|
||||
for pattern in ("*.csv", "*.xlsx"):
|
||||
for fpath in glob.glob(os.path.join(session.output_dir, pattern)):
|
||||
fname = os.path.basename(fpath)
|
||||
if fname in uploaded_basenames:
|
||||
continue
|
||||
if fname not in known_files:
|
||||
try:
|
||||
size_bytes = os.path.getsize(fpath)
|
||||
except OSError:
|
||||
size_bytes = 0
|
||||
known_files[fname] = {
|
||||
"filename": fname,
|
||||
"description": "",
|
||||
"rows": 0,
|
||||
"cols": 0,
|
||||
"size_bytes": size_bytes,
|
||||
}
|
||||
|
||||
return {"files": list(known_files.values())}
|
||||
|
||||
|
||||
@app.get("/api/data-files/preview")
|
||||
async def preview_data_file(
|
||||
session_id: str = Query(..., description="Session ID"),
|
||||
filename: str = Query(..., description="File name"),
|
||||
):
|
||||
"""Read CSV/XLSX via pandas, return {columns, rows (first 5)}."""
|
||||
session = session_manager.get_session(session_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Session not found")
|
||||
|
||||
if not session.output_dir:
|
||||
raise HTTPException(status_code=404, detail=f"File not found: {filename}")
|
||||
|
||||
file_path = os.path.join(session.output_dir, filename)
|
||||
if not os.path.exists(file_path):
|
||||
raise HTTPException(status_code=404, detail=f"File not found: {filename}")
|
||||
|
||||
try:
|
||||
if filename.lower().endswith(".xlsx"):
|
||||
df = pd.read_excel(file_path, nrows=5)
|
||||
else:
|
||||
# Try utf-8-sig first (common for Chinese CSV exports), fall back to utf-8
|
||||
try:
|
||||
df = pd.read_csv(file_path, nrows=5, encoding="utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
try:
|
||||
df = pd.read_csv(file_path, nrows=5, encoding="utf-8")
|
||||
except UnicodeDecodeError:
|
||||
df = pd.read_csv(file_path, nrows=5, encoding="gbk")
|
||||
|
||||
columns = list(df.columns)
|
||||
rows = df.head(5).to_dict(orient="records")
|
||||
# Sanitize NaN/inf for JSON serialization
|
||||
rows = [
|
||||
{k: (None if isinstance(v, float) and (_math.isnan(v) or _math.isinf(v)) else v)
|
||||
for k, v in row.items()}
|
||||
for row in rows
|
||||
]
|
||||
return {"columns": columns, "rows": rows}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Failed to read file: {str(e)}")
|
||||
|
||||
|
||||
@app.get("/api/data-files/download")
|
||||
async def download_data_file(
|
||||
session_id: str = Query(..., description="Session ID"),
|
||||
filename: str = Query(..., description="File name"),
|
||||
):
|
||||
"""Return FileResponse with correct MIME type."""
|
||||
session = session_manager.get_session(session_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Session not found")
|
||||
|
||||
if not session.output_dir:
|
||||
raise HTTPException(status_code=404, detail=f"File not found: {filename}")
|
||||
|
||||
file_path = os.path.join(session.output_dir, filename)
|
||||
if not os.path.exists(file_path):
|
||||
raise HTTPException(status_code=404, detail=f"File not found: {filename}")
|
||||
|
||||
if filename.lower().endswith(".xlsx"):
|
||||
media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
else:
|
||||
media_type = "text/csv"
|
||||
|
||||
return FileResponse(path=file_path, filename=filename, media_type=media_type)
|
||||
|
||||
|
||||
|
||||
# --- 新增API端点 ---
|
||||
@@ -597,6 +771,30 @@ def _split_report_to_paragraphs(markdown_content: str) -> list:
|
||||
return paragraphs
|
||||
|
||||
|
||||
def _extract_evidence_annotations(paragraphs: list, session) -> dict:
|
||||
"""Parse <!-- evidence:round_N --> annotations from paragraph content.
|
||||
|
||||
For each paragraph containing an evidence annotation, look up
|
||||
session.rounds[N-1].evidence_rows and build a supporting_data mapping
|
||||
keyed by paragraph ID.
|
||||
"""
|
||||
supporting_data = {}
|
||||
evidence_pattern = re.compile(r"<!--\s*evidence:round_(\d+)\s*-->")
|
||||
|
||||
for para in paragraphs:
|
||||
content = para.get("content", "")
|
||||
match = evidence_pattern.search(content)
|
||||
if match:
|
||||
round_num = int(match.group(1))
|
||||
# rounds are 1-indexed, list is 0-indexed
|
||||
idx = round_num - 1
|
||||
if 0 <= idx < len(session.rounds):
|
||||
evidence_rows = session.rounds[idx].get("evidence_rows", [])
|
||||
if evidence_rows:
|
||||
supporting_data[para["id"]] = evidence_rows
|
||||
return supporting_data
|
||||
|
||||
|
||||
class PolishRequest(BaseModel):
|
||||
session_id: str
|
||||
paragraph_id: str
|
||||
|
||||
@@ -322,6 +322,51 @@ body {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
/* Template Cards */
|
||||
.template-cards {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.template-card {
|
||||
flex: 1 1 calc(50% - 0.35rem);
|
||||
min-width: 100px;
|
||||
padding: 0.35rem 0.5rem;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 0.25rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s;
|
||||
background: #FFFFFF;
|
||||
}
|
||||
|
||||
.template-card:hover {
|
||||
border-color: var(--primary-color);
|
||||
background: #F0F7FF;
|
||||
}
|
||||
|
||||
.template-card.selected {
|
||||
border-color: var(--primary-color);
|
||||
background: #EFF6FF;
|
||||
box-shadow: 0 0 0 1px rgba(37, 99, 235, 0.15);
|
||||
}
|
||||
|
||||
.template-card-title {
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.template-card-desc {
|
||||
font-size: 0.68rem;
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.2;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Upload Area */
|
||||
.upload-area {
|
||||
border: 2px dashed var(--border-color);
|
||||
@@ -404,15 +449,14 @@ body {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
#logsTab {
|
||||
background-color: #1a1b26;
|
||||
color: #a9b1d6;
|
||||
font-family: 'JetBrains Mono', 'Menlo', 'Monaco', 'Courier New', monospace;
|
||||
padding: 1.5rem;
|
||||
/* Execution Tab */
|
||||
#executionTab {
|
||||
background-color: #F9FAFB;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.log-content {
|
||||
font-family: inherit;
|
||||
font-family: 'JetBrains Mono', 'Menlo', 'Monaco', 'Courier New', monospace;
|
||||
font-size: 0.85rem;
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.6;
|
||||
@@ -444,96 +488,340 @@ body {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Gallery Carousel */
|
||||
.carousel-container {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #F3F4F6;
|
||||
border-radius: 0.5rem;
|
||||
overflow: hidden;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
/* ===== Round Card Styles ===== */
|
||||
|
||||
.carousel-slide {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
.round-cards-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 2rem;
|
||||
gap: 0.75rem;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.carousel-slide img {
|
||||
max-width: 100%;
|
||||
max-height: 500px;
|
||||
object-fit: contain;
|
||||
border-radius: 0.25rem;
|
||||
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
|
||||
transition: transform 0.2s;
|
||||
background: white;
|
||||
}
|
||||
|
||||
.carousel-btn {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
.round-card {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 50%;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 0.5rem;
|
||||
background: #FFFFFF;
|
||||
overflow: hidden;
|
||||
transition: box-shadow 0.2s;
|
||||
}
|
||||
|
||||
.round-card:hover {
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.round-card.expanded {
|
||||
border-color: var(--primary-color);
|
||||
box-shadow: 0 2px 12px rgba(37, 99, 235, 0.1);
|
||||
}
|
||||
|
||||
.round-card-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.75rem 1rem;
|
||||
cursor: pointer;
|
||||
z-index: 10;
|
||||
color: var(--text-primary);
|
||||
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
|
||||
transition: all 0.2s;
|
||||
background: #F9FAFB;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.carousel-btn:hover {
|
||||
background: var(--primary-color);
|
||||
color: white;
|
||||
border-color: var(--primary-color);
|
||||
transform: translateY(-50%) scale(1.1);
|
||||
.round-card-header:hover {
|
||||
background: #F0F7FF;
|
||||
}
|
||||
|
||||
.carousel-btn.prev {
|
||||
left: 1rem;
|
||||
}
|
||||
|
||||
.carousel-btn.next {
|
||||
right: 1rem;
|
||||
}
|
||||
|
||||
.image-info {
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
color: var(--text-primary);
|
||||
background: white;
|
||||
padding: 1rem;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.image-title {
|
||||
.round-number {
|
||||
font-weight: 600;
|
||||
font-size: 1.1rem;
|
||||
margin-bottom: 0.5rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--primary-color);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.round-summary {
|
||||
flex: 1;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-secondary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.round-toggle-icon {
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.75rem;
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
|
||||
.round-card-body {
|
||||
padding: 1rem;
|
||||
border-top: 1px solid var(--border-color);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.round-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.round-section-title {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
|
||||
.round-reasoning {
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-primary);
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.round-result {
|
||||
font-size: 0.9rem;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.round-details {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 0.375rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.round-details summary {
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
background: #F9FAFB;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.round-details summary:hover {
|
||||
background: #F0F7FF;
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.image-desc {
|
||||
font-size: 0.9rem;
|
||||
.round-code,
|
||||
.round-raw-log {
|
||||
margin: 0;
|
||||
padding: 0.75rem;
|
||||
font-family: 'JetBrains Mono', 'Menlo', 'Monaco', 'Courier New', monospace;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.5;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
background: #1a1b26;
|
||||
color: #a9b1d6;
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.evidence-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.8rem;
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
|
||||
.evidence-table th,
|
||||
.evidence-table td {
|
||||
border: 1px solid var(--border-color);
|
||||
padding: 0.35rem 0.5rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.evidence-table th {
|
||||
background: #F3F4F6;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.evidence-table td {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
/* ===== Data File Card Styles ===== */
|
||||
|
||||
.file-cards-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
gap: 0.75rem;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.data-file-card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.75rem 1rem;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 0.5rem;
|
||||
background: #FFFFFF;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.data-file-card:hover {
|
||||
border-color: var(--primary-color);
|
||||
background: #F0F7FF;
|
||||
box-shadow: 0 2px 8px rgba(37, 99, 235, 0.08);
|
||||
}
|
||||
|
||||
.data-file-icon {
|
||||
font-size: 1.5rem;
|
||||
color: var(--primary-color);
|
||||
width: 2rem;
|
||||
text-align: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.data-file-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.data-file-name {
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.data-file-desc {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-secondary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.data-preview-panel {
|
||||
margin: 0.75rem 0.5rem;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 0.5rem;
|
||||
background: #FFFFFF;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.data-preview-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: #F9FAFB;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.data-preview-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.data-preview-table th,
|
||||
.data-preview-table td {
|
||||
border: 1px solid var(--border-color);
|
||||
padding: 0.4rem 0.6rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.data-preview-table th {
|
||||
background: #F3F4F6;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ===== Supporting Data Styles ===== */
|
||||
|
||||
.supporting-data-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0.25rem 0.6rem;
|
||||
font-size: 0.78rem;
|
||||
border: 1px solid #BFDBFE;
|
||||
border-radius: 1rem;
|
||||
background: #EFF6FF;
|
||||
color: var(--primary-color);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
margin-top: 0.35rem;
|
||||
}
|
||||
|
||||
.supporting-data-btn:hover {
|
||||
background: var(--primary-color);
|
||||
color: white;
|
||||
border-color: var(--primary-color);
|
||||
}
|
||||
|
||||
.supporting-data-modal {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.supporting-data-content {
|
||||
background: #FFFFFF;
|
||||
border-radius: 0.5rem;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
|
||||
max-width: 700px;
|
||||
width: 90%;
|
||||
max-height: 80vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.supporting-data-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0.75rem 1rem;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
font-weight: 600;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.supporting-data-header button {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 1.25rem;
|
||||
cursor: pointer;
|
||||
color: var(--text-secondary);
|
||||
padding: 0.25rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.supporting-data-header button:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.supporting-data-body {
|
||||
padding: 1rem;
|
||||
overflow-y: auto;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.supporting-data-body .evidence-table {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
|
||||
/* ===== Report Paragraph Polishing ===== */
|
||||
|
||||
@@ -765,3 +1053,56 @@ body {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* ===== Progress Bar ===== */
|
||||
|
||||
.progress-bar-container {
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: #F9FAFB;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 0.375rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.progress-bar-info {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 0.35rem;
|
||||
}
|
||||
|
||||
.progress-label {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.progress-percent {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.progress-bar-track {
|
||||
width: 100%;
|
||||
height: 8px;
|
||||
background: #E5E7EB;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.progress-bar-fill {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, var(--primary-color), #60A5FA);
|
||||
border-radius: 4px;
|
||||
transition: width 0.5s ease;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.progress-message {
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-secondary);
|
||||
margin-top: 0.25rem;
|
||||
min-height: 1em;
|
||||
}
|
||||
|
||||
@@ -76,8 +76,19 @@
|
||||
<input type="file" id="fileInput" multiple accept=".csv,.xlsx,.xls" hidden>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="templateSelectorGroup">
|
||||
<label class="form-label">2. Analysis Template</label>
|
||||
<div id="templateSelector" class="template-cards">
|
||||
<div class="template-card selected" data-template="" onclick="selectTemplate(this, '')">
|
||||
<div class="template-card-title">No Template</div>
|
||||
<div class="template-card-desc">Free Analysis</div>
|
||||
</div>
|
||||
<!-- Dynamic template cards loaded via JS -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">2. Requirement</label>
|
||||
<label class="form-label">3. Requirement</label>
|
||||
<textarea id="requirementInput" class="form-textarea"
|
||||
placeholder="Describe what you want to analyze..."></textarea>
|
||||
</div>
|
||||
@@ -92,9 +103,9 @@
|
||||
<div class="panel-title" style="margin-bottom:0.5rem;">
|
||||
<span>Output</span>
|
||||
<div class="tabs">
|
||||
<div class="tab active" onclick="switchTab('logs')">Live Log</div>
|
||||
<div class="tab active" onclick="switchTab('execution')">执行过程</div>
|
||||
<div class="tab" onclick="switchTab('datafiles')">数据文件</div>
|
||||
<div class="tab" onclick="switchTab('report')">Report</div>
|
||||
<div class="tab" onclick="switchTab('gallery')">Gallery</div>
|
||||
</div>
|
||||
<button id="downloadScriptBtn" class="btn btn-sm btn-secondary hidden"
|
||||
onclick="downloadScript()" style="margin-left:auto;">
|
||||
@@ -102,10 +113,41 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Progress Bar -->
|
||||
<div id="progressBarContainer" class="progress-bar-container hidden">
|
||||
<div class="progress-bar-info">
|
||||
<span id="progressLabel" class="progress-label">Round 0/0</span>
|
||||
<span id="progressPercent" class="progress-percent">0%</span>
|
||||
</div>
|
||||
<div class="progress-bar-track">
|
||||
<div id="progressBarFill" class="progress-bar-fill" style="width: 0%"></div>
|
||||
</div>
|
||||
<div id="progressMessage" class="progress-message"></div>
|
||||
</div>
|
||||
|
||||
<div class="output-container" id="outputContainer">
|
||||
<!-- Logs Tab -->
|
||||
<div id="logsTab" class="tab-content active" style="height:100%; overflow-y:auto;">
|
||||
<pre id="logOutput" class="log-content">Waiting to start...</pre>
|
||||
<!-- Execution Process Tab -->
|
||||
<div id="executionTab" class="tab-content active" style="height:100%; overflow-y:auto;">
|
||||
<div id="roundCardsWrapper" class="round-cards-wrapper">
|
||||
<div class="empty-state" id="executionEmptyState">
|
||||
<p>Waiting to start...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Data Files Tab -->
|
||||
<div id="datafilesTab" class="tab-content hidden" style="height:100%; overflow-y:auto;">
|
||||
<div id="fileCardsGrid" class="file-cards-grid"></div>
|
||||
<div id="dataPreviewPanel" class="data-preview-panel hidden">
|
||||
<div class="data-preview-header">
|
||||
<span id="previewFileName"></span>
|
||||
<button class="btn btn-sm btn-secondary" onclick="closePreview()"><i class="fa-solid fa-xmark"></i></button>
|
||||
</div>
|
||||
<div id="previewTableContainer"></div>
|
||||
</div>
|
||||
<div class="empty-state" id="datafilesEmptyState">
|
||||
<p>No data files yet.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Report Tab -->
|
||||
@@ -135,21 +177,15 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Gallery Tab -->
|
||||
<div id="galleryTab" class="tab-content hidden"
|
||||
style="height:100%; display:flex; flex-direction:column; align-items:center; justify-content:center;">
|
||||
<div class="carousel-container">
|
||||
<button class="carousel-btn prev" onclick="prevImage()"><i
|
||||
class="fa-solid fa-chevron-left"></i></button>
|
||||
<div class="carousel-slide" id="carouselSlide">
|
||||
<p class="placeholder-text" style="color:var(--text-secondary);">No images
|
||||
generated.</p>
|
||||
<!-- Supporting Data Modal -->
|
||||
<div class="supporting-data-modal hidden" id="supportingDataModal">
|
||||
<div class="supporting-data-content">
|
||||
<div class="supporting-data-header">
|
||||
<span>支撑数据</span>
|
||||
<button onclick="closeSupportingData()">×</button>
|
||||
</div>
|
||||
<div class="supporting-data-body" id="supportingDataBody">
|
||||
</div>
|
||||
<button class="carousel-btn next" onclick="nextImage()"><i
|
||||
class="fa-solid fa-chevron-right"></i></button>
|
||||
</div>
|
||||
<div class="image-info" id="imageInfo" style="margin-top:1rem; text-align:center;">
|
||||
<!-- Title/Desc -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -6,17 +6,44 @@ const startBtn = document.getElementById('startBtn');
|
||||
const requirementInput = document.getElementById('requirementInput');
|
||||
const statusDot = document.getElementById('statusDot');
|
||||
const statusText = document.getElementById('statusText');
|
||||
const logOutput = document.getElementById('logOutput');
|
||||
const reportContainer = document.getElementById('reportContainer');
|
||||
const downloadScriptBtn = document.getElementById('downloadScriptBtn');
|
||||
|
||||
let isRunning = false;
|
||||
let pollingInterval = null;
|
||||
let currentSessionId = null;
|
||||
let selectedTemplate = '';
|
||||
|
||||
// 报告段落数据(用于润色功能)
|
||||
let reportParagraphs = [];
|
||||
|
||||
// Supporting data from report API
|
||||
let supportingData = {};
|
||||
|
||||
// Execution Process state
|
||||
let lastRenderedRound = 0;
|
||||
|
||||
// --- Progress Bar ---
|
||||
function updateProgressBar(percentage, message, currentRound, maxRounds) {
|
||||
const container = document.getElementById('progressBarContainer');
|
||||
const fill = document.getElementById('progressBarFill');
|
||||
const label = document.getElementById('progressLabel');
|
||||
const percent = document.getElementById('progressPercent');
|
||||
const msg = document.getElementById('progressMessage');
|
||||
if (!container || !fill) return;
|
||||
|
||||
container.classList.remove('hidden');
|
||||
fill.style.width = percentage + '%';
|
||||
if (label) label.textContent = `Round ${currentRound || 0}/${maxRounds || 0}`;
|
||||
if (percent) percent.textContent = Math.round(percentage) + '%';
|
||||
if (msg) msg.textContent = message || '';
|
||||
}
|
||||
|
||||
function hideProgressBar() {
|
||||
const container = document.getElementById('progressBarContainer');
|
||||
if (container) container.classList.add('hidden');
|
||||
}
|
||||
|
||||
// --- Upload Logic ---
|
||||
if (uploadZone) {
|
||||
uploadZone.addEventListener('dragover', (e) => {
|
||||
@@ -60,6 +87,34 @@ async function handleFiles(files) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Template Logic ---
|
||||
async function loadTemplates() {
|
||||
try {
|
||||
const res = await fetch('/api/templates');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const selector = document.getElementById('templateSelector');
|
||||
if (!selector || !data.templates) return;
|
||||
|
||||
for (const tpl of data.templates) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'template-card';
|
||||
card.setAttribute('data-template', tpl.name);
|
||||
card.onclick = function() { selectTemplate(this, tpl.name); };
|
||||
card.innerHTML = `<div class="template-card-title">${tpl.display_name}</div><div class="template-card-desc">${tpl.description}</div>`;
|
||||
selector.appendChild(card);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load templates', e);
|
||||
}
|
||||
}
|
||||
|
||||
window.selectTemplate = function(el, name) {
|
||||
document.querySelectorAll('.template-card').forEach(c => c.classList.remove('selected'));
|
||||
el.classList.add('selected');
|
||||
selectedTemplate = name;
|
||||
}
|
||||
|
||||
// --- Analysis Logic ---
|
||||
if (startBtn) {
|
||||
startBtn.addEventListener('click', startAnalysis);
|
||||
@@ -75,19 +130,30 @@ async function startAnalysis() {
|
||||
}
|
||||
|
||||
setRunningState(true);
|
||||
// Reset execution state for new analysis
|
||||
lastRenderedRound = 0;
|
||||
const wrapper = document.getElementById('roundCardsWrapper');
|
||||
if (wrapper) wrapper.innerHTML = '';
|
||||
const emptyState = document.getElementById('executionEmptyState');
|
||||
if (emptyState) emptyState.remove();
|
||||
|
||||
try {
|
||||
const body = { requirement };
|
||||
if (selectedTemplate) {
|
||||
body.template = selectedTemplate;
|
||||
}
|
||||
|
||||
const res = await fetch('/api/start', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ requirement })
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
currentSessionId = data.session_id;
|
||||
startPolling();
|
||||
switchTab('logs');
|
||||
switchTab('execution');
|
||||
} else {
|
||||
const err = await res.json();
|
||||
alert('Failed to start: ' + err.detail);
|
||||
@@ -112,6 +178,8 @@ function setRunningState(running) {
|
||||
const followUpSection = document.getElementById('followUpSection');
|
||||
if (followUpSection) followUpSection.classList.add('hidden');
|
||||
if (downloadScriptBtn) downloadScriptBtn.classList.add('hidden');
|
||||
const tplGroup = document.getElementById('templateSelectorGroup');
|
||||
if (tplGroup) tplGroup.classList.add('hidden');
|
||||
} else {
|
||||
startBtn.innerHTML = '<i class="fa-solid fa-play"></i> Start Analysis';
|
||||
statusDot.className = 'status-dot';
|
||||
@@ -122,6 +190,7 @@ function setRunningState(running) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Polling ---
|
||||
function startPolling() {
|
||||
if (pollingInterval) clearInterval(pollingInterval);
|
||||
if (!currentSessionId) return;
|
||||
@@ -132,14 +201,29 @@ function startPolling() {
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
|
||||
logOutput.innerText = data.log || "Waiting for output...";
|
||||
const logTab = document.getElementById('logsTab');
|
||||
if (logTab) logTab.scrollTop = logTab.scrollHeight;
|
||||
// Render round cards incrementally
|
||||
const rounds = data.rounds || [];
|
||||
renderRoundCards(rounds);
|
||||
|
||||
// Load data files during polling
|
||||
loadDataFiles();
|
||||
|
||||
// Update progress bar during analysis
|
||||
if (data.is_running && data.progress_percentage !== undefined) {
|
||||
updateProgressBar(data.progress_percentage, data.status_message, data.current_round, data.max_rounds);
|
||||
}
|
||||
|
||||
if (!data.is_running && isRunning) {
|
||||
updateProgressBar(100, 'Analysis complete', data.current_round || data.max_rounds, data.max_rounds);
|
||||
setTimeout(hideProgressBar, 3000);
|
||||
|
||||
setRunningState(false);
|
||||
clearInterval(pollingInterval);
|
||||
|
||||
// Final render of rounds
|
||||
renderRoundCards(data.rounds || []);
|
||||
loadDataFiles();
|
||||
|
||||
if (data.has_report) {
|
||||
await loadReport();
|
||||
switchTab('report');
|
||||
@@ -155,7 +239,215 @@ function startPolling() {
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
// --- Report Logic (with paragraph-level polishing) ---
|
||||
// --- Execution Process Tab (Task 11) ---
|
||||
|
||||
function renderRoundCards(rounds) {
|
||||
if (!rounds || rounds.length === 0) return;
|
||||
|
||||
const wrapper = document.getElementById('roundCardsWrapper');
|
||||
if (!wrapper) return;
|
||||
|
||||
// Handle server restart: if rounds shrunk, re-render all
|
||||
if (rounds.length < lastRenderedRound) {
|
||||
lastRenderedRound = 0;
|
||||
wrapper.innerHTML = '';
|
||||
}
|
||||
|
||||
// Remove empty state if present
|
||||
const emptyState = document.getElementById('executionEmptyState');
|
||||
if (emptyState) emptyState.remove();
|
||||
|
||||
// Only render new rounds
|
||||
for (let i = lastRenderedRound; i < rounds.length; i++) {
|
||||
const rd = rounds[i];
|
||||
const card = createRoundCard(rd);
|
||||
wrapper.appendChild(card);
|
||||
}
|
||||
|
||||
lastRenderedRound = rounds.length;
|
||||
|
||||
// Auto-scroll when running
|
||||
if (isRunning) {
|
||||
const executionTab = document.getElementById('executionTab');
|
||||
if (executionTab) {
|
||||
executionTab.scrollTop = executionTab.scrollHeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function createRoundCard(rd) {
|
||||
const roundNum = rd.round || 0;
|
||||
const summary = escapeHtml(rd.result_summary || '');
|
||||
const reasoning = escapeHtml(rd.reasoning || '');
|
||||
const code = escapeHtml(rd.code || '');
|
||||
const rawLog = escapeHtml(rd.raw_log || '');
|
||||
|
||||
const card = document.createElement('div');
|
||||
card.className = 'round-card';
|
||||
card.setAttribute('data-round', roundNum);
|
||||
|
||||
// Build evidence table HTML
|
||||
let evidenceHtml = '';
|
||||
const evidenceRows = rd.evidence_rows || [];
|
||||
if (evidenceRows.length > 0) {
|
||||
const cols = Object.keys(evidenceRows[0]);
|
||||
evidenceHtml = `
|
||||
<div class="round-section">
|
||||
<div class="round-section-title">本轮数据案例</div>
|
||||
<table class="evidence-table">
|
||||
<thead><tr>${cols.map(c => `<th>${escapeHtml(c)}</th>`).join('')}</tr></thead>
|
||||
<tbody>${evidenceRows.map(row =>
|
||||
`<tr>${cols.map(c => `<td>${escapeHtml(String(row[c] ?? ''))}</td>`).join('')}</tr>`
|
||||
).join('')}</tbody>
|
||||
</table>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
card.innerHTML = `
|
||||
<div class="round-card-header" onclick="toggleRoundCard(${roundNum})">
|
||||
<span class="round-number">Round ${roundNum}</span>
|
||||
<span class="round-summary">${summary}</span>
|
||||
<i class="fa-solid fa-chevron-down round-toggle-icon"></i>
|
||||
</div>
|
||||
<div class="round-card-body hidden">
|
||||
<div class="round-section">
|
||||
<div class="round-section-title">AI 推理</div>
|
||||
<div class="round-reasoning">${reasoning}</div>
|
||||
</div>
|
||||
<details class="round-details">
|
||||
<summary>代码</summary>
|
||||
<pre class="round-code">${code}</pre>
|
||||
</details>
|
||||
<div class="round-section">
|
||||
<div class="round-section-title">执行结果</div>
|
||||
<div class="round-result">${summary}</div>
|
||||
</div>
|
||||
${evidenceHtml}
|
||||
<details class="round-details">
|
||||
<summary>原始日志</summary>
|
||||
<pre class="round-raw-log">${rawLog}</pre>
|
||||
</details>
|
||||
</div>
|
||||
`;
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
window.toggleRoundCard = function(roundNum) {
|
||||
const card = document.querySelector(`.round-card[data-round="${roundNum}"]`);
|
||||
if (!card) return;
|
||||
const body = card.querySelector('.round-card-body');
|
||||
const icon = card.querySelector('.round-toggle-icon');
|
||||
if (!body) return;
|
||||
|
||||
body.classList.toggle('hidden');
|
||||
if (icon) {
|
||||
icon.classList.toggle('fa-chevron-down');
|
||||
icon.classList.toggle('fa-chevron-up');
|
||||
}
|
||||
card.classList.toggle('expanded');
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// --- Data Files Tab (Task 12) ---
|
||||
|
||||
async function loadDataFiles() {
|
||||
if (!currentSessionId) return;
|
||||
try {
|
||||
const res = await fetch(`/api/data-files?session_id=${currentSessionId}`);
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const files = data.files || [];
|
||||
|
||||
const grid = document.getElementById('fileCardsGrid');
|
||||
const emptyState = document.getElementById('datafilesEmptyState');
|
||||
if (!grid) return;
|
||||
|
||||
if (files.length === 0) {
|
||||
grid.innerHTML = '';
|
||||
if (emptyState) emptyState.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
if (emptyState) emptyState.classList.add('hidden');
|
||||
|
||||
grid.innerHTML = files.map(f => {
|
||||
const desc = escapeHtml(f.description || '');
|
||||
const name = escapeHtml(f.filename || '');
|
||||
const rows = f.rows || 0;
|
||||
const iconClass = name.endsWith('.xlsx') ? 'fa-file-excel' : 'fa-file-csv';
|
||||
return `
|
||||
<div class="data-file-card" onclick="previewDataFile('${escapeHtml(f.filename)}')">
|
||||
<div class="data-file-icon"><i class="fa-regular ${iconClass}"></i></div>
|
||||
<div class="data-file-info">
|
||||
<div class="data-file-name">${name}</div>
|
||||
<div class="data-file-desc">${desc} · ${rows}行</div>
|
||||
</div>
|
||||
<button class="btn btn-sm btn-secondary" onclick="event.stopPropagation(); downloadDataFile('${escapeHtml(f.filename)}')">
|
||||
<i class="fa-solid fa-download"></i>
|
||||
</button>
|
||||
</div>`;
|
||||
}).join('');
|
||||
} catch (e) {
|
||||
console.error('Failed to load data files', e);
|
||||
}
|
||||
}
|
||||
|
||||
window.previewDataFile = async function(filename) {
|
||||
if (!currentSessionId) return;
|
||||
try {
|
||||
const res = await fetch(`/api/data-files/preview?session_id=${currentSessionId}&filename=${encodeURIComponent(filename)}`);
|
||||
if (!res.ok) {
|
||||
alert('Failed to load preview');
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
const columns = data.columns || [];
|
||||
const rows = data.rows || [];
|
||||
|
||||
const panel = document.getElementById('dataPreviewPanel');
|
||||
const nameEl = document.getElementById('previewFileName');
|
||||
const container = document.getElementById('previewTableContainer');
|
||||
if (!panel || !container) return;
|
||||
|
||||
nameEl.textContent = filename;
|
||||
|
||||
let tableHtml = '<table class="data-preview-table">';
|
||||
tableHtml += '<thead><tr>' + columns.map(c => `<th>${escapeHtml(c)}</th>`).join('') + '</tr></thead>';
|
||||
tableHtml += '<tbody>';
|
||||
for (const row of rows) {
|
||||
tableHtml += '<tr>' + columns.map(c => `<td>${escapeHtml(String(row[c] ?? ''))}</td>`).join('') + '</tr>';
|
||||
}
|
||||
tableHtml += '</tbody></table>';
|
||||
|
||||
container.innerHTML = tableHtml;
|
||||
panel.classList.remove('hidden');
|
||||
} catch (e) {
|
||||
console.error('Preview failed', e);
|
||||
}
|
||||
}
|
||||
|
||||
window.downloadDataFile = function(filename) {
|
||||
if (!currentSessionId) return;
|
||||
const link = document.createElement('a');
|
||||
link.href = `/api/data-files/download?session_id=${currentSessionId}&filename=${encodeURIComponent(filename)}`;
|
||||
link.download = '';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
|
||||
window.closePreview = function() {
|
||||
const panel = document.getElementById('dataPreviewPanel');
|
||||
if (panel) panel.classList.add('hidden');
|
||||
}
|
||||
|
||||
// --- Report Logic with Supporting Data (Task 14) ---
|
||||
|
||||
async function loadReport() {
|
||||
if (!currentSessionId) return;
|
||||
@@ -166,13 +458,13 @@ async function loadReport() {
|
||||
if (!data.content || data.content === "Report not ready.") {
|
||||
reportContainer.innerHTML = '<div class="empty-state"><p>Analysis in progress or no report generated yet.</p></div>';
|
||||
reportParagraphs = [];
|
||||
supportingData = {};
|
||||
return;
|
||||
}
|
||||
|
||||
// 保存段落数据
|
||||
reportParagraphs = data.paragraphs || [];
|
||||
supportingData = data.supporting_data || {};
|
||||
|
||||
// 渲染段落化的报告(支持点击润色)
|
||||
renderParagraphReport(reportParagraphs);
|
||||
|
||||
} catch (e) {
|
||||
@@ -190,9 +482,14 @@ function renderParagraphReport(paragraphs) {
|
||||
for (const p of paragraphs) {
|
||||
const renderedContent = marked.parse(p.content);
|
||||
const typeClass = `para-${p.type}`;
|
||||
const hasSupportingData = supportingData[p.id] && supportingData[p.id].length > 0;
|
||||
const supportingBtn = hasSupportingData
|
||||
? `<button class="supporting-data-btn" onclick="event.stopPropagation(); showSupportingData('${p.id}')"><i class="fa-solid fa-table"></i> 查看支撑数据</button>`
|
||||
: '';
|
||||
html += `
|
||||
<div class="report-paragraph ${typeClass}" data-para-id="${p.id}" onclick="selectParagraph('${p.id}')">
|
||||
<div class="para-content">${renderedContent}</div>
|
||||
${supportingBtn}
|
||||
<div class="para-actions hidden">
|
||||
<button class="polish-btn" onclick="event.stopPropagation(); polishParagraph('${p.id}', 'context')" title="根据上下文润色">
|
||||
<i class="fa-solid fa-wand-magic-sparkles"></i> 上下文润色
|
||||
@@ -210,14 +507,40 @@ function renderParagraphReport(paragraphs) {
|
||||
reportContainer.innerHTML = html;
|
||||
}
|
||||
|
||||
window.showSupportingData = function(paraId) {
|
||||
const rows = supportingData[paraId];
|
||||
if (!rows || rows.length === 0) return;
|
||||
|
||||
const modal = document.getElementById('supportingDataModal');
|
||||
const body = document.getElementById('supportingDataBody');
|
||||
if (!modal || !body) return;
|
||||
|
||||
const cols = Object.keys(rows[0]);
|
||||
let tableHtml = '<table class="evidence-table">';
|
||||
tableHtml += '<thead><tr>' + cols.map(c => `<th>${escapeHtml(c)}</th>`).join('') + '</tr></thead>';
|
||||
tableHtml += '<tbody>';
|
||||
for (const row of rows) {
|
||||
tableHtml += '<tr>' + cols.map(c => `<td>${escapeHtml(String(row[c] ?? ''))}</td>`).join('') + '</tr>';
|
||||
}
|
||||
tableHtml += '</tbody></table>';
|
||||
|
||||
body.innerHTML = tableHtml;
|
||||
modal.classList.remove('hidden');
|
||||
}
|
||||
|
||||
window.closeSupportingData = function() {
|
||||
const modal = document.getElementById('supportingDataModal');
|
||||
if (modal) modal.classList.add('hidden');
|
||||
}
|
||||
|
||||
// --- Paragraph Selection & Polishing (preserved from original) ---
|
||||
|
||||
window.selectParagraph = function(paraId) {
|
||||
// 取消所有选中
|
||||
document.querySelectorAll('.report-paragraph').forEach(el => {
|
||||
el.classList.remove('selected');
|
||||
el.querySelector('.para-actions')?.classList.add('hidden');
|
||||
});
|
||||
|
||||
// 选中当前段落
|
||||
const target = document.querySelector(`[data-para-id="${paraId}"]`);
|
||||
if (target) {
|
||||
target.classList.add('selected');
|
||||
@@ -231,7 +554,6 @@ window.polishParagraph = async function(paraId, mode, customInstruction = '') {
|
||||
const target = document.querySelector(`[data-para-id="${paraId}"]`);
|
||||
if (!target) return;
|
||||
|
||||
// 显示加载状态
|
||||
const actionsEl = target.querySelector('.para-actions');
|
||||
const originalActions = actionsEl.innerHTML;
|
||||
actionsEl.innerHTML = '<span class="polish-loading"><i class="fa-solid fa-spinner fa-spin"></i> AI 润色中...</span>';
|
||||
@@ -256,8 +578,6 @@ window.polishParagraph = async function(paraId, mode, customInstruction = '') {
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
// 显示对比视图
|
||||
showPolishDiff(target, paraId, data.original, data.polished);
|
||||
|
||||
} catch (e) {
|
||||
@@ -296,7 +616,6 @@ function showPolishDiff(targetEl, paraId, original, polished) {
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 用 addEventListener 绑定,避免内联 onclick 中特殊字符破坏 HTML
|
||||
document.getElementById(`acceptBtn-${paraId}`).addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
applyPolish(paraId, polished);
|
||||
@@ -322,7 +641,6 @@ window.applyPolish = async function(paraId, newContent) {
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
// 重新加载报告
|
||||
await loadReport();
|
||||
} else {
|
||||
alert('应用失败');
|
||||
@@ -334,7 +652,6 @@ window.applyPolish = async function(paraId, newContent) {
|
||||
}
|
||||
|
||||
window.rejectPolish = function(paraId) {
|
||||
// 重新加载报告恢复原状
|
||||
loadReport();
|
||||
}
|
||||
|
||||
@@ -371,55 +688,6 @@ window.submitCustomPolish = function(paraId) {
|
||||
polishParagraph(paraId, 'custom', instruction);
|
||||
}
|
||||
|
||||
// --- Gallery Logic ---
|
||||
let galleryImages = [];
|
||||
let currentImageIndex = 0;
|
||||
|
||||
async function loadGallery() {
|
||||
if (!currentSessionId) return;
|
||||
try {
|
||||
const res = await fetch(`/api/figures?session_id=${currentSessionId}`);
|
||||
const data = await res.json();
|
||||
galleryImages = data.figures || [];
|
||||
currentImageIndex = 0;
|
||||
renderGalleryImage();
|
||||
} catch (e) {
|
||||
console.error("Gallery load failed", e);
|
||||
document.getElementById('carouselSlide').innerHTML = '<p class="error">Failed to load images.</p>';
|
||||
}
|
||||
}
|
||||
|
||||
function renderGalleryImage() {
|
||||
const slide = document.getElementById('carouselSlide');
|
||||
const info = document.getElementById('imageInfo');
|
||||
|
||||
if (galleryImages.length === 0) {
|
||||
slide.innerHTML = '<p class="placeholder-text" style="color:var(--text-secondary);">No images generated in this session.</p>';
|
||||
info.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const img = galleryImages[currentImageIndex];
|
||||
slide.innerHTML = `<img src="${img.web_url}" alt="${img.filename}" onclick="window.open('${img.web_url}', '_blank')">`;
|
||||
info.innerHTML = `
|
||||
<div class="image-title">${img.filename} (${currentImageIndex + 1}/${galleryImages.length})</div>
|
||||
<div class="image-desc">${img.description || 'No description available.'}</div>
|
||||
${img.analysis ? `<div style="font-size:0.8rem; margin-top:0.5rem; color:#4B5563; background:#F3F4F6; padding:0.5rem; border-radius:4px;">${img.analysis}</div>` : ''}
|
||||
`;
|
||||
}
|
||||
|
||||
window.prevImage = function () {
|
||||
if (galleryImages.length === 0) return;
|
||||
currentImageIndex = (currentImageIndex - 1 + galleryImages.length) % galleryImages.length;
|
||||
renderGalleryImage();
|
||||
}
|
||||
|
||||
window.nextImage = function () {
|
||||
if (galleryImages.length === 0) return;
|
||||
currentImageIndex = (currentImageIndex + 1) % galleryImages.length;
|
||||
renderGalleryImage();
|
||||
}
|
||||
|
||||
// --- Download / Export ---
|
||||
window.downloadScript = async function () {
|
||||
if (!currentSessionId) return;
|
||||
@@ -471,8 +739,12 @@ window.sendFollowUp = async function () {
|
||||
if (res.ok) {
|
||||
input.value = '';
|
||||
setRunningState(true);
|
||||
// Reset round rendering for follow-up
|
||||
lastRenderedRound = 0;
|
||||
const wrapper = document.getElementById('roundCardsWrapper');
|
||||
if (wrapper) wrapper.innerHTML = '';
|
||||
startPolling();
|
||||
switchTab('logs');
|
||||
switchTab('execution');
|
||||
} else {
|
||||
alert('Failed to send request');
|
||||
}
|
||||
@@ -524,18 +796,26 @@ window.loadSession = async function (sessionId) {
|
||||
const activeItem = document.getElementById(`hist-${sessionId}`);
|
||||
if (activeItem) activeItem.classList.add('active');
|
||||
|
||||
logOutput.innerText = "Loading session data...";
|
||||
reportContainer.innerHTML = "";
|
||||
if (downloadScriptBtn) downloadScriptBtn.classList.add('hidden');
|
||||
const tplGroup = document.getElementById('templateSelectorGroup');
|
||||
if (tplGroup) tplGroup.classList.add('hidden');
|
||||
|
||||
// Reset execution state for loaded session
|
||||
lastRenderedRound = 0;
|
||||
const wrapper = document.getElementById('roundCardsWrapper');
|
||||
if (wrapper) wrapper.innerHTML = '';
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/status?session_id=${sessionId}`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
logOutput.innerText = data.log || "No logs available.";
|
||||
|
||||
const logTab = document.getElementById('logsTab');
|
||||
if (logTab) logTab.scrollTop = logTab.scrollHeight;
|
||||
// Render rounds for historical session
|
||||
renderRoundCards(data.rounds || []);
|
||||
|
||||
// Load data files for historical session
|
||||
loadDataFiles();
|
||||
|
||||
if (data.has_report) {
|
||||
await loadReport();
|
||||
@@ -545,16 +825,17 @@ window.loadSession = async function (sessionId) {
|
||||
}
|
||||
switchTab('report');
|
||||
} else {
|
||||
switchTab('logs');
|
||||
switchTab('execution');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logOutput.innerText = "Error loading session.";
|
||||
console.error("Error loading session", e);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Init & Navigation ---
|
||||
// --- Init & Navigation (Task 13) ---
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
loadTemplates();
|
||||
loadHistory();
|
||||
});
|
||||
|
||||
@@ -563,25 +844,29 @@ window.switchView = function (viewName) {
|
||||
}
|
||||
|
||||
window.switchTab = function (tabName) {
|
||||
// Deactivate all tabs
|
||||
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
|
||||
|
||||
['logs', 'report', 'gallery'].forEach(name => {
|
||||
// Hide all tab content
|
||||
['execution', 'datafiles', 'report'].forEach(name => {
|
||||
const content = document.getElementById(`${name}Tab`);
|
||||
if (content) content.classList.add('hidden');
|
||||
});
|
||||
|
||||
// Activate the clicked tab button
|
||||
document.querySelectorAll('.tab').forEach(btn => {
|
||||
if (btn.getAttribute('onclick') && btn.getAttribute('onclick').includes(`'${tabName}'`)) {
|
||||
btn.classList.add('active');
|
||||
}
|
||||
});
|
||||
|
||||
if (tabName === 'logs') {
|
||||
document.getElementById('logsTab').classList.remove('hidden');
|
||||
// Show the selected tab content
|
||||
if (tabName === 'execution') {
|
||||
document.getElementById('executionTab').classList.remove('hidden');
|
||||
} else if (tabName === 'datafiles') {
|
||||
document.getElementById('datafilesTab').classList.remove('hidden');
|
||||
if (currentSessionId) loadDataFiles();
|
||||
} else if (tabName === 'report') {
|
||||
document.getElementById('reportTab').classList.remove('hidden');
|
||||
} else if (tabName === 'gallery') {
|
||||
document.getElementById('galleryTab').classList.remove('hidden');
|
||||
if (currentSessionId) loadGallery();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user