Commit bcd74913 by 江名洋

feat(harmony): 添加鸿蒙子品牌分析接口及修复时区与调度配置

1 parent e2aa8c94
...@@ -874,6 +874,109 @@ async def harmony_download(file: str = Query(None)): ...@@ -874,6 +874,109 @@ async def harmony_download(file: str = Query(None)):
) )
# ==================== 鸿蒙子品牌分析接口 ====================
_sub_brand_file = None
@router.get("/harmony/sub-brand/template/{template_type}")
async def download_sub_brand_template(template_type: str):
"""下载鸿蒙子品牌分析模板文件"""
prefix_map = {
"output": "输出模板-鸿蒙子品牌-模板",
}
prefix = prefix_map.get(template_type)
if not prefix:
raise HTTPException(status_code=400, detail="无效的模板类型,支持: output")
try:
file_path = _find_latest_template(prefix)
except FileNotFoundError:
raise HTTPException(status_code=404, detail=f"未找到类型为 {template_type} 的模板文件")
filename = os.path.basename(file_path)
return FileResponse(file_path, filename=filename,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
@router.post("/harmony/sub-brand/upload")
async def sub_brand_upload(
data_file: UploadFile = File(...),
start_date: str = Form(None),
end_date: str = Form(None),
):
"""上传鸿蒙子品牌数据文件"""
global _sub_brand_file
if not data_file or not data_file.filename:
raise HTTPException(status_code=400, detail="请上传子品牌数据文件")
fname = _build_dated_filename(data_file.filename, "hm_sub_brand", start_date, end_date)
file_path = _date_path(fname, category="harmony")
with open(file_path, "wb") as f:
shutil.copyfileobj(data_file.file, f)
_sub_brand_file = file_path
return {"status": "success", "message": f"子品牌数据已上传: {data_file.filename}"}
@router.post("/harmony/sub-brand/generate")
async def sub_brand_generate(
start_date: str = Form(None),
end_date: str = Form(None),
):
"""根据上传的子品牌数据生成鸿蒙子品牌分析报表"""
global _sub_brand_file
if not _sub_brand_file or not os.path.exists(_sub_brand_file):
raise HTTPException(status_code=400, detail="请先上传子品牌数据文件")
try:
output_path = HarmonyAnalysisService.build_sub_brand_report(
_sub_brand_file,
start_date=start_date,
end_date=end_date,
)
return {
"status": "success",
"message": "鸿蒙子品牌分析报表已生成",
"file_path": output_path,
"download_url": f"api/harmony/sub-brand/download?file={os.path.basename(output_path)}",
}
except Exception as e:
logger.error(f"Sub-brand analysis generate failed: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"报表生成失败: {str(e)}")
@router.get("/harmony/sub-brand/download")
async def sub_brand_download(file: str = Query(None)):
"""下载鸿蒙子品牌分析报表"""
if file:
file_path = _find_file(file)
if not file_path:
raise HTTPException(status_code=404, detail="指定的报表文件不存在")
return FileResponse(
file_path, filename=file,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
output_files = sorted(
[os.path.join(root, f) for root, _ds, fs in os.walk(UPLOAD_BASE)
for f in fs if f.startswith("鸿蒙子品牌分析") and f.endswith(".xlsx")],
key=lambda f: os.path.getmtime(f),
reverse=True
)
if not output_files:
raise HTTPException(status_code=404, detail="未找到鸿蒙子品牌分析报表,请先生成")
file_path = output_files[0]
return FileResponse(
file_path,
filename=os.path.basename(file_path),
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
# ==================== 策略效果盯防接口 ==================== # ==================== 策略效果盯防接口 ====================
@router.get("/strategy/options") @router.get("/strategy/options")
......
...@@ -36,8 +36,8 @@ class Settings(BaseSettings): ...@@ -36,8 +36,8 @@ class Settings(BaseSettings):
@property @property
def database_url(self) -> str: def database_url(self) -> str:
"""返回 SQLAlchemy 连接字符串""" """返回 SQLAlchemy 连接字符串(session timezone 设为 UTC+8)"""
return f"mysql+pymysql://{self.DB_USER}:{self.DB_PASSWORD}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}?charset=utf8mb4" return f"mysql+pymysql://{self.DB_USER}:{self.DB_PASSWORD}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}?charset=utf8mb4&init_command=SET time_zone='%2B08:00'"
# LLM Settings (Qwen) # LLM Settings (Qwen)
LLM_QWEN_MODEL: str = "qwen3.7-plus" LLM_QWEN_MODEL: str = "qwen3.7-plus"
......
...@@ -31,28 +31,30 @@ class SchedulerManager: ...@@ -31,28 +31,30 @@ class SchedulerManager:
if cls._scheduler is None: if cls._scheduler is None:
cls._scheduler = AsyncIOScheduler() cls._scheduler = AsyncIOScheduler()
# 1. ODS 同步任务 (每 30 分钟执行一次,带 3s 抖动,模仿用户参考) # 1. ODS 同步任务 (每 3 小时执行一次,带 3s 抖动)
# start_date 设为启动后 30s,避免等 3 小时才首次执行
first_run = datetime.now() + timedelta(seconds=30)
cls._scheduler.add_job( cls._scheduler.add_job(
cls.sync_ods_task, cls.sync_ods_task,
IntervalTrigger(minutes=180, jitter=3), IntervalTrigger(minutes=180, jitter=3, start_date=first_run),
id="sync_ods_data", id="sync_ods_data",
max_instances=1, max_instances=1,
replace_existing=True replace_existing=True
) )
# 2. 策略效果分析任务 (每 2 小时执行一次) # 2. 策略效果分析任务 (每 2 小时执行一次,启动后 60s 首次执行)
cls._scheduler.add_job( cls._scheduler.add_job(
cls.sync_strategy_analysis, cls.sync_strategy_analysis,
IntervalTrigger(hours=2), IntervalTrigger(hours=2, start_date=first_run),
id="sync_strategy_analysis", id="sync_strategy_analysis",
max_instances=1, max_instances=1,
replace_existing=True, replace_existing=True,
) )
# 3. 盯防数据自动刷新 (每 1 小时扫描超过 4 小时未刷新的盯防数据) # 3. 盯防数据自动刷新 (每 1 小时扫描超过 4 小时未刷新的盯防数据,启动后 60s 首次执行)
cls._scheduler.add_job( cls._scheduler.add_job(
cls.auto_refresh_strategy_monitoring, cls.auto_refresh_strategy_monitoring,
IntervalTrigger(hours=1, jitter=120), IntervalTrigger(hours=1, jitter=120, start_date=first_run),
id="auto_refresh_strategy_monitoring", id="auto_refresh_strategy_monitoring",
max_instances=1, max_instances=1,
replace_existing=True, replace_existing=True,
......
...@@ -67,7 +67,8 @@ class ETLService: ...@@ -67,7 +67,8 @@ class ETLService:
charset='utf8mb4', charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor, cursorclass=pymysql.cursors.DictCursor,
connect_timeout=10, connect_timeout=10,
read_timeout=300 read_timeout=300,
init_command="SET time_zone='+08:00'"
) )
@staticmethod @staticmethod
...@@ -82,7 +83,8 @@ class ETLService: ...@@ -82,7 +83,8 @@ class ETLService:
cursorclass=pymysql.cursors.DictCursor, cursorclass=pymysql.cursors.DictCursor,
autocommit=True, autocommit=True,
connect_timeout=10, connect_timeout=10,
read_timeout=300 read_timeout=300,
init_command="SET time_zone='+08:00'"
) )
@classmethod @classmethod
...@@ -271,17 +273,33 @@ class ETLService: ...@@ -271,17 +273,33 @@ class ETLService:
except Exception as e: except Exception as e:
logger.error(f"[X] ODS Sync failed for task_id={task_id}: {e}", exc_info=True) logger.error(f"[X] ODS Sync failed for task_id={task_id}: {e}", exc_info=True)
if history_id: # 使用独立连接(pymysql)更新历史记录,避免 db 会话已损坏时更新失败
db.execute(text(""" cls._safe_update_history_failed(history_id, str(e))
UPDATE _etl_history SET end_time = NOW(), status = 'failed', result_info = :err
WHERE id = :id
"""), {"err": str(e), "id": history_id})
db.commit()
raise e raise e
finally: finally:
db.close() db.close()
@staticmethod @staticmethod
def _safe_update_history_failed(history_id: int, error_msg: str):
"""使用独立 pymysql 连接更新 _etl_history 失败状态,避免 SQLAlchemy session 已损坏时更新失败"""
if not history_id:
return
conn = None
try:
conn = ETLService.get_target_conn()
with conn.cursor() as cur:
cur.execute(
"UPDATE _etl_history SET end_time = NOW(), status = 'failed', result_info = %s WHERE id = %s",
(error_msg[:2000], history_id) # 截断超长错误信息
)
conn.commit()
except Exception as update_err:
logger.error(f"[X] Failed to update ETL history (id={history_id}) to 'failed': {update_err}")
finally:
if conn:
conn.close()
@staticmethod
def _populate_ods_store_config(): def _populate_ods_store_config():
""" """
从 ods_service_merchant 填充 ods_store_config 中缺失的门店基础信息, 从 ods_service_merchant 填充 ods_store_config 中缺失的门店基础信息,
...@@ -521,12 +539,7 @@ class ETLService: ...@@ -521,12 +539,7 @@ class ETLService:
except Exception as e: except Exception as e:
logger.error(f"[X] {layer} Sync failed for task_id={task_id}: {e}", exc_info=True) logger.error(f"[X] {layer} Sync failed for task_id={task_id}: {e}", exc_info=True)
if history_id: cls._safe_update_history_failed(history_id, str(e))
db.execute(text("""
UPDATE _etl_history SET end_time = NOW(), status = 'failed', result_info = :err
WHERE id = :id
"""), {"err": str(e), "id": history_id})
db.commit()
raise e raise e
finally: finally:
db.close() db.close()
......
...@@ -37,6 +37,9 @@ def _find_latest_template(prefix: str) -> str: ...@@ -37,6 +37,9 @@ def _find_latest_template(prefix: str) -> str:
HARMONY_BRAND_IDS = (2698, 2741, 2740, 2797) HARMONY_BRAND_IDS = (2698, 2741, 2740, 2797)
# 2695=问界, 2698=智界, 2741=享界, 2740=尊界, 2797=尚界 # 2695=问界, 2698=智界, 2741=享界, 2740=尊界, 2797=尚界
# 鸿蒙子品牌映射
SUB_BRAND_NAMES = {"智界": "智界", "享界": "享界", "尊界": "尊界", "尚界": "尚界"}
# first_brand_id(鸿蒙智行,参考 generate_weekly_comparison.py) # first_brand_id(鸿蒙智行,参考 generate_weekly_comparison.py)
FIRST_BRAND_ID = 2365 FIRST_BRAND_ID = 2365
...@@ -511,6 +514,271 @@ class HarmonyAnalysisService: ...@@ -511,6 +514,271 @@ class HarmonyAnalysisService:
logger.info(f"Harmony report generated: {output_path}") logger.info(f"Harmony report generated: {output_path}")
return output_path return output_path
# ──────────────── 鸿蒙子品牌分析 ────────────────
@staticmethod
def read_sub_brand_data(file_path: str) -> pd.DataFrame:
"""
读取鸿蒙子品牌Excel(含主机厂数据)。
structure: rows 0-1 headers, rows 2-6 subtotals (skip), rows 7+ store data.
columns: 门店, 兜底指标, 区域(省), 直营与否, 区域运营, 飞行督导,
线上运营, 品牌, 主机厂交付数, 产值表交付数, 触客数, 触客率,
整车延保成交订单数, 整车延保渗透率, 触客成交率,
安心包, 安心包渗透率, 电池, 电池渗透率
"""
df_raw = pd.read_excel(file_path, header=None)
# 自动定位子品牌sheet
xl = pd.ExcelFile(file_path)
target_sheet = None
for sn in xl.sheet_names:
if "子品牌" in str(sn):
target_sheet = sn
break
if target_sheet:
df_raw = pd.read_excel(file_path, sheet_name=target_sheet, header=None)
col_names = [
"门店名", "兜底指标", "区域(省)", "直营与否", "区域运营",
"飞行督导", "线上运营", "品牌",
"主机厂交付数", "产值表交付数", "触客数", "触客率",
"整车延保成交数", "整车延保渗透率", "触客成交率",
"安心包达成数量", "安心包渗透率", "电池延保成交数", "电池延保渗透率",
]
# 只取前19列
df_raw = df_raw.iloc[:, :len(col_names)]
df_raw.columns = col_names
# 数据从第8行开始(跳过header和subtotals)
start_row = 7
df = df_raw.iloc[start_row:].copy()
df = df.reset_index(drop=True)
# 过滤无效行
df = df[df["门店名"].notna() & (df["门店名"].astype(str).str.strip() != "")]
df = df[~df["门店名"].astype(str).str.strip().isin(
["门店", "品牌", "总计", "合计", "小计", "nan"])]
# 数值列转换
numeric_cols = [
"主机厂交付数", "产值表交付数", "触客数", "整车延保成交数",
"安心包达成数量", "电池延保成交数",
]
for c in numeric_cols:
if c in df.columns:
df[c] = pd.to_numeric(df[c], errors="coerce").fillna(0).astype(int)
rate_cols = ["触客率", "整车延保渗透率", "触客成交率", "安心包渗透率", "电池延保渗透率"]
for c in rate_cols:
if c in df.columns:
df[c] = pd.to_numeric(df[c], errors="coerce").fillna(0)
logger.info(f"Sub-brand data loaded: {len(df)} stores, brands={sorted(df['品牌'].dropna().unique())}")
return df
@staticmethod
def _parse_guarantee_text(text: str) -> dict:
"""
解析兜底指标文本,提取兜底类型、需达标转化率、赔付金额。
Returns: {"兜底类型": str, "需达标_整车延保": float, "需达标_安心包": float,
"需达标_电池延保": float, "赔付_整车延保": float, "赔付_安心包": float,
"赔付_电池延保": float, "特殊情况": str}
"""
result = {
"兜底类型": "触客",
"需达标_整车延保": 0.0,
"需达标_安心包": 0.0,
"需达标_电池延保": 0.0,
"赔付_整车延保": 0.0,
"赔付_安心包": 0.0,
"赔付_电池延保": 0.0,
"特殊情况": "",
}
if not text or pd.isna(text):
return result
s = str(text).strip()
if not s or s in ("/", "nan", "None"):
return result
# 无兜底
if "无兜底" in s or "合同还未签回" in s:
result["兜底类型"] = "无兜底"
return result
# 兜底类型判断
if "触客" in s:
result["兜底类型"] = "触客"
elif "交付" in s or "交车" in s:
result["兜底类型"] = "交付"
# 提取百分比目标(整车延保为主)
import re
# 比较符号:全角<>≤≥ + 半角<>=,注意 < 和 ≤ 都是"小于"语义
CMP = r'[<>≤≥<>=]'
pct_patterns = [
r'(?:延保|整车延保).*?触客.*?(?:渗透率|成交率).*?' + CMP + r'\s*(\d+)%?',
r'(?:延保|整车延保).*(?:渗透率|成交率).*?' + CMP + r'\s*(\d+)%?',
r'渗透率\s*' + CMP + r'\s*(\d+)%?',
r'触客\s*渗透率\s*' + CMP + r'\s*(\d+)%?',
r'触客\s*成交率\s*' + CMP + r'\s*(\d+)%?',
r'(?:' + CMP + r')\s*(\d{1,3})\s*%',
r'(?:不低于|不少于|大于|超过|高于)\s*(\d{1,3})\s*%',
r'(?:低于|少于|不足|小于)\s*(\d{1,3})\s*%',
r'(?:达到|达成|完成|兜底)\s*(\d{1,3})\s*%',
r'兜底[::]?\s*(\d{1,3})\s*%',
r'渗透率[≥≤]?\s*(\d{1,3})\s*%',
# 无比较符号:直接"触客60%"或"交付65%"
r'(?:触客|交付|交车)\s*[率成交]?\s*(\d{1,3})\s*%',
r'按\s*(\d{1,3})\s*%',
]
target_yb = 0.0
for pat in pct_patterns:
m = re.search(pat, s)
if m:
val = float(m.group(1))
if val > 0:
target_yb = val / 100.0
break
# 提取赔付单价
comp_patterns = [
r'[按每]?\s*(\d+)\s*元\s*[/台单]', # 按400元/台, 1000元/单
r'赔付\s*(\d+)\s*元', # 赔付1000元
r'补偿\s*(\d+)\s*元', # 补偿300元
r'赔付\s*金额\s*(\d+)', # 赔付金额2000
r'按\s*(\d+)\s*元', # 按1000元
r'每[单车台].*?(\d+)\s*元', # 每单1000元
r'(\d+)\s*元\s*[/台单]个]', # 1000元/台
]
comp = 0.0
for pat in comp_patterns:
m = re.search(pat, s)
if m:
comp = float(m.group(1))
break
result["需达标_整车延保"] = target_yb
result["赔付_整车延保"] = comp
# 特殊情况
specials = []
if "安心包专岗" in s:
specials.append("安心包专岗")
if "尚界" in s:
result["特殊情况"] = "尚界条款"
return result
@staticmethod
def build_sub_brand_report(file_path: str,
start_date: str = None,
end_date: str = None) -> str:
"""
构建鸿蒙子品牌分析报表。
读取子品牌Excel(含门店数据+主机厂数据+产值数据),
解析兜底条款,计算赔付金额,输出到模板。
"""
import shutil
import time
TEMPLATE_FILE = _find_latest_template("输出模板-鸿蒙子品牌-模板")
TEMPLATE_SHEET = "模板"
if not os.path.exists(TEMPLATE_FILE):
raise FileNotFoundError(f"子品牌模板文件不存在: {TEMPLATE_FILE}")
# 读取子品牌数据
raw_df = HarmonyAnalysisService.read_sub_brand_data(file_path)
if raw_df.empty:
raise ValueError("子品牌数据为空")
# 默认日期
if not start_date:
start_date = date.today().replace(day=1).strftime('%Y-%m-%d')
if not end_date:
end_date = date.today().strftime('%Y-%m-%d')
# 输出文件
output_dir = os.path.join("temp_uploads", "reports", date.today().strftime("%Y%m%d"))
os.makedirs(output_dir, exist_ok=True)
date_str = end_date.replace("-", "")
ts = time.strftime("%H%M%S")
output_filename = f"鸿蒙子品牌分析_{date_str}_{ts}.xlsx"
output_filename = ensure_unique_filename(output_dir, output_filename)
output_path = os.path.join(output_dir, output_filename)
shutil.copy2(TEMPLATE_FILE, output_path)
wb = load_workbook(output_path)
ws_template = wb[TEMPLATE_SHEET]
# 提取公式
formula_map, skip_external_cols = HarmonyAnalysisService._extract_formulas_from_template(ws_template)
# 复制模板sheet,隐藏原模板
ws = wb.copy_worksheet(ws_template)
sheet_name = f"鸿蒙子品牌({date_str})"
ws.title = sheet_name
ws_template.sheet_state = 'hidden'
HarmonyAnalysisService._clear_sheet_data(ws)
# DB查询产值数据(作为补充,优先使用文件中的产值数据)
store_names = [str(n) for n in raw_df["门店名"].tolist() if pd.notna(n)]
db_perf = HarmonyAnalysisService._query_harmony_store_performance(
store_names, start_date, end_date) if store_names else {}
# 构建适配 _write_data_rows 的 merged_df
merged_rows = []
for _, row in raw_df.iterrows():
store_name = str(row.get("门店名", ""))
parsed = HarmonyAnalysisService._parse_guarantee_text(row.get("兜底指标", ""))
merged_rows.append({
"门店名": store_name,
"品牌": str(row.get("品牌", "")),
"兜底指标": str(row.get("兜底指标", "")) if pd.notna(row.get("兜底指标")) else "",
"区域(省)": str(row.get("区域(省)", "")) if pd.notna(row.get("区域(省)")) else "",
"直营与否": str(row.get("直营与否", "")) if pd.notna(row.get("直营与否")) else "",
"区域运营": str(row.get("区域运营", "")) if pd.notna(row.get("区域运营")) else "",
"飞行督导": str(row.get("飞行督导", "")) if pd.notna(row.get("飞行督导")) else "",
"线上运营": str(row.get("线上运营", "")) if pd.notna(row.get("线上运营")) else "",
"特殊情况": parsed.get("特殊情况", ""),
"交付数": _safe_float(row.get("主机厂交付数", 0)), # 主机厂交付数
"触客数": _safe_float(row.get("触客数", 0)),
"整车延保成交数": _safe_float(row.get("整车延保成交数", 0)),
"安心包达成数量": _safe_float(row.get("安心包达成数量", 0)),
"电池延保成交数": _safe_float(row.get("电池延保成交数", 0)),
"兜底类型": parsed.get("兜底类型", "触客"),
"需达标转化率_整车延保": parsed.get("需达标_整车延保", 0),
"需达标转化率_安心包": parsed.get("需达标_安心包", 0),
"需达标转化率_电池延保": parsed.get("需达标_电池延保", 0),
"预计赔付金额_整车": parsed.get("赔付_整车延保", 0),
"预计赔付金额_安心包": parsed.get("赔付_安心包", 0),
"预计赔付金额_电池": parsed.get("赔付_电池延保", 0),
})
merged_df = pd.DataFrame(merged_rows)
logger.info(f"Sub-brand merged: {len(merged_df)} stores, db={len(db_perf)}")
# 为 db_perf 补充产值表交付数
for store_name, perf in db_perf.items():
# db_perf 中的 delivery 是产值表交付数,映射为产值交付数来源
pass # 已在后续写入逻辑中使用
# 写入数据
next_row = HarmonyAnalysisService._write_data_rows(
ws, merged_df, db_perf, formula_map, skip_external_cols,
start_date, end_date)
# 自动筛选
from openpyxl.utils import get_column_letter
last_col = get_column_letter(ws.max_column)
ws.auto_filter.ref = f"A2:{last_col}{next_row - 1}"
wb.save(output_path)
logger.info(f"Sub-brand report generated: {output_path}")
return output_path
@staticmethod @staticmethod
def _extract_formulas_from_template(ws): def _extract_formulas_from_template(ws):
formula_map = {} formula_map = {}
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>鸿蒙生态分析 - 问界门店运营数据分析平台</title> <title>鸿蒙生态分析 - 问界门店运营数据分析平台</title>
<link rel="stylesheet" href="./static/css/style.css"> <link rel="stylesheet" href="./static/css/style.css">
<script src="https://cdn.sheetjs.com/xlsx-0.20.1/package/dist/xlsx.full.min.js"></script>
<style> <style>
.analysis-layout { .analysis-layout {
display: flex; gap: 16px; height: calc(100vh - 160px); display: flex; gap: 16px; height: calc(100vh - 160px);
...@@ -119,6 +120,22 @@ ...@@ -119,6 +120,22 @@
color: white; border: none; border-radius: 4px; font-size: 14px; color: white; border: none; border-radius: 4px; font-size: 14px;
text-decoration: none; cursor: pointer; margin-top: 10px; text-decoration: none; cursor: pointer; margin-top: 10px;
} }
.hm-tab-nav {
display: flex; gap: 0; margin-bottom: 14px;
border-bottom: 2px solid #e8e8e8;
}
.hm-tab-btn {
padding: 8px 24px; border: none; background: none;
font-size: 14px; color: #666; cursor: pointer;
border-bottom: 2px solid transparent;
margin-bottom: -2px; transition: all 0.2s;
}
.hm-tab-btn:hover { color: #1890ff; }
.hm-tab-btn.active {
color: #1890ff; border-bottom-color: #1890ff;
font-weight: 600;
}
.hm-tab-content.active { display: block !important; }
@media (max-width: 900px) { @media (max-width: 900px) {
.analysis-layout { flex-direction: column; height: auto; } .analysis-layout { flex-direction: column; height: auto; }
.left-panel { width: 100%; min-width: 0; } .left-panel { width: 100%; min-width: 0; }
...@@ -144,6 +161,15 @@ ...@@ -144,6 +161,15 @@
<section id="content-area"> <section id="content-area">
<div class="card"> <div class="card">
<h2 id="content-title">鸿蒙生态分析</h2> <h2 id="content-title">鸿蒙生态分析</h2>
<!-- Tab 导航 -->
<div class="hm-tab-nav">
<button class="hm-tab-btn active" data-tab="harmony" onclick="switchTab('harmony')">鸿蒙生态分析</button>
<button class="hm-tab-btn" data-tab="sub-brand" onclick="switchTab('sub-brand')">鸿蒙子品牌分析</button>
</div>
<!-- ===== Tab: 鸿蒙生态分析 ===== -->
<div id="tab-harmony" class="hm-tab-content active">
<div id="content-body"> <div id="content-body">
<div class="analysis-layout"> <div class="analysis-layout">
...@@ -235,6 +261,65 @@ ...@@ -235,6 +261,65 @@
</div> </div>
</div> </div>
</div> </div>
<!-- ===== Tab: 鸿蒙子品牌分析 ===== -->
<div id="tab-sub-brand" class="hm-tab-content" style="display:none;">
<div id="sub-brand-content">
<div class="analysis-layout">
<div class="left-panel">
<div class="step-card active" id="sb-step-upload">
<div class="step-title">&#9312; 上传子品牌数据</div>
<div class="step-row">
<div class="step-upload-zone" id="sb-drop-zone" onclick="document.getElementById('sb-file-input').click()">
<input type="file" id="sb-file-input" style="display:none;" accept=".xlsx,.xls" onchange="onSubBrandFileChange()">
&#x1f4c1; <span id="sb-file-name">点击上传鸿蒙子品牌数据文件(含主机厂数据)</span>
</div>
</div>
<div class="step-date-row">
<input type="date" id="sb-start-date" title="开始日期">
<span style="font-size:12px;color:#999;">~</span>
<input type="date" id="sb-end-date" title="结束日期">
</div>
</div>
<div style="background: #e6f7ff; padding: 6px 14px; border-radius: 6px; border: 1px solid #91d5ff; display: flex; align-items: center; gap: 8px;">
<span style="font-size:13px; color:#1890ff;">&#x1f6c8;</span>
<span style="font-size:12px; color:#666;">上传含"鸿蒙子品牌"sheet的Excel文件,系统将自动解析门店数据、兜底条款,计算赔付金额。</span>
</div>
<div style="text-align:center; margin-top:4px;">
<button class="btn-generate" id="btn-generate-sb-report">
&#x1f680; 生成鸿蒙子品牌分析报表
</button>
<p style="font-size:11px;color:#999;margin-top:4px;">使用模板: 输出模板-鸿蒙子品牌-模板001.xlsx</p>
</div>
<div class="result-box" id="sb-analysis-result">
<h3 style="color:#52c41a;margin:0 0 6px;">&#x2705; 报表生成成功</h3>
<div style="font-size:12px;color:#666;margin-bottom:10px;" id="sb-analysis-result-info"></div>
<a class="btn-download" id="btn-download-sb-report" href="#">&#x1f4e5; 下载子品牌分析报表</a>
</div>
<div class="result-box" id="sb-analysis-error">
<h3 style="color:#f5222d;margin:0 0 6px;">&#x274c; 报表生成失败</h3>
<p style="margin:0;color:#666;font-size:12px;" id="sb-analysis-error-msg"></p>
</div>
</div>
<div class="right-panel">
<div class="right-panel-header">
<span>&#x1f4ca; 子品牌数据预览</span>
</div>
<div class="right-panel-body" id="sb-preview-body">
<div class="right-panel-empty" id="sb-preview-empty">
请上传鸿蒙子品牌数据文件,解析后将在此处预览
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section> </section>
</main> </main>
...@@ -394,6 +479,147 @@ ...@@ -394,6 +479,147 @@
} }
}); });
// ========== Tab 切换 ==========
window.switchTab = function(tabName) {
document.querySelectorAll('.hm-tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.hm-tab-content').forEach(c => c.classList.remove('active'));
const btn = document.querySelector(`.hm-tab-btn[data-tab="${tabName}"]`);
if (btn) btn.classList.add('active');
const tab = document.getElementById(`tab-${tabName}`);
if (tab) { tab.classList.add('active'); tab.style.display = 'block'; }
document.getElementById('content-title').textContent =
tabName === 'sub-brand' ? '鸿蒙子品牌分析' : '鸿蒙生态分析';
};
// ========== 子品牌: 文件上传 ==========
window.onSubBrandFileChange = async function() {
const input = document.getElementById('sb-file-input');
if (!input.files.length) return;
const file = input.files[0];
const name = file.name;
document.getElementById('sb-file-name').textContent = '\u2705 ' + name;
document.getElementById('sb-drop-zone').classList.add('has-file');
// 服务端预览
const formData = new FormData();
formData.append('data_file', file);
try {
document.getElementById('sb-preview-body').innerHTML =
'<div class="right-panel-empty">正在解析数据...</div>';
const res = await fetch(window.API_BASE + '/harmony/sub-brand/upload', { method: 'POST', body: formData });
const data = await res.json();
if (data.status === 'success') {
// 用前端读取方式预览
const reader = new FileReader();
reader.onload = function(e) {
try {
const wb = XLSX.read(e.target.result, {type: 'array'});
const sheetName = wb.SheetNames.find(s => s.includes('子品牌')) || wb.SheetNames[0];
const ws = wb.Sheets[sheetName];
const rows = XLSX.utils.sheet_to_json(ws, {header: 1, defval: ''});
// skip header & subtotals (rows 0-6)
const dataRows = rows.slice(7).filter(r => r[0] && String(r[0]).trim());
const headers = ['门店','品牌','区域','直营','主机厂交付','产值交付','触客数','整车延保成交','安心包','电池','兜底指标'];
const cols = dataRows.length > 0 ? dataRows[0].length : 0;
let html = '<table class="preview-table"><thead><tr><th>#</th>';
headers.slice(0, 11).forEach(h => html += '<th>' + escapeHtml(h) + '</th>');
html += '</tr></thead><tbody>';
dataRows.slice(0, 100).forEach((row, i) => {
html += '<tr><td style="text-align:center;color:#999;">' + (i+1) + '</td>';
html += '<td>' + escapeHtml(String(row[0]||'')) + '</td>'; // 门店
html += '<td>' + escapeHtml(String(row[7]||'')) + '</td>'; // 品牌
html += '<td>' + escapeHtml(String(row[2]||'')) + '</td>'; // 区域
html += '<td>' + escapeHtml(String(row[3]||'')) + '</td>'; // 直营
html += '<td>' + escapeHtml(String(row[8]||'')) + '</td>'; // 主机厂交付
html += '<td>' + escapeHtml(String(row[9]||'')) + '</td>'; // 产值交付
html += '<td>' + escapeHtml(String(row[10]||'')) + '</td>'; // 触客数
html += '<td>' + escapeHtml(String(row[12]||'')) + '</td>'; // 延保成交
html += '<td>' + escapeHtml(String(row[15]||'')) + '</td>'; // 安心包
html += '<td>' + escapeHtml(String(row[17]||'')) + '</td>'; // 电池
html += '<td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;">' + escapeHtml(String(row[1]||'')) + '</td>'; // 兜底指标
html += '</tr>';
});
html += '</tbody></table>';
document.getElementById('sb-preview-body').innerHTML = html;
} catch(ex) {
document.getElementById('sb-preview-body').innerHTML =
'<div class="right-panel-empty" style="color:#f5222d;">解析预览失败: ' + ex.message + '</div>';
}
};
reader.readAsArrayBuffer(file);
}
} catch(e) {
console.error('子品牌上传失败:', e);
}
};
// ========== 子品牌: 生成报表 ==========
(function() {
const btnSb = document.getElementById('btn-generate-sb-report');
if (!btnSb) return;
btnSb.addEventListener('click', async () => {
document.getElementById('sb-analysis-result').className = 'result-box';
document.getElementById('sb-analysis-error').className = 'result-box';
const input = document.getElementById('sb-file-input');
if (!input || !input.files.length) {
document.getElementById('sb-analysis-error').className = 'result-box error';
document.getElementById('sb-analysis-error-msg').textContent = '请先上传子品牌数据文件';
return;
}
btnSb.disabled = true;
btnSb.textContent = '\u23f3 正在生成报表...';
try {
// 先上传
const uploadForm = new FormData();
uploadForm.append('data_file', input.files[0]);
const sd = document.getElementById('sb-start-date').value;
const ed = document.getElementById('sb-end-date').value;
if (sd) uploadForm.append('start_date', sd);
if (ed) uploadForm.append('end_date', ed);
const upRes = await fetch(window.API_BASE + '/harmony/sub-brand/upload', { method: 'POST', body: uploadForm });
const upData = await upRes.json();
if (upData.status !== 'success') throw new Error(upData.detail || '上传失败');
btnSb.textContent = '\u23f3 正在分析计算...';
// 再生成
const genForm = new FormData();
if (sd) genForm.append('start_date', sd);
if (ed) genForm.append('end_date', ed);
const genRes = await fetch(window.API_BASE + '/harmony/sub-brand/generate', { method: 'POST', body: genForm });
const genData = await genRes.json();
if (genData.status === 'success') {
document.getElementById('sb-analysis-result').className = 'result-box success';
document.getElementById('sb-analysis-result-info').innerHTML =
'文件位置: <strong>' + genData.file_path + '</strong>';
document.getElementById('btn-download-sb-report').href = genData.download_url;
} else {
throw new Error(genData.detail || '报表生成失败');
}
} catch (err) {
console.error('子品牌分析失败:', err);
document.getElementById('sb-analysis-error').className = 'result-box error';
document.getElementById('sb-analysis-error-msg').textContent = err.message || '未知错误';
} finally {
btnSb.disabled = false;
btnSb.textContent = '\u{1f680} 生成鸿蒙子品牌分析报表';
}
});
// 子品牌设置默认日期
const fmt = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
const now = new Date();
const yesterday = new Date(now); yesterday.setDate(yesterday.getDate()-1);
const sbStart = document.getElementById('sb-start-date');
const sbEnd = document.getElementById('sb-end-date');
if (sbStart && !sbStart.value) sbStart.value = fmt(new Date(now.getFullYear(), now.getMonth(), 1));
if (sbEnd && !sbEnd.value) sbEnd.value = fmt(yesterday);
})();
// ========== 辅助函数 ========== // ========== 辅助函数 ==========
function highlightStep(cardId) { function highlightStep(cardId) {
......
...@@ -21,6 +21,7 @@ import base64 ...@@ -21,6 +21,7 @@ import base64
import asyncio import asyncio
import argparse import argparse
import logging import logging
import numpy as np
from pathlib import Path from pathlib import Path
import httpx import httpx
...@@ -340,13 +341,21 @@ def _extract_json(text: str) -> str: ...@@ -340,13 +341,21 @@ def _extract_json(text: str) -> str:
text = text.strip() text = text.strip()
# 去除 Markdown ```json ... ``` 或 ``` ... ``` 包裹 # 去除 Markdown ```json ... ``` 或 ``` ... ``` 包裹
if text.startswith("```"): if "```" in text:
first_newline = text.find("\n") # 寻找第一个 ``` 和最后一个 ```
start_idx = text.find("```")
# 跳过开头标记,如 ```json
first_newline = text.find("\n", start_idx)
if first_newline != -1: if first_newline != -1:
text = text[first_newline + 1:] start_pos = first_newline + 1
else: else:
text = text[3:] start_pos = start_idx + 3
text = re.sub(r"\n?```\s*$", "", text).strip()
end_idx = text.rfind("```")
if end_idx > start_pos:
text = text[start_pos:end_idx].strip()
else:
text = text[start_pos:].strip()
# 如果 LLM 在 JSON 前后加了说明文字,尝试提取第一个 JSON 对象 # 如果 LLM 在 JSON 前后加了说明文字,尝试提取第一个 JSON 对象
brace_start = text.find("{") brace_start = text.find("{")
...@@ -354,12 +363,36 @@ def _extract_json(text: str) -> str: ...@@ -354,12 +363,36 @@ def _extract_json(text: str) -> str:
if brace_start != -1 and brace_end != -1 and brace_end > brace_start: if brace_start != -1 and brace_end != -1 and brace_end > brace_start:
text = text[brace_start:brace_end + 1] text = text[brace_start:brace_end + 1]
# 容错处理:处理常见的 LLM JSON 错误
# 1. 移除多余的逗号 (trailing commas)
text = re.sub(r',\s*([}\]])', r'\1', text)
# 2. 移除单行注释 // ...
text = re.sub(r'//.*$', '', text, flags=re.MULTILINE)
# 3. 处理可能的截断问题:如果最后一个字符不是 } 或 ],尝试补齐
# 但这比较危险,先不自动补齐,而是打印更多调试信息
return text return text
def _get_http_client(no_proxy: bool = False) -> httpx.AsyncClient:
"""创建 httpx 客户端,处理代理逻辑"""
client_kwargs = {"timeout": 180.0}
if not no_proxy:
proxy_url = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
if proxy_url:
client_kwargs["proxy"] = proxy_url
# print(f" [代理] {proxy_url}") # 调试用,实际调用处会打印
return httpx.AsyncClient(**client_kwargs)
async def _call_vision_llm(image_path: str, max_size: int = DEFAULT_MAX_SIZE, async def _call_vision_llm(image_path: str, max_size: int = DEFAULT_MAX_SIZE,
quality: int = DEFAULT_QUALITY, quality: int = DEFAULT_QUALITY,
api_url: str = "", api_key: str = "", model: str = "") -> dict: api_url: str = "", api_key: str = "", model: str = "",
no_proxy: bool = False) -> dict:
""" """
调用 VL 模型提取图片中的表格为 JSON。 调用 VL 模型提取图片中的表格为 JSON。
自动缩放图片以满足 API 长度限制。 自动缩放图片以满足 API 长度限制。
...@@ -394,15 +427,13 @@ JSON 格式: ...@@ -394,15 +427,13 @@ JSON 格式:
} }
仅返回 JSON,不要 Markdown 代码块。""" 仅返回 JSON,不要 Markdown 代码块。"""
try: async def _do_request(use_proxy: bool):
client_kwargs = {"timeout": 180.0} proxy_url = (os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")) if use_proxy else None
proxy_url = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
if proxy_url: if proxy_url:
client_kwargs["proxy"] = proxy_url
print(f" [代理] {proxy_url}") print(f" [代理] {proxy_url}")
async with httpx.AsyncClient(**client_kwargs) as client: async with _get_http_client(no_proxy=not use_proxy) as client:
response = await client.post( return await client.post(
api_url, api_url,
headers={ headers={
"Authorization": f"Bearer {api_key}", "Authorization": f"Bearer {api_key}",
...@@ -423,9 +454,18 @@ JSON 格式: ...@@ -423,9 +454,18 @@ JSON 格式:
"temperature": 0.1, "temperature": 0.1,
"max_tokens": 8192, "max_tokens": 8192,
}, },
timeout=1800.0,
) )
try:
try:
response = await _do_request(use_proxy=not no_proxy)
except (httpx.ConnectError, httpx.ProxyError) as e:
if not no_proxy and (os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")):
print(f" [重试] 代理连接失败,尝试直接连接... ({e})")
response = await _do_request(use_proxy=False)
else:
raise
if response.status_code != 200: if response.status_code != 200:
logger.error(f"Vision LLM API Error: {response.status_code} - {response.text}") logger.error(f"Vision LLM API Error: {response.status_code} - {response.text}")
raise RuntimeError(f"API 请求失败: {response.status_code}") raise RuntimeError(f"API 请求失败: {response.status_code}")
...@@ -436,28 +476,101 @@ JSON 格式: ...@@ -436,28 +476,101 @@ JSON 格式:
return json.loads(content) return json.loads(content)
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
logger.error(f"Failed to parse LLM response as JSON. Raw content:\n{content}") logger.error(f"Failed to parse LLM response as JSON. Error: {e}")
# 打印末尾 500 个字符,帮助判断是否截断
tail = content[-500:] if len(content) > 500 else content
logger.error(f"Response Tail (last 500 chars):\n...{tail}")
raise RuntimeError(f"LLM 返回内容不是合法 JSON: {e}") raise RuntimeError(f"LLM 返回内容不是合法 JSON: {e}")
except Exception as e: except Exception as e:
logger.error(f"Failed to call vision LLM: {e}") logger.error(f"Failed to call vision LLM: {e}")
raise raise
def _split_image(image_path: str, n_chunks: int, max_size: int = DEFAULT_MAX_SIZE, def _find_split_points(image_path: str, max_chunk_height: int = 1500) -> list:
"""
智能寻找纵向切分点:
1. 优先寻找全黑或全白的横向分割线。
2. 其次寻找像素变化较小的行(可能是表格边框)。
"""
img = Image.open(image_path).convert("L")
w, h = img.size
if h <= max_chunk_height:
return [0, h]
# 将图像转换为 numpy 数组以便快速处理
data = np.array(img)
# 计算每一行的平均亮度
row_means = np.mean(data, axis=1)
# 计算每一行像素的标准差(反映该行是否包含文字/线条)
row_stds = np.std(data, axis=1)
split_points = [0]
current_y = 0
while current_y + max_chunk_height < h:
# 在目标切分点附近的窗口内寻找最佳切分位置
search_start = current_y + int(max_chunk_height * 0.8)
search_end = min(h, current_y + int(max_chunk_height * 1.2))
# 寻找窗口内 std 最小的行(最可能是空白或直线)
window_stds = row_stds[search_start:search_end]
if len(window_stds) == 0:
break
best_in_window = np.argmin(window_stds)
best_y = search_start + best_in_window
split_points.append(int(best_y))
current_y = best_y
if split_points[-1] < h:
split_points.append(h)
img.close()
return split_points
def _split_image(image_path: str, n_chunks: int = 0, max_size: int = DEFAULT_MAX_SIZE,
quality: int = DEFAULT_QUALITY) -> list: quality: int = DEFAULT_QUALITY) -> list:
""" """
将长图纵向切成 n_chunks 段,每段有 15% 重叠以确保行不被截断。 将长图纵向切分。
返回 [(data_uri, mime_type, chunk_index), ...] 如果 n_chunks > 0, 则平均切分(带重叠)。
如果 n_chunks == 0, 则根据图片高度自动智能切分。
返回 [(data_uri, chunk_index, y1, y2, size_kb), ...]
""" """
img = Image.open(image_path) img = Image.open(image_path)
w, h = img.size w, h = img.size
# 确定切分点
if n_chunks > 0:
# 平均切分逻辑
chunk_h = h // n_chunks chunk_h = h // n_chunks
overlap = int(chunk_h * 0.15) overlap = int(chunk_h * 0.15)
y_ranges = []
chunks = []
for i in range(n_chunks): for i in range(n_chunks):
y1 = max(0, i * chunk_h - (overlap if i > 0 else 0)) y1 = max(0, i * chunk_h - (overlap if i > 0 else 0))
y2 = min(h, (i + 1) * chunk_h + (overlap if i < n_chunks - 1 else 0)) y2 = min(h, (i + 1) * chunk_h + (overlap if i < n_chunks - 1 else 0))
y_ranges.append((y1, y2))
else:
# 自动智能切分逻辑
# 设定单片建议高度(针对 VL 模型的 token 限制优化)
target_h = 1800 if h > 2000 else h
if h <= target_h:
y_ranges = [(0, h)]
else:
points = _find_split_points(image_path, max_chunk_height=target_h)
y_ranges = []
# 增加 50px 的重叠以防万一
overlap = 50
for i in range(len(points) - 1):
y1 = max(0, points[i] - (overlap if i > 0 else 0))
y2 = min(h, points[i+1] + (overlap if i < len(points) - 2 else 0))
y_ranges.append((y1, y2))
n_actual = len(y_ranges)
chunks = []
for i, (y1, y2) in enumerate(y_ranges):
chunk_img = img.crop((0, y1, w, y2)) chunk_img = img.crop((0, y1, w, y2))
if max(chunk_img.size) > max_size: if max(chunk_img.size) > max_size:
...@@ -481,7 +594,7 @@ def _split_image(image_path: str, n_chunks: int, max_size: int = DEFAULT_MAX_SIZ ...@@ -481,7 +594,7 @@ def _split_image(image_path: str, n_chunks: int, max_size: int = DEFAULT_MAX_SIZ
size_kb = len(buf.getvalue()) / 1024 size_kb = len(buf.getvalue()) / 1024
data_uri = f"data:image/jpeg;base64,{encoded}" data_uri = f"data:image/jpeg;base64,{encoded}"
chunks.append((data_uri, i, y1, y2, size_kb)) chunks.append((data_uri, i, y1, y2, size_kb))
print(f" [分片 {i + 1}/{n_chunks}] y={y1}-{y2}, base64={size_kb:.0f}KB") print(f" [分片 {i + 1}/{n_actual}] y={y1}-{y2}, base64={size_kb:.0f}KB")
img.close() img.close()
return chunks return chunks
...@@ -490,7 +603,8 @@ def _split_image(image_path: str, n_chunks: int, max_size: int = DEFAULT_MAX_SIZ ...@@ -490,7 +603,8 @@ def _split_image(image_path: str, n_chunks: int, max_size: int = DEFAULT_MAX_SIZ
async def _call_vision_llm_split(image_path: str, n_chunks: int, async def _call_vision_llm_split(image_path: str, n_chunks: int,
max_size: int = DEFAULT_MAX_SIZE, max_size: int = DEFAULT_MAX_SIZE,
quality: int = DEFAULT_QUALITY, quality: int = DEFAULT_QUALITY,
api_url: str = "", api_key: str = "", model: str = "") -> dict: api_url: str = "", api_key: str = "", model: str = "",
no_proxy: bool = False) -> dict:
""" """
分片模式:将长图切成 n_chunks 段分别识别,合并结果(去重重叠行)。 分片模式:将长图切成 n_chunks 段分别识别,合并结果(去重重叠行)。
""" """
...@@ -519,13 +633,8 @@ JSON 格式: ...@@ -519,13 +633,8 @@ JSON 格式:
all_headers = [] all_headers = []
all_rows = [] all_rows = []
async with httpx.AsyncClient(timeout=180.0) as client: async def _do_chunk_request(client, data_uri, chunk_prompt):
for idx, (data_uri, chunk_i, y1, y2, size_kb) in enumerate(chunks): return await client.post(
is_first = (idx == 0)
chunk_prompt = prompt + ("\n注意:这是图片的第一部分,请提取表头。" if is_first else "\n注意:这是图片的后续部分,不需要再提取表头,只提取数据行。")
print(f" [识别 {idx + 1}/{n_chunks}] 发送请求...")
response = await client.post(
api_url, api_url,
headers={ headers={
"Authorization": f"Bearer {api_key}", "Authorization": f"Bearer {api_key}",
...@@ -548,21 +657,43 @@ JSON 格式: ...@@ -548,21 +657,43 @@ JSON 格式:
}, },
) )
async def _process_chunks(use_proxy: bool):
proxy_url = (os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")) if use_proxy else None
if proxy_url:
print(f" [代理] {proxy_url}")
local_headers = []
local_rows = []
async with _get_http_client(no_proxy=not use_proxy) as client:
n_actual = len(chunks)
for idx, (data_uri, chunk_i, y1, y2, size_kb) in enumerate(chunks):
is_first = (idx == 0)
chunk_prompt = prompt + ("\n注意:这是图片的第一部分,请提取表头。" if is_first else "\n注意:这是图片的后续部分,不需要再提取表头,只提取数据行。")
print(f" [识别 {idx + 1}/{n_actual}] 发送请求...")
response = await _do_chunk_request(client, data_uri, chunk_prompt)
if response.status_code != 200: if response.status_code != 200:
logger.error(f"Chunk {idx} API Error: {response.status_code} - {response.text}") logger.error(f"Chunk {idx} API Error: {response.status_code} - {response.text}")
raise RuntimeError(f"分片 {idx} API 请求失败: {response.status_code}") raise RuntimeError(f"分片 {idx} API 请求失败: {response.status_code}")
result = response.json() content = response.json()["choices"][0]["message"]["content"]
content = result["choices"][0]["message"]["content"] try:
content = _extract_json(content) content = _extract_json(content)
chunk_data = json.loads(content) chunk_data = json.loads(content)
except json.JSONDecodeError as e:
logger.error(f"Failed to parse Chunk {idx} response as JSON. Error: {e}")
tail = content[-500:] if len(content) > 500 else content
logger.error(f"Response Tail:\n...{tail}")
raise RuntimeError(f"分片 {idx} 返回内容不是合法 JSON: {e}")
if is_first and chunk_data.get("has_header", True): if is_first and chunk_data.get("has_header", True):
all_headers = chunk_data.get("headers", []) local_headers = chunk_data.get("headers", [])
chunk_rows = chunk_data.get("rows", []) chunk_rows = chunk_data.get("rows", [])
if idx > 0 and all_rows and chunk_rows: if idx > 0 and local_rows and chunk_rows:
last_row = tuple(str(v) for v in all_rows[-1]) last_row = tuple(str(v) for v in local_rows[-1])
skip = 0 skip = 0
for r in chunk_rows: for r in chunk_rows:
if tuple(str(v) for v in r) == last_row: if tuple(str(v) for v in r) == last_row:
...@@ -573,9 +704,20 @@ JSON 格式: ...@@ -573,9 +704,20 @@ JSON 格式:
print(f" [去重] 分片 {idx + 1} 跳过前 {skip} 行") print(f" [去重] 分片 {idx + 1} 跳过前 {skip} 行")
chunk_rows = chunk_rows[skip:] chunk_rows = chunk_rows[skip:]
all_rows.extend(chunk_rows) local_rows.extend(chunk_rows)
print(f" [分片 {idx + 1}] 提取 {len(chunk_rows)} 行") print(f" [分片 {idx + 1}] 提取 {len(chunk_rows)} 行")
return local_headers, local_rows
try:
all_headers, all_rows = await _process_chunks(use_proxy=not no_proxy)
except (httpx.ConnectError, httpx.ProxyError) as e:
if not no_proxy and (os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")):
print(f" [重试] 代理连接失败,尝试直接连接... ({e})")
all_headers, all_rows = await _process_chunks(use_proxy=False)
else:
raise
return {"headers": all_headers, "rows": all_rows} return {"headers": all_headers, "rows": all_rows}
...@@ -618,6 +760,8 @@ def main(): ...@@ -618,6 +760,8 @@ def main():
help="LLM 模式:API Key。不指定则使用 LLM_QWEN_API_KEY") help="LLM 模式:API Key。不指定则使用 LLM_QWEN_API_KEY")
parser.add_argument("--model", "-m", default="", parser.add_argument("--model", "-m", default="",
help="LLM 模式:模型名称。不指定则使用 LLM_QWEN_VISION_MODEL") help="LLM 模式:模型名称。不指定则使用 LLM_QWEN_VISION_MODEL")
parser.add_argument("--no-proxy", action="store_true",
help="LLM 模式:禁用环境变量中的 HTTP/HTTPS 代理")
args = parser.parse_args() args = parser.parse_args()
output_path = args.output or str(Path(args.image).with_suffix(".xlsx")) output_path = args.output or str(Path(args.image).with_suffix(".xlsx"))
...@@ -633,7 +777,9 @@ def main(): ...@@ -633,7 +777,9 @@ def main():
if settings.LLM_QWEN_API_KEY: if settings.LLM_QWEN_API_KEY:
print(f"[!] PaddleOCR 识别失败: {e}") print(f"[!] PaddleOCR 识别失败: {e}")
print(f"[*] 自动切换到 LLM 引擎尝试识别...") print(f"[*] 自动切换到 LLM 引擎尝试识别...")
table_data = asyncio.run(_call_vision_llm(args.image)) table_data = asyncio.run(_call_vision_llm(
args.image, no_proxy=args.no_proxy
))
rows_count = len(table_data.get("rows", [])) rows_count = len(table_data.get("rows", []))
_write_table_to_excel(table_data, output_path) _write_table_to_excel(table_data, output_path)
print(f"[+] 已保存: {output_path}\n 模型: {settings.LLM_QWEN_VISION_MODEL}\n 行数: {rows_count}") print(f"[+] 已保存: {output_path}\n 模型: {settings.LLM_QWEN_VISION_MODEL}\n 行数: {rows_count}")
...@@ -650,16 +796,26 @@ def main(): ...@@ -650,16 +796,26 @@ def main():
if api_url: if api_url:
print(f"[*] API: {api_url}") print(f"[*] API: {api_url}")
# 自动判断是否需要切分
img = Image.open(args.image)
height = img.size[1]
img.close()
# 如果用户手动指定了分段,或者图片太长(高度 > 2000),则进入切分模式
if args.split > 0 or height > 2000:
if args.split > 0: if args.split > 0:
print(f"[*] 分片模式:{args.split} 段") print(f"[*] 分片模式:手动指定 {args.split} 段")
else:
print(f"[*] 分片模式:图片高度 {height}px,自动智能切分")
table_data = asyncio.run(_call_vision_llm_split( table_data = asyncio.run(_call_vision_llm_split(
args.image, args.split, max_size=args.max_size, quality=args.quality, args.image, args.split, max_size=args.max_size, quality=args.quality,
api_url=api_url, api_key=api_key, model=model, api_url=api_url, api_key=api_key, model=model, no_proxy=args.no_proxy
)) ))
else: else:
table_data = asyncio.run(_call_vision_llm( table_data = asyncio.run(_call_vision_llm(
args.image, max_size=args.max_size, quality=args.quality, args.image, max_size=args.max_size, quality=args.quality,
api_url=api_url, api_key=api_key, model=model, api_url=api_url, api_key=api_key, model=model, no_proxy=args.no_proxy
)) ))
rows_count = len(table_data.get("rows", [])) rows_count = len(table_data.get("rows", []))
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!