Commit 59d72f67 by 江名洋

fix: 优化任务详情展示与ETL卡住清理逻辑

1 parent 6002b83e
No preview for this file type
......@@ -112,11 +112,16 @@ async def get_etl_status():
@router.get("/etl/history")
async def get_etl_history(
task_id: str = Query(None),
limit: int = Query(10)
limit: int = Query(10),
task_pattern: str = Query(None)
):
"""获取执行历史"""
"""获取执行历史
- task_id: 精确匹配
- task_pattern: LIKE 模糊匹配,如 '%_ods_sync' 匹配所有 ODS 同步任务
"""
try:
return await ETLService.get_etl_history(task_id=task_id, limit=limit)
return await ETLService.get_etl_history(task_id=task_id, limit=limit, task_pattern=task_pattern)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
......
......@@ -532,16 +532,27 @@ class ETLService:
db.close()
@staticmethod
async def get_etl_history(task_id: str = None, limit: int = 10):
"""获取任务执行历史"""
async def get_etl_history(task_id: str = None, limit: int = 10, task_pattern: str = None):
"""获取任务执行历史
Args:
task_id: 精确匹配 task_id
limit: 返回条数上限
task_pattern: task_id 模糊匹配(LIKE 语法),如 '%_ods_sync' 匹配所有 ODS 同步任务
"""
db = SessionLocal()
try:
query = "SELECT * FROM _etl_history"
query = "SELECT * FROM _etl_history WHERE 1=1"
params = {"limit": limit}
if task_id:
query += f" WHERE task_id = '{task_id}'"
query += " AND task_id = :task_id"
params["task_id"] = task_id
if task_pattern:
query += " AND task_id LIKE :task_pattern"
params["task_pattern"] = task_pattern
query += " ORDER BY start_time DESC LIMIT :limit"
result = db.execute(text(query), {"limit": limit}).fetchall()
result = db.execute(text(query), params).fetchall()
return [dict(row._asdict()) for row in result]
finally:
db.close()
......
......@@ -29,9 +29,16 @@ let pollingTimer = null;
let historyCache = {};
// ========== 历史记录渲染 ==========
async function fetchHistory(filterFn) {
// fetchHistory(filterFn, taskPattern)
// filterFn: 客户端二次过滤函数(可选)
// taskPattern: 服务端 LIKE 模式(可选),如 '%_ods_sync' 只取 ODS 相关记录
async function fetchHistory(filterFn, taskPattern) {
try {
const res = await fetch(window.API_BASE + '/etl/history?limit=15');
let url = window.API_BASE + '/etl/history?limit=50';
if (taskPattern) {
url += '&task_pattern=' + encodeURIComponent(taskPattern);
}
const res = await fetch(url);
const history = await res.json();
const tbody = document.getElementById('history-tbody');
if (!tbody) return false;
......@@ -62,12 +69,12 @@ async function fetchHistory(filterFn) {
}
}
function startPolling(filterFn) {
function startPolling(filterFn, taskPattern) {
if (pollingTimer) clearInterval(pollingTimer);
let count = 0;
pollingTimer = setInterval(async () => {
count++;
const hasRunning = await fetchHistory(filterFn);
const hasRunning = await fetchHistory(filterFn, taskPattern);
if (!hasRunning || count > 20) {
clearInterval(pollingTimer);
pollingTimer = null;
......@@ -87,23 +94,39 @@ window.showTaskDetail = function(id) {
try {
const data = JSON.parse(info);
if (Array.isArray(data)) {
data.forEach(item => {
const tr = document.createElement('tr');
const cls = item.status === 'success' ? 'status-success' : 'status-failed';
tr.innerHTML =
`<td>${item.source || item.table || '-'}</td>` +
`<td>${item.target || '-'}</td>` +
`<td style="font-size:11px;color:#666;">${item.range_start ? '从:' + item.range_start + '<br>至:' + item.range_end : '-'}</td>` +
`<td><strong>${item.rows ?? 0}</strong> 行</td>` +
`<td><span class="status-tag ${cls}">${item.status || 'unknown'}</span></td>`;
tbody.appendChild(tr);
});
if (data.length === 0) {
tbody.innerHTML = `<tr><td colspan="5" style="text-align:center;color:#999;">无详细记录</td></tr>`;
} else {
data.forEach(item => {
const tr = document.createElement('tr');
const st = item.status || 'unknown';
const cls = st === 'success' ? 'status-success'
: (st === 'no_data' || st === 'no_valid_data' ? 'status-skip' : 'status-failed');
const rangeText = item.range_start ? '从: ' + item.range_start + '<br>至: ' + item.range_end : '-';
tr.innerHTML =
`<td>${item.source || item.table || '-'}</td>` +
`<td>${item.target || '-'}</td>` +
`<td style="font-size:11px;color:#666;">${rangeText}</td>` +
`<td><strong>${item.rows ?? 0}</strong> 行</td>` +
`<td><span class="status-tag ${cls}">${st}</span></td>`;
tbody.appendChild(tr);
});
}
} else {
tbody.innerHTML = `<tr><td colspan="4"><pre style="white-space:pre-wrap;">${JSON.stringify(data,null,2)}</pre></td></tr>`;
tbody.innerHTML = `<tr><td colspan="5"><pre style="white-space:pre-wrap;max-height:300px;overflow:auto;">${JSON.stringify(data, null, 2)}</pre></td></tr>`;
}
modal.style.display = 'block';
} catch(e) {
tbody.innerHTML = `<tr><td colspan="4">${info}</td></tr>`;
// result_info 不是 JSON(如纯文本错误信息),直接展示
const errText = info || '(无信息)';
const isError = /error|exception|failed|traceback|interrupt/i.test(errText);
tbody.innerHTML =
`<tr><td colspan="5" style="padding:16px;">
<div style="color:${isError ? '#f5222d' : '#666'};font-weight:bold;margin-bottom:8px;">
${isError ? '❌ 执行失败' : '执行信息'}
</div>
<pre style="white-space:pre-wrap;word-break:break-all;background:#fafafa;padding:12px;border-radius:4px;font-size:12px;max-height:300px;overflow:auto;">${errText}</pre>
</td></tr>`;
modal.style.display = 'block';
}
};
......
......@@ -109,7 +109,7 @@
const end = document.getElementById('dw-end-date');
if (start && !start.value) start.value = fmtDate(lastMonth26);
if (end && !end.value) end.value = fmtDate(now);
fetchHistory(DW_FILTER);
fetchHistory(DW_FILTER, '%_dw%_sync');
});
document.getElementById('btn-run-dw').addEventListener('click', async () => {
......@@ -135,8 +135,8 @@
const data = await res.json();
if (data.status === 'success') {
setTimeout(() => { btn.disabled = false; btn.textContent = '开始加工'; }, 2000);
fetchHistory(DW_FILTER);
startPolling(DW_FILTER);
fetchHistory(DW_FILTER, '%_dw%_sync');
startPolling(DW_FILTER, '%_dw%_sync');
} else {
alert('执行失败: ' + data.detail);
btn.disabled = false;
......
......@@ -96,7 +96,7 @@
} catch (err) {
console.error('获取配置失败:', err);
}
fetchHistory(ODS_FILTER);
fetchHistory(ODS_FILTER, '%_ods_sync');
});
document.getElementById('btn-run-ods').addEventListener('click', async () => {
......@@ -108,8 +108,8 @@
const data = await res.json();
if (data.status === 'success') {
setTimeout(() => { btn.disabled = false; btn.textContent = '立即同步 ODS'; }, 2000);
fetchHistory(ODS_FILTER);
startPolling(ODS_FILTER);
fetchHistory(ODS_FILTER, '%_ods_sync');
startPolling(ODS_FILTER, '%_ods_sync');
} else {
alert('执行失败: ' + data.detail);
btn.disabled = false;
......
......@@ -67,7 +67,8 @@ async def lifespan(app: FastAPI):
await asyncio.to_thread(StrategyService.ensure_result_table)
except Exception as e:
print(f"[!] Failed to create strategy result table: {e}")
# 清理启动前卡住的 running 状态 ETL 历史记录
# 清理启动前卡住的 running 状态 ETL 历史记录(仅清理超过 2 小时未完成的任务)
# 避免 reload 模式下将正在正常执行的 scheduler 任务误标记为 failed
try:
from sqlalchemy import text
from app.db.session import SessionLocal
......@@ -76,7 +77,7 @@ async def lifespan(app: FastAPI):
result = db.execute(text(
"UPDATE _etl_history SET status = 'failed', "
"end_time = NOW(), result_info = 'Server restarted, task interrupted' "
"WHERE status = 'running'"
"WHERE status = 'running' AND start_time < DATE_SUB(NOW(), INTERVAL 2 HOUR)"
))
db.commit()
stuck_count = getattr(result, 'rowcount', 0)
......
# -*- coding: utf-8 -*-
"""临时脚本:使用项目目录作为模型目录,测试 PPStructureV3"""
import os
import sys
# 指向项目内有写权限的目录(已经在 .bat 或 shell 中设置了 PADDLE_PDX_MODEL_DIR)
model_dir = os.environ.get("PADDLE_PDX_MODEL_DIR", r"d:\work1\data-analyze-webui\.paddlex_models")
os.makedirs(model_dir, exist_ok=True)
from paddleocr import PPStructureV3
print(f"Model dir: {model_dir}", flush=True)
print("Creating PPStructureV3 (use_doc_unwarping=False)...", flush=True)
engine = PPStructureV3(use_doc_unwarping=False)
print("Created! Running predict...", flush=True)
result = engine.predict(r"C:\Users\jiata\Desktop\微信图片_20260722093956_9_32.png")
print(f"\nResult type: {type(result)}, length: {len(result)}", flush=True)
for i, item in enumerate(result[:10]):
print(f"\n--- Item {i} ({type(item).__name__}) ---", flush=True)
if isinstance(item, dict):
print(f" keys: {list(item.keys())}", flush=True)
for k, v in item.items():
if k == "res" and isinstance(v, dict):
print(f" [{k}] keys={list(v.keys())}", flush=True)
if "html" in v:
print(f" html [{len(v['html'])}]: {v['html'][:500]}", flush=True)
else:
s = str(v)
if len(s) > 150:
s = s[:150] + "..."
print(f" [{k}]: {s}", flush=True)
# 保存为 Excel
htmls = []
for item in result:
if isinstance(item, dict) and item.get("type") == "table":
html = item.get("res", {}).get("html", "")
if html:
htmls.append(html)
print(f"\nFound {len(htmls)} tables", flush=True)
if htmls:
import pandas as pd
excel_path = r"d:\work1\data-analyze-webui\output_paddle_test.xlsx"
with pd.ExcelWriter(excel_path, engine="openpyxl") as writer:
for idx, html in enumerate(htmls):
dfs = pd.read_html(html)
if dfs:
dfs[0].to_excel(writer, index=False, sheet_name=f"Table_{idx+1}")
print(f"Saved to {excel_path}", flush=True)
......@@ -137,16 +137,67 @@ def _call_paddle_structure(image_path: str) -> list:
print(f"[*] PaddleOCR PP-Structure 识别中: {image_path}")
img = Image.open(path)
print(f" [图片] {img.size[0]}x{img.size[1]}, mode={img.mode}")
img.close()
orig_w, orig_h = img.size[0], img.size[1]
print(f" [图片] {orig_w}x{orig_h}, mode={img.mode}")
# 大图缩放:长边限制 1600px,大幅加速纯 CPU 推理
MAX_LONG_SIDE = 1600
long_side = max(orig_w, orig_h)
if long_side > MAX_LONG_SIDE:
scale = MAX_LONG_SIDE / long_side
new_w, new_h = int(orig_w * scale), int(orig_h * scale)
img = img.resize((new_w, new_h), Image.LANCZOS)
print(f" [缩放] {orig_w}x{orig_h} → {new_w}x{new_h}(长边限制 {MAX_LONG_SIDE}px)")
# 保存缩放后的图片到临时文件
import tempfile
tmp_fd, tmp_path = tempfile.mkstemp(suffix='.png')
os.close(tmp_fd)
img.save(tmp_path)
img.close()
predict_path = tmp_path
else:
img.close()
predict_path = str(path)
# PPStructureV3 自动完成:布局分析 → 表格检测 → 表格结构识别 → 单元格 OCR
# use_doc_unwarping=False 避免加载 UVDoc 弯曲矫正模型(减少依赖/权限问题)
engine = PPStructureV3(use_doc_unwarping=False, enable_mkldnn=False)
result = engine.predict(str(path))
tables = [r for r in result if r.get("type") == "table"]
print(f"[*] 开始执行 predict(输入: {predict_path})...")
try:
result = engine.predict(predict_path)
finally:
if predict_path != str(path):
os.unlink(predict_path)
print(f"[*] predict 完成,返回类型: {type(result)}")
# PPStructureV3.predict() 返回生成器,需要 list() 展开
if not isinstance(result, list):
result = list(result)
print(f"[*] 结果数量: {len(result)}")
if result:
print(f"[*] 第一项类型: {type(result[0])}")
if hasattr(result[0], '__dict__'):
print(f"[*] 第一项属性: {list(result[0].__dict__.keys())[:15]}")
elif isinstance(result[0], dict):
print(f"[*] 第一项 keys: {list(result[0].keys())[:15]}")
# 打印每项的 type 字段
for idx, r in enumerate(result[:5]):
if isinstance(r, dict):
print(f" [{idx}] type={r.get('type', 'N/A')}")
else:
print(f" [{idx}] {type(r).__name__}: {str(r)[:100]}")
tables = [r for r in result if isinstance(r, dict) and r.get("type") == "table"]
if not tables:
# 降级:如果没有 "table" 类型,尝试找包含 html 的项
tables = [r for r in result if isinstance(r, dict) and 'res' in r and 'html' in str(r.get('res', ''))]
if tables:
print(f" [降级] 通过 html 字段找到 {len(tables)} 个表格")
if not tables:
print("[!] 未检测到表格,所有结果类型:")
for idx, r in enumerate(result):
if isinstance(r, dict):
print(f" [{idx}] type={r.get('type', 'N/A')}, keys={list(r.keys())[:10]}")
raise RuntimeError("未在图片中检测到表格,请确认图片包含清晰的表格区域")
print(f" [检测] 发现 {len(tables)} 个表格")
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!