Commit 6002b83e by 江名洋

fix(模板): 更新问界模板001

1 parent 1899a49f
...@@ -38,3 +38,4 @@ Thumbs.db ...@@ -38,3 +38,4 @@ Thumbs.db
# Jupyter # Jupyter
.ipynb_checkpoints/ .ipynb_checkpoints/
/.paddlex_models
...@@ -26,10 +26,25 @@ import logging ...@@ -26,10 +26,25 @@ import logging
logger = logging.getLogger("app.api") logger = logging.getLogger("app.api")
router = APIRouter() router = APIRouter()
# 临时文件存放目录 # 统一上传基础目录,所有文件按日期目录分级存放
UPLOAD_DIR = "temp_uploads" UPLOAD_BASE = "temp_uploads"
if not os.path.exists(UPLOAD_DIR): os.makedirs(UPLOAD_BASE, exist_ok=True)
os.makedirs(UPLOAD_DIR)
def _date_path(filename: str, category: str = "") -> str:
"""生成按日期分级的文件路径: temp_uploads/[category/]YYYYMMDD/filename"""
today = datetime.now().strftime("%Y%m%d")
target_dir = os.path.join(UPLOAD_BASE, category, today) if category else os.path.join(UPLOAD_BASE, today)
os.makedirs(target_dir, exist_ok=True)
return os.path.join(target_dir, filename)
def _find_file(filename: str) -> Optional[str]:
"""在 temp_uploads 下递归查找指定文件名,返回完整路径或 None"""
for root, _dirs, files in os.walk(UPLOAD_BASE):
if filename in files:
return os.path.join(root, filename)
return None
XLSX_DIR = os.path.join("app", "templates", "xlsx") XLSX_DIR = os.path.join("app", "templates", "xlsx")
...@@ -45,7 +60,7 @@ async def upload_data( ...@@ -45,7 +60,7 @@ async def upload_data(
# 记录接收到的参数,方便调试 422 错误 # 记录接收到的参数,方便调试 422 错误
logger.info(f"Upload request received: filename={file.filename}, table_name={table_name}, upload_type={upload_type}, tag={version_tag}") logger.info(f"Upload request received: filename={file.filename}, table_name={table_name}, upload_type={upload_type}, tag={version_tag}")
file_path = os.path.join(UPLOAD_DIR, file.filename) file_path = _date_path(file.filename)
try: try:
# 1. 保存临时文件 # 1. 保存临时文件
with open(file_path, "wb") as buffer: with open(file_path, "wb") as buffer:
...@@ -340,7 +355,7 @@ async def analysis_upload( ...@@ -340,7 +355,7 @@ async def analysis_upload(
result = {"status": "success", "messages": []} result = {"status": "success", "messages": []}
if store_file and store_file.filename: if store_file and store_file.filename:
file_path = os.path.join(UPLOAD_DIR, f"analysis_store_{store_file.filename}") file_path = _date_path(f"analysis_store_{store_file.filename}", category="analysis")
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(store_file.file, f) shutil.copyfileobj(store_file.file, f)
global _analysis_store_file global _analysis_store_file
...@@ -350,7 +365,7 @@ async def analysis_upload( ...@@ -350,7 +365,7 @@ async def analysis_upload(
def _save_factory(upload_file, prefix, global_var_name): def _save_factory(upload_file, prefix, global_var_name):
if not upload_file or not upload_file.filename: if not upload_file or not upload_file.filename:
return None return None
file_path = os.path.join(UPLOAD_DIR, f"analysis_{prefix}_{upload_file.filename}") file_path = _date_path(f"analysis_{prefix}_{upload_file.filename}", category="analysis")
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(upload_file.file, f) shutil.copyfileobj(upload_file.file, f)
try: try:
...@@ -386,19 +401,20 @@ async def analysis_upload( ...@@ -386,19 +401,20 @@ async def analysis_upload(
@router.post("/analysis/save-batch") @router.post("/analysis/save-batch")
async def analysis_save_batch( async def analysis_save_batch(
file_type: str = Form(...), # "store", "ecology", "nature" file_type: str = Form(...), # "store", "ecology", "nature", "factory"
file: UploadFile = File(...), file: UploadFile = File(...),
period_start: str = Form(""), period_start: str = Form(""),
period_end: str = Form(""), period_end: str = Form(""),
period_type: str = Form(""), # ecology / nature,仅 oem 使用 period_type: str = Form(""), # ecology / nature,仅 oem 使用
brand: str = Form("问界"),
): ):
"""将分析页面上传的文件保存为历史批次,便于下次复用""" """将分析页面上传的文件保存为历史批次,便于下次复用"""
if file_type not in ("store", "ecology", "nature"): if file_type not in ("store", "ecology", "nature", "factory"):
raise HTTPException(status_code=400, detail="file_type 仅支持 store/ecology/nature") raise HTTPException(status_code=400, detail="file_type 仅支持 store/ecology/nature/factory")
if not file.filename: if not file.filename:
raise HTTPException(status_code=400, detail="请选择文件") raise HTTPException(status_code=400, detail="请选择文件")
file_path = os.path.join(UPLOAD_DIR, f"_save_batch_{file.filename}") file_path = _date_path(f"_save_batch_{file.filename}", category="batch")
try: try:
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(file.file, f) shutil.copyfileobj(file.file, f)
...@@ -410,7 +426,7 @@ async def analysis_save_batch( ...@@ -410,7 +426,7 @@ async def analysis_save_batch(
result = import_store_guarantee( result = import_store_guarantee(
file_path=file_path, file_path=file_path,
original_filename=file.filename, original_filename=file.filename,
brand="问界", brand=brand,
data_period_start=today, data_period_start=today,
data_period_end=today, data_period_end=today,
file_size=file_size, file_size=file_size,
...@@ -421,7 +437,7 @@ async def analysis_save_batch( ...@@ -421,7 +437,7 @@ async def analysis_save_batch(
result = import_oem_delivery( result = import_oem_delivery(
file_path=file_path, file_path=file_path,
original_filename=file.filename, original_filename=file.filename,
brand="问界", brand=brand,
data_period_start=period_start or "", data_period_start=period_start or "",
data_period_end=period_end or "", data_period_end=period_end or "",
period_type=pt, period_type=pt,
...@@ -515,10 +531,9 @@ async def analysis_generate( ...@@ -515,10 +531,9 @@ async def analysis_generate(
@router.get("/analysis/download") @router.get("/analysis/download")
async def analysis_download(file: str = Query(None)): async def analysis_download(file: str = Query(None)):
"""下载生成的分析报表,支持指定文件名""" """下载生成的分析报表,支持指定文件名"""
output_dir = "temp_uploads"
if file: if file:
file_path = os.path.join(output_dir, file) file_path = _find_file(file)
if not os.path.exists(file_path): if not file_path:
raise HTTPException(status_code=404, detail="指定的报表文件不存在") raise HTTPException(status_code=404, detail="指定的报表文件不存在")
return FileResponse( return FileResponse(
file_path, filename=file, file_path, filename=file,
...@@ -527,14 +542,15 @@ async def analysis_download(file: str = Query(None)): ...@@ -527,14 +542,15 @@ async def analysis_download(file: str = Query(None)):
# 无指定时返回最新文件 # 无指定时返回最新文件
output_files = sorted( output_files = sorted(
[f for f in os.listdir(output_dir) if f.startswith("问界生态系数分析") and f.endswith(".xlsx")], [os.path.join(root, f) for root, _ds, fs in os.walk(UPLOAD_BASE)
key=lambda f: os.path.getmtime(os.path.join(output_dir, f)), for f in fs if f.startswith("问界生态系数分析") and f.endswith(".xlsx")],
key=lambda f: os.path.getmtime(f),
reverse=True reverse=True
) )
if not output_files: if not output_files:
raise HTTPException(status_code=404, detail="未找到分析报表,请先生成") raise HTTPException(status_code=404, detail="未找到分析报表,请先生成")
file_path = os.path.join(output_dir, output_files[0]) file_path = output_files[0]
return FileResponse( return FileResponse(
file_path, file_path,
filename=output_files[0], filename=output_files[0],
...@@ -550,7 +566,7 @@ async def analysis_preview_file( ...@@ -550,7 +566,7 @@ async def analysis_preview_file(
file: UploadFile = File(...), file: UploadFile = File(...),
): ):
"""上传分析文件并返回解析后的预览数据""" """上传分析文件并返回解析后的预览数据"""
file_path = os.path.join(UPLOAD_DIR, f"_preview_{file.filename}") file_path = _date_path(f"_preview_{file.filename}")
try: try:
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(file.file, f) shutil.copyfileobj(file.file, f)
...@@ -682,14 +698,14 @@ async def harmony_upload( ...@@ -682,14 +698,14 @@ async def harmony_upload(
result = {"status": "success", "messages": []} result = {"status": "success", "messages": []}
if store_file and store_file.filename: if store_file and store_file.filename:
file_path = os.path.join(UPLOAD_DIR, f"harmony_store_{store_file.filename}") file_path = _date_path(f"harmony_store_{store_file.filename}", category="harmony")
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(store_file.file, f) shutil.copyfileobj(store_file.file, f)
_harmony_store_file = file_path _harmony_store_file = file_path
result["messages"].append(f"门店兜底配置已上传: {store_file.filename}") result["messages"].append(f"门店兜底配置已上传: {store_file.filename}")
if factory_file and factory_file.filename: if factory_file and factory_file.filename:
file_path = os.path.join(UPLOAD_DIR, f"harmony_factory_{factory_file.filename}") file_path = _date_path(f"harmony_factory_{factory_file.filename}", category="harmony")
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(factory_file.file, f) shutil.copyfileobj(factory_file.file, f)
_harmony_factory_file = file_path _harmony_factory_file = file_path
...@@ -705,24 +721,32 @@ async def harmony_upload( ...@@ -705,24 +721,32 @@ async def harmony_upload(
async def harmony_generate( async def harmony_generate(
start_date: str = Form(None), start_date: str = Form(None),
end_date: str = Form(None), end_date: str = Form(None),
store_batch_no: str = Form(None),
factory_batch_no: str = Form(None),
): ):
"""根据已上传的数据生成鸿蒙生态分析报表(产值数据从数据库自动查询)""" """根据已上传的数据或历史批次生成鸿蒙生态分析报表(产值数据从数据库自动查询)"""
global _harmony_store_file, _harmony_factory_file global _harmony_store_file, _harmony_factory_file
# 门店兜底配置:未上传时使用最新模板 # 加载store_df:优先批次DB数据,其次文件,最后默认模板
if not _harmony_store_file or not os.path.exists(_harmony_store_file): if store_batch_no:
store_df = _load_store_df_from_batch(store_batch_no)
elif _harmony_store_file and os.path.exists(_harmony_store_file):
store_df = HarmonyAnalysisService.read_store_list(_harmony_store_file)
else:
try: try:
_harmony_store_file = _find_latest_template("门店数据-鸿蒙-模板") _harmony_store_file = _find_latest_template("门店数据-鸿蒙-模板")
store_df = HarmonyAnalysisService.read_store_list(_harmony_store_file)
except FileNotFoundError: except FileNotFoundError:
raise HTTPException(status_code=400, detail="请先上传门店兜底配置文件") raise HTTPException(status_code=400, detail="请先上传门店兜底配置文件")
# 加载factory_df:优先批次DB数据,其次文件
factory_df = None factory_df = None
if factory_batch_no:
if _harmony_factory_file and os.path.exists(_harmony_factory_file): factory_df = _load_oem_factory_from_batch(factory_batch_no)
elif _harmony_factory_file and os.path.exists(_harmony_factory_file):
factory_df = HarmonyAnalysisService.read_factory_data(_harmony_factory_file) factory_df = HarmonyAnalysisService.read_factory_data(_harmony_factory_file)
try: try:
store_df = HarmonyAnalysisService.read_store_list(_harmony_store_file)
output_path = HarmonyAnalysisService.build_report( output_path = HarmonyAnalysisService.build_report(
store_df, store_df,
factory_df=factory_df, factory_df=factory_df,
...@@ -747,10 +771,9 @@ async def harmony_generate( ...@@ -747,10 +771,9 @@ async def harmony_generate(
@router.get("/harmony/download") @router.get("/harmony/download")
async def harmony_download(file: str = Query(None)): async def harmony_download(file: str = Query(None)):
"""下载鸿蒙分析报表""" """下载鸿蒙分析报表"""
output_dir = "temp_uploads"
if file: if file:
file_path = os.path.join(output_dir, file) file_path = _find_file(file)
if not os.path.exists(file_path): if not file_path:
raise HTTPException(status_code=404, detail="指定的报表文件不存在") raise HTTPException(status_code=404, detail="指定的报表文件不存在")
return FileResponse( return FileResponse(
file_path, filename=file, file_path, filename=file,
...@@ -759,14 +782,15 @@ async def harmony_download(file: str = Query(None)): ...@@ -759,14 +782,15 @@ async def harmony_download(file: str = Query(None)):
# 无指定时返回最新的鸿蒙分析文件 # 无指定时返回最新的鸿蒙分析文件
output_files = sorted( output_files = sorted(
[f for f in os.listdir(output_dir) if f.startswith("鸿蒙分析") and f.endswith(".xlsx")], [os.path.join(root, f) for root, _ds, fs in os.walk(UPLOAD_BASE)
key=lambda f: os.path.getmtime(os.path.join(output_dir, f)), for f in fs if f.startswith("鸿蒙分析") and f.endswith(".xlsx")],
key=lambda f: os.path.getmtime(f),
reverse=True reverse=True
) )
if not output_files: if not output_files:
raise HTTPException(status_code=404, detail="未找到鸿蒙分析报表,请先生成") raise HTTPException(status_code=404, detail="未找到鸿蒙分析报表,请先生成")
file_path = os.path.join(output_dir, output_files[0]) file_path = output_files[0]
return FileResponse( return FileResponse(
file_path, file_path,
filename=output_files[0], filename=output_files[0],
...@@ -946,20 +970,16 @@ async def strategy_stale_list(stale_hours: int = Query(4, ge=1, le=48)): ...@@ -946,20 +970,16 @@ async def strategy_stale_list(stale_hours: int = Query(4, ge=1, le=48)):
# ==================== 门店数据 & 主机厂数据 上传接口 ==================== # ==================== 门店数据 & 主机厂数据 上传接口 ====================
# 临时上传缓存目录 # 数据导入临时上传(使用 _date_path + data 类别实现日期分级)
DATA_UPLOAD_BASE_DIR = "temp_uploads/data" DATA_UPLOAD_CATEGORY = "data"
def _save_upload(file: UploadFile, brand: str, data_type: str) -> tuple: def _save_upload(file: UploadFile, brand: str, data_type: str) -> tuple:
"""保存上传文件到按日期分级的目录,返回 (文件路径, 原始文件名)""" """保存上传文件到按日期分级的目录,返回 (文件路径, 原始文件名)"""
today = datetime.now().strftime("%Y%m%d")
ts = datetime.now().strftime("%H%M%S") ts = datetime.now().strftime("%H%M%S")
upload_dir = os.path.join(DATA_UPLOAD_BASE_DIR, today)
os.makedirs(upload_dir, exist_ok=True)
base, ext = os.path.splitext(file.filename) base, ext = os.path.splitext(file.filename)
safe_name = f"{data_type}_{brand}_{ts}{ext}" safe_name = f"{data_type}_{brand}_{ts}{ext}"
file_path = os.path.join(upload_dir, safe_name) file_path = _date_path(safe_name, category=DATA_UPLOAD_CATEGORY)
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(file.file, f) shutil.copyfileobj(file.file, f)
......
...@@ -43,6 +43,7 @@ class Settings(BaseSettings): ...@@ -43,6 +43,7 @@ class Settings(BaseSettings):
LLM_QWEN_MODEL: str = "qwen3.7-plus" LLM_QWEN_MODEL: str = "qwen3.7-plus"
LLM_QWEN_API_KEY: Optional[str] = None LLM_QWEN_API_KEY: Optional[str] = None
LLM_QWEN_BASE_URL: str = "https://llm-3druebrrtubn1ouc.cn-beijing.maas.aliyuncs.com/compatible-mode/v1" LLM_QWEN_BASE_URL: str = "https://llm-3druebrrtubn1ouc.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
LLM_QWEN_VISION_MODEL: str = "qwen-vl-max" # 视觉模型,用于图片转表格等场景
# Log Settings # Log Settings
LOG_DIR: str = "logs" LOG_DIR: str = "logs"
......
...@@ -34,7 +34,7 @@ class SchedulerManager: ...@@ -34,7 +34,7 @@ class SchedulerManager:
# 1. ODS 同步任务 (每 30 分钟执行一次,带 3s 抖动,模仿用户参考) # 1. ODS 同步任务 (每 30 分钟执行一次,带 3s 抖动,模仿用户参考)
cls._scheduler.add_job( cls._scheduler.add_job(
cls.sync_ods_task, cls.sync_ods_task,
IntervalTrigger(minutes=30, jitter=3), IntervalTrigger(minutes=180, jitter=3),
id="sync_ods_data", id="sync_ods_data",
max_instances=1, max_instances=1,
replace_existing=True replace_existing=True
...@@ -94,7 +94,7 @@ class SchedulerManager: ...@@ -94,7 +94,7 @@ class SchedulerManager:
logger.info(f"[Scheduler] Start sync_ods_task at {datetime.now()}") logger.info(f"[Scheduler] Start sync_ods_task at {datetime.now()}")
try: try:
from app.services.etl_service import ETLService from app.services.etl_service import ETLService
results = await ETLService.run_ods_sync(task_id="scheduler_ods_sync") results = await asyncio.to_thread(ETLService.run_ods_sync, task_id="scheduler_ods_sync")
logger.info(f"[Scheduler] sync_ods_task completed. Results: {results}") logger.info(f"[Scheduler] sync_ods_task completed. Results: {results}")
except Exception as e: except Exception as e:
logger.error(f"[Scheduler] sync_ods_task failed: {e}") logger.error(f"[Scheduler] sync_ods_task failed: {e}")
...@@ -162,7 +162,8 @@ class SchedulerManager: ...@@ -162,7 +162,8 @@ class SchedulerManager:
logger.info(f"[Scheduler] DWS sync date range: {start_str} ~ {end_str}") logger.info(f"[Scheduler] DWS sync date range: {start_str} ~ {end_str}")
from app.services.etl_service import ETLService from app.services.etl_service import ETLService
results = await ETLService.run_dw_sync( results = await asyncio.to_thread(
ETLService.run_dw_sync,
layer='DWS', layer='DWS',
start_date=start_str, start_date=start_str,
end_date=end_str, end_date=end_str,
......
...@@ -777,7 +777,7 @@ class AnalysisService: ...@@ -777,7 +777,7 @@ class AnalysisService:
ref_date = max(d for d in [ecology_end, nature_end] if d) if (ecology_end or nature_end) else "" ref_date = max(d for d in [ecology_end, nature_end] if d) if (ecology_end or nature_end) else ""
sheet_name = f"数据截止{ref_date}" if ref_date else "生态系数分析" sheet_name = f"数据截止{ref_date}" if ref_date else "生态系数分析"
output_dir = "temp_uploads" output_dir = os.path.join("temp_uploads", "reports", date.today().strftime("%Y%m%d"))
os.makedirs(output_dir, exist_ok=True) os.makedirs(output_dir, exist_ok=True)
import time import time
......
...@@ -65,7 +65,9 @@ class ETLService: ...@@ -65,7 +65,9 @@ class ETLService:
password=settings.SOURCE_DB_PASSWORD, password=settings.SOURCE_DB_PASSWORD,
database=settings.SOURCE_DB_NAME, database=settings.SOURCE_DB_NAME,
charset='utf8mb4', charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor cursorclass=pymysql.cursors.DictCursor,
connect_timeout=10,
read_timeout=300
) )
@staticmethod @staticmethod
...@@ -78,11 +80,13 @@ class ETLService: ...@@ -78,11 +80,13 @@ class ETLService:
database=settings.DB_NAME, database=settings.DB_NAME,
charset='utf8mb4', charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor, cursorclass=pymysql.cursors.DictCursor,
autocommit=True autocommit=True,
connect_timeout=10,
read_timeout=300
) )
@classmethod @classmethod
async def run_ods_sync(cls, source_table_filter: str = None, task_id: str = "auto_ods_sync"): def run_ods_sync(cls, source_table_filter: str = None, task_id: str = "auto_ods_sync"):
""" """
执行真实的 ODS 层同步任务:从源生产库抽取数据并 Upsert 到目标数仓。 执行真实的 ODS 层同步任务:从源生产库抽取数据并 Upsert 到目标数仓。
""" """
...@@ -392,7 +396,7 @@ class ETLService: ...@@ -392,7 +396,7 @@ class ETLService:
conn.close() conn.close()
@classmethod @classmethod
async def run_dw_sync(cls, layer: str, start_date: str = None, end_date: str = None, task_id: str = None, full_sync: str = None): def run_dw_sync(cls, layer: str, start_date: str = None, end_date: str = None, task_id: str = None, full_sync: str = None):
""" """
执行 DWS/DWM/DWA 层的数据加工任务。 执行 DWS/DWM/DWA 层的数据加工任务。
......
...@@ -445,7 +445,7 @@ class HarmonyAnalysisService: ...@@ -445,7 +445,7 @@ class HarmonyAnalysisService:
end_date = date.today().strftime('%Y-%m-%d') end_date = date.today().strftime('%Y-%m-%d')
# 输出文件 # 输出文件
output_dir = "temp_uploads" output_dir = os.path.join("temp_uploads", "reports", date.today().strftime("%Y%m%d"))
os.makedirs(output_dir, exist_ok=True) os.makedirs(output_dir, exist_ok=True)
ts = int(time.time()) ts = int(time.time())
date_str = end_date.replace("-", "") date_str = end_date.replace("-", "")
......
...@@ -213,7 +213,7 @@ class StrategyService: ...@@ -213,7 +213,7 @@ class StrategyService:
AND TABLE_NAME = 'strategy_analysis_result' AND TABLE_NAME = 'strategy_analysis_result'
AND COLUMN_NAME = 'monitor_refresh_time' AND COLUMN_NAME = 'monitor_refresh_time'
""") """)
if cur.fetchone()[0] == 0: if cur.fetchone()['COUNT(*)'] == 0:
cur.execute(alter_sql) cur.execute(alter_sql)
logger.info("[Strategy] added monitor_refresh_time column") logger.info("[Strategy] added monitor_refresh_time column")
conn.commit() conn.commit()
......
...@@ -271,7 +271,6 @@ ...@@ -271,7 +271,6 @@
<a class="nav-item active" href="./analysis">问界生态系数分析</a> <a class="nav-item active" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./strategy">策略效果盯防(开发中)</a> <a class="nav-item" href="./strategy">策略效果盯防(开发中)</a>
<a class="nav-item" href="./import">数据导入</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
......
...@@ -45,7 +45,6 @@ ...@@ -45,7 +45,6 @@
<a class="nav-item" href="./analysis">问界生态系数分析</a> <a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./strategy">策略效果盯防</a> <a class="nav-item" href="./strategy">策略效果盯防</a>
<a class="nav-item active" href="./import">数据导入</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
......
...@@ -16,7 +16,6 @@ ...@@ -16,7 +16,6 @@
<a class="nav-item" href="./analysis">问界生态系数分析</a> <a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./strategy">策略效果盯防(开发中)</a> <a class="nav-item" href="./strategy">策略效果盯防(开发中)</a>
<a class="nav-item" href="./import">数据导入</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
...@@ -100,7 +99,8 @@ ...@@ -100,7 +99,8 @@
<script src="./static/js/common.js"></script> <script src="./static/js/common.js"></script>
<script src="./static/js/auth.js"></script> <script src="./static/js/auth.js"></script>
<script> <script>
const DW_FILTER = item => item.task_id.includes('sync'); // 只匹配 DW 加工任务:manual_dws_sync / manual_dwm_sync / manual_dwa_sync / scheduler_dws_sync
const DW_FILTER = item => /_(dws|dwm|dwa)_sync$/.test(item.task_id);
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
const now = new Date(); const now = new Date();
......
...@@ -5,6 +5,126 @@ ...@@ -5,6 +5,126 @@
<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">
<style>
.analysis-layout {
display: flex; gap: 16px; height: calc(100vh - 160px);
min-height: 600px; align-items: flex-start; overflow: hidden;
}
.left-panel {
width: 420px; min-width: 380px; height: 100%; overflow-y: auto;
scrollbar-width: none; -ms-overflow-style: none;
display: flex; flex-direction: column; gap: 10px;
}
.left-panel::-webkit-scrollbar { display: none; }
.right-panel {
flex: 1; height: 100%; overflow: hidden;
border: 1px solid #e8e8e8; border-radius: 6px;
background: #fff; display: flex; flex-direction: column;
}
.right-panel-header {
padding: 10px 16px; border-bottom: 1px solid #e8e8e8;
background: #fafafa; font-size: 13px; color: #666;
display: flex; align-items: center; justify-content: space-between;
}
.right-panel-body { flex: 1; overflow: auto; padding: 0; }
.right-panel-meta {
padding: 6px 16px; border-bottom: 1px solid #e8e8e8;
background: #f0f7ff; font-size: 12px; color: #555;
display: flex; flex-wrap: wrap; gap: 4px 16px;
}
.right-panel-meta .meta-item { white-space: nowrap; }
.right-panel-meta .meta-label { color: #999; }
.right-panel-meta .meta-value { color: #333; font-weight: 500; }
.right-panel-empty {
display: flex; align-items: center; justify-content: center;
height: 100%; color: #bbb; font-size: 14px;
}
.step-card {
background: #f8f9fa; padding: 10px 14px;
border-radius: 6px; border: 1px solid #e8e8e8;
}
.step-card.active { border-color: #1890ff; background: #f0f5ff; }
.step-title {
font-size: 14px; font-weight: 600; color: #333;
margin-bottom: 8px; display: flex; align-items: center; gap: 6px;
}
.step-row { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
.step-row:last-child { margin-bottom: 0; }
.step-select {
flex: 1; padding: 5px 8px; border: 1px solid #d9d9d9;
border-radius: 4px; font-size: 12px; background: #fff; color: #333;
}
.btn-save-batch {
margin-top: 6px; padding: 4px 12px; border: 1px solid #1890ff;
border-radius: 4px; background: #e6f7ff; color: #1890ff;
font-size: 12px; cursor: pointer; width: 100%;
}
.btn-save-batch:hover { background: #bae7ff; }
.btn-save-batch:disabled { opacity: 0.5; cursor: not-allowed; }
.step-or { font-size: 11px; color: #999; white-space: nowrap; }
.step-upload-zone {
flex: 1; border: 1px dashed #d9d9d9; padding: 5px 10px;
border-radius: 4px; cursor: pointer; background: #fff;
font-size: 12px; color: #999; white-space: nowrap;
overflow: hidden; text-overflow: ellipsis;
display: flex; align-items: center; gap: 4px;
}
.step-upload-zone.has-file {
color: #52c41a; border-color: #52c41a; background: #f6ffed;
}
.step-date-row {
display: flex; align-items: center; gap: 6px; margin-top: 6px;
}
.step-date-row input[type="date"] {
width: 130px; padding: 4px 6px; border: 1px solid #d9d9d9;
border-radius: 4px; font-size: 12px;
}
.btn-download-tpl {
font-size: 11px; color: #1890ff; text-decoration: none;
white-space: nowrap; cursor: pointer;
}
.btn-download-tpl:hover { text-decoration: underline; }
.btn-generate {
padding: 12px 48px; background: #1890ff; color: white;
border: none; border-radius: 6px; font-size: 16px;
cursor: pointer; transition: all 0.3s; width: 100%;
}
.btn-generate:hover { background: #40a9ff; }
.btn-generate:disabled { background: #d9d9d9; cursor: not-allowed; }
.preview-table {
width: 100%; border-collapse: collapse; font-size: 12px; white-space: nowrap;
}
.preview-table thead { position: sticky; top: 0; z-index: 2; }
.preview-table th {
background: #fafafa; padding: 6px 10px; border-bottom: 2px solid #e8e8e8;
text-align: left; font-weight: 600; color: #333;
position: sticky; top: 0;
}
.preview-table td {
padding: 5px 10px; border-bottom: 1px solid #f0f0f0;
color: #555; max-width: 200px; overflow: hidden; text-overflow: ellipsis;
}
.preview-table tr:hover td { background: #e6f7ff; }
.result-box {
padding: 16px; border-radius: 8px; text-align: center; display: none;
}
.result-box.success {
display: block; background: #f6ffed; border: 1px solid #b7eb8f;
}
.result-box.error {
display: block; background: #fff2f0; border: 1px solid #ffccc7;
}
.btn-download {
display: inline-block; padding: 10px 32px; background: #52c41a;
color: white; border: none; border-radius: 4px; font-size: 14px;
text-decoration: none; cursor: pointer; margin-top: 10px;
}
@media (max-width: 900px) {
.analysis-layout { flex-direction: column; height: auto; }
.left-panel { width: 100%; min-width: 0; }
.right-panel { min-height: 400px; }
}
</style>
</head> </head>
<body> <body>
<header> <header>
...@@ -16,7 +136,6 @@ ...@@ -16,7 +136,6 @@
<a class="nav-item" href="./analysis">问界生态系数分析</a> <a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item active" href="./harmony">鸿蒙生态分析</a> <a class="nav-item active" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./strategy">策略效果盯防(开发中)</a> <a class="nav-item" href="./strategy">策略效果盯防(开发中)</a>
<a class="nav-item" href="./import">数据导入</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
...@@ -26,166 +145,242 @@ ...@@ -26,166 +145,242 @@
<div class="card"> <div class="card">
<h2 id="content-title">鸿蒙生态分析</h2> <h2 id="content-title">鸿蒙生态分析</h2>
<div id="content-body"> <div id="content-body">
<div class="analysis-layout">
<div id="harmony-analysis-section"> <!-- ============ 左侧表单 ============ -->
<div style="display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px;"> <div class="left-panel">
<!-- 步骤1: 上传门店兜底配置 --> <!-- 步骤1: 门店兜底配置 -->
<div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 16px;"> <div class="step-card" id="step1-card">
<span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">门店兜底配置</span> <div class="step-title">&#9312; 步骤1: 门店兜底配置</div>
<div id="hm-store-drop-zone" style="flex:1; border: 1px dashed #d9d9d9; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;"> <div class="step-row">
<input type="file" id="hm-store-file-input" style="display:none;" accept=".xlsx,.xls"> <select class="step-select" id="store-batch-select" onchange="onStoreBatchSelect()">
<span style="font-size:16px;">&#x1f3ea;</span> <option value="">-- 选择历史批次 --</option>
<p id="hm-store-file-name" style="margin:0; font-size:13px; color:#999;">可选:点击选择门店兜底配置文件(不选则使用系统默认模板)</p> </select>
</div>
<div class="step-row">
<span class="step-or">或</span>
<div class="step-upload-zone" id="store-drop-zone" onclick="document.getElementById('store-file-input').click()">
<input type="file" id="store-file-input" style="display:none;" accept=".xlsx,.xls" onchange="onStoreFileChange()">
&#x1f4c1; <span id="store-file-name">点击上传门店兜底配置文件</span>
</div>
<a class="btn-download-tpl" href="./api/harmony/template/store">&#x1f4e5; 模板</a>
</div> </div>
<a href="./api/harmony/template/store" style="font-size:12px; color:#1890ff; text-decoration:none; white-space:nowrap;">&#x1f4e5; 下载模板</a> <button class="btn-save-batch" id="btn-save-store" style="display:none;" onclick="saveBatch('store')">&#x1f4be; 保存为历史批次</button>
</div> </div>
<!-- 步骤2: 上传主机厂数据 --> <!-- 步骤2: 主机厂数据 -->
<div style="background: #f0f5ff; padding: 8px 16px; border-radius: 6px; border: 1px solid #adc6ff; display: flex; align-items: center; gap: 12px;"> <div class="step-card" id="step2-card">
<span style="font-size:14px; font-weight:600; color:#1890ff; white-space:nowrap;">主机厂数据</span> <div class="step-title">&#9313; 步骤2: 主机厂数据</div>
<div id="hm-factory-drop-zone" style="flex:1; border: 1px dashed #1890ff; padding: 6px 12px; border-radius: 4px; cursor: pointer; background: #fff; display: flex; align-items: center; gap: 8px;"> <div class="step-row">
<input type="file" id="hm-factory-file-input" style="display:none;" accept=".xlsx,.xls"> <select class="step-select" id="factory-batch-select" onchange="onFactoryBatchSelect()">
<span style="font-size:16px;">&#x1f3ed;</span> <option value="">-- 选择历史批次 --</option>
<p id="hm-factory-file-name" style="margin:0; font-size:12px; color:#999;">点击选择主机厂数据(含交付数)</p> </select>
</div> </div>
<a href="./api/harmony/template/factory" style="font-size:12px; color:#1890ff; text-decoration:none; white-space:nowrap;">&#x1f4e5; 下载模板</a> <div class="step-row">
<span class="step-or">或</span>
<div class="step-upload-zone" id="factory-drop-zone" onclick="document.getElementById('factory-file-input').click()">
<input type="file" id="factory-file-input" style="display:none;" accept=".xlsx,.xls" onchange="onFactoryFileChange()">
&#x1f4c1; <span id="factory-file-name">点击上传主机厂数据(含交付数)</span>
</div>
<a class="btn-download-tpl" href="./api/harmony/template/factory">&#x1f4e5; 模板</a>
</div>
<div class="step-date-row">
<input type="date" id="hm-start-date" title="开始日期">
<span style="font-size:12px;color:#999;">~</span>
<input type="date" id="hm-end-date" title="结束日期">
</div>
<button class="btn-save-batch" id="btn-save-factory" style="display:none;" onclick="saveBatch('factory')">&#x1f4be; 保存为历史批次</button>
</div> </div>
<!-- 说明: 产值表数据从数据库自动查询 --> <!-- 说明 -->
<div style="background: #e6f7ff; padding: 6px 16px; border-radius: 6px; border: 1px solid #91d5ff; display: flex; align-items: center; gap: 8px;"> <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:13px; color:#1890ff;">&#x1f6c8;</span>
<span style="font-size:12px; color:#666;">产值表数据(触客数、成交数、渗透率等)将自动从数据库查询,无需上传。</span> <span style="font-size:12px; color:#666;">产值表数据(触客数、成交数、渗透率等)将自动从数据库查询,无需上传。</span>
</div> </div>
<!-- 日期范围 --> <!-- 生成按钮 -->
<div style="background: #f8f9fa; padding: 8px 16px; border-radius: 6px; border: 1px solid #e8e8e8; display: flex; align-items: center; gap: 12px;"> <div style="text-align:center; margin-top:4px;">
<span style="font-size:14px; font-weight:600; color:#333; white-space:nowrap;">数据周期</span> <button class="btn-generate" id="btn-generate-report">
<input type="date" id="hm-start-date" style="width:140px; padding: 4px 6px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;">
<span style="color:#999; font-size:12px;">~</span>
<input type="date" id="hm-end-date" style="width:140px; padding: 4px 6px; border: 1px solid #d9d9d9; border-radius: 4px; font-size:12px;">
</div>
</div>
<!-- 生成报表按钮 -->
<div style="text-align: center; margin: 20px 0;">
<button id="btn-hm-generate" style="padding: 12px 48px; background: #1890ff; color: white; border: none; border-radius: 6px; font-size: 16px; cursor: pointer; transition: all 0.3s;">
&#x1f680; 生成鸿蒙生态分析报表 &#x1f680; 生成鸿蒙生态分析报表
</button> </button>
<p style="font-size:12px; color:#999; margin-top:8px;">合并门店兜底配置 + 主机厂交付数据 + 数据库产值指标,计算渗透率达标系数和赔付金额</p> <p style="font-size:11px;color:#999;margin-top:4px;">使用模板: 输出模板-鸿蒙-模板001.xlsx</p>
<p style="font-size:11px; color:#faad14;">&#x1f4cc; 使用模板: 输出模板-鸿蒙-模板001.xlsx</p>
</div> </div>
<!-- 结果提示 --> <!-- 生成结果 -->
<div id="hm-result" style="display:none; background: #f6ffed; border: 1px solid #b7eb8f; padding: 20px; border-radius: 8px; text-align: center;"> <div class="result-box" id="analysis-result">
<h3 style="color:#52c41a; margin:0 0 10px;">&#x2705; 报表生成成功</h3> <h3 style="color:#52c41a;margin:0 0 6px;">&#x2705; 报表生成成功</h3>
<div id="hm-result-info" style="font-size:13px; color:#666; margin-bottom:15px;"></div> <div style="font-size:12px;color:#666;margin-bottom:10px;" id="analysis-result-info"></div>
<a id="btn-hm-download" href="#" <a class="btn-download" id="btn-download-report" href="#">&#x1f4e5; 下载分析报表</a>
style="display:inline-block; padding: 10px 32px; background: #52c41a; color: white; border: none; border-radius: 4px; font-size: 14px; text-decoration: none; cursor: pointer;"> </div>
&#x1f4e5; 下载分析报表 <div class="result-box" id="analysis-error">
</a> <h3 style="color:#f5222d;margin:0 0 6px;">&#x274c; 报表生成失败</h3>
<p style="margin:0;color:#666;font-size:12px;" id="analysis-error-msg"></p>
</div>
</div> </div>
<div id="hm-error" style="display:none; background: #fff2f0; border: 1px solid #ffccc7; padding: 20px; border-radius: 8px; text-align: center;"> <!-- ============ 右侧预览 ============ -->
<h3 style="color:#f5222d; margin:0 0 10px;">&#x274c; 报表生成失败</h3> <div class="right-panel">
<p id="hm-error-msg" style="margin:0; color:#666;"></p> <div class="right-panel-header">
<span id="preview-title">&#x1f4ca; 数据预览</span>
<span id="preview-count" style="font-size:11px;color:#999;"></span>
</div>
<div class="right-panel-meta" id="preview-meta" style="display:none;"></div>
<div class="right-panel-body" id="preview-body">
<div class="right-panel-empty" id="preview-empty">
请在左侧选择历史批次或上传文件,数据将在此处预览
</div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div>
</section> </section>
</main> </main>
<script> <script>
(function(){var p=window.location.pathname;if(p.endsWith('/'))p=p.slice(0,-1);var i=p.lastIndexOf('/');window.API_BASE=p.substring(0,i)+'/api';})(); (function(){var p=window.location.pathname;if(p.endsWith('/'))p=p.slice(0,-1);var i=p.lastIndexOf('/');window.API_BASE=p.substring(0,i)+'/api';})();
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
const fmt = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`; const fmt = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
const now = new Date(); const now = new Date();
const todayStr = fmt(now); const yesterday = new Date(now);
yesterday.setDate(yesterday.getDate() - 1);
const yesterdayStr = fmt(yesterday);
const firstOfMonth = fmt(new Date(now.getFullYear(), now.getMonth(), 1)); const firstOfMonth = fmt(new Date(now.getFullYear(), now.getMonth(), 1));
const startDate = document.getElementById('hm-start-date'); // 默认日期
const endDate = document.getElementById('hm-end-date'); const hmStart = document.getElementById('hm-start-date');
if (startDate && !startDate.value) startDate.value = firstOfMonth; const hmEnd = document.getElementById('hm-end-date');
if (endDate && !endDate.value) endDate.value = todayStr; if (hmStart && !hmStart.value) hmStart.value = firstOfMonth;
if (hmEnd && !hmEnd.value) hmEnd.value = yesterdayStr;
// 门店兜底配置上传
const storeDropZone = document.getElementById('hm-store-drop-zone'); // 加载历史批次下拉
const storeFileInput = document.getElementById('hm-store-file-input'); loadBatchOptions();
if (storeDropZone) {
storeDropZone.addEventListener('click', () => storeFileInput.click()); // ========== 步骤1: 门店兜底配置 ==========
storeFileInput.addEventListener('change', () => { window.onStoreBatchSelect = async function() {
if (storeFileInput.files.length > 0) { const sel = document.getElementById('store-batch-select');
document.getElementById('hm-store-file-name').textContent = '\u2705 已选择: ' + storeFileInput.files[0].name; if (!sel.value) return;
document.getElementById('hm-store-file-name').style.color = '#52c41a'; highlightStep('step1-card');
} const opt = sel.options[sel.selectedIndex];
await loadBatchPreview(sel.value, '门店兜底配置 - 历史批次', {
type: '门店兜底配置',
period: opt.dataset.periodStart ? `${opt.dataset.periodStart} ~ ${opt.dataset.periodEnd}` : '',
source: opt.textContent.split(' [')[0],
}); });
} };
// 主机厂数据上传 window.onStoreFileChange = async function() {
const factoryDropZone = document.getElementById('hm-factory-drop-zone'); const input = document.getElementById('store-file-input');
const factoryFileInput = document.getElementById('hm-factory-file-input'); if (!input.files.length) return;
if (factoryDropZone) { const name = input.files[0].name;
factoryDropZone.addEventListener('click', () => factoryFileInput.click()); document.getElementById('store-file-name').textContent = '\u2705 ' + name;
factoryFileInput.addEventListener('change', () => { document.getElementById('store-drop-zone').classList.add('has-file');
if (factoryFileInput.files.length > 0) { document.getElementById('store-batch-select').value = '';
document.getElementById('hm-factory-file-name').textContent = '\u2705 已选择: ' + factoryFileInput.files[0].name; highlightStep('step1-card');
document.getElementById('hm-factory-file-name').style.color = '#52c41a'; document.getElementById('btn-save-store').style.display = 'block';
}
const formData = new FormData();
formData.append('file_type', 'store');
formData.append('file', input.files[0]);
await previewFile(formData, '门店兜底配置 - ' + name);
};
// ========== 步骤2: 主机厂数据 ==========
window.onFactoryBatchSelect = async function() {
const sel = document.getElementById('factory-batch-select');
if (!sel.value) return;
highlightStep('step2-card');
const opt = sel.options[sel.selectedIndex];
// 同步日期
if (opt.dataset.periodStart) document.getElementById('hm-start-date').value = opt.dataset.periodStart;
if (opt.dataset.periodEnd) document.getElementById('hm-end-date').value = opt.dataset.periodEnd;
await loadBatchPreview(sel.value, '主机厂数据 - 历史批次', {
type: '主机厂交付数据',
period: opt.dataset.periodStart ? `${opt.dataset.periodStart} ~ ${opt.dataset.periodEnd}` : '',
source: opt.textContent.split(' [')[0],
}); });
} };
// 生成报表 window.onFactoryFileChange = async function() {
const btnGenerate = document.getElementById('btn-hm-generate'); const input = document.getElementById('factory-file-input');
if (!input.files.length) return;
const name = input.files[0].name;
document.getElementById('factory-file-name').textContent = '\u2705 ' + name;
document.getElementById('factory-drop-zone').classList.add('has-file');
document.getElementById('factory-batch-select').value = '';
highlightStep('step2-card');
document.getElementById('btn-save-factory').style.display = 'block';
const formData = new FormData();
formData.append('file_type', 'factory');
formData.append('file', input.files[0]);
await previewFile(formData, '主机厂数据 - ' + name);
};
// ========== 生成报表 ==========
const btnGenerate = document.getElementById('btn-generate-report');
if (btnGenerate) { if (btnGenerate) {
btnGenerate.addEventListener('click', async () => { btnGenerate.addEventListener('click', async () => {
document.getElementById('hm-result').style.display = 'none'; document.getElementById('analysis-result').className = 'result-box';
document.getElementById('hm-error').style.display = 'none'; document.getElementById('analysis-error').className = 'result-box';
const storeInput = document.getElementById('store-file-input');
const factoryInput = document.getElementById('factory-file-input');
const storeBatchSel = document.getElementById('store-batch-select');
const factoryBatchSel = document.getElementById('factory-batch-select');
const hasStore = storeFileInput && storeFileInput.files.length > 0; const hasStoreFile = storeInput && storeInput.files.length > 0;
const hasFactory = factoryFileInput && factoryFileInput.files.length > 0; const hasFactoryFile = factoryInput && factoryInput.files.length > 0;
const hasStoreBatch = storeBatchSel && storeBatchSel.value;
const hasFactoryBatch = factoryBatchSel && factoryBatchSel.value;
btnGenerate.disabled = true; btnGenerate.disabled = true;
btnGenerate.textContent = '\u23f3 正在上传文件...'; btnGenerate.textContent = '\u23f3 正在生成报表...';
try { try {
// 上传文件
const uploadForm = new FormData(); const uploadForm = new FormData();
if (hasStore) uploadForm.append('store_file', storeFileInput.files[0]); if (hasStoreFile) uploadForm.append('store_file', storeInput.files[0]);
if (hasFactory) uploadForm.append('factory_file', factoryFileInput.files[0]); if (hasFactoryFile) uploadForm.append('factory_file', factoryInput.files[0]);
const anyFile = hasStoreFile || hasFactoryFile;
if (anyFile) {
const uploadRes = await fetch(window.API_BASE + '/harmony/upload', { method: 'POST', body: uploadForm }); const uploadRes = await fetch(window.API_BASE + '/harmony/upload', { method: 'POST', body: uploadForm });
const uploadData = await uploadRes.json(); const uploadData = await uploadRes.json();
if (uploadData.status !== 'success') { if (uploadData.status !== 'success') throw new Error(uploadData.detail || '文件上传失败');
throw new Error(uploadData.detail || '文件上传失败');
} }
btnGenerate.textContent = '\u23f3 正在分析计算...'; btnGenerate.textContent = '\u23f3 正在分析计算...';
// 生成报表
const genForm = new FormData(); const genForm = new FormData();
const sd = document.getElementById('hm-start-date').value; const sd = document.getElementById('hm-start-date').value;
const ed = document.getElementById('hm-end-date').value; const ed = document.getElementById('hm-end-date').value;
if (sd) genForm.append('start_date', sd); if (sd) genForm.append('start_date', sd);
if (ed) genForm.append('end_date', ed); if (ed) genForm.append('end_date', ed);
// 传递批次号
if (hasStoreBatch) genForm.append('store_batch_no', storeBatchSel.value);
if (hasFactoryBatch) genForm.append('factory_batch_no', factoryBatchSel.value);
const genRes = await fetch(window.API_BASE + '/harmony/generate', { method: 'POST', body: genForm }); const genRes = await fetch(window.API_BASE + '/harmony/generate', { method: 'POST', body: genForm });
const genData = await genRes.json(); const genData = await genRes.json();
if (genData.status === 'success') { if (genData.status === 'success') {
document.getElementById('hm-result').style.display = 'block'; document.getElementById('analysis-result').className = 'result-box success';
document.getElementById('hm-result-info').innerHTML = document.getElementById('analysis-result-info').innerHTML =
'门店数: <strong>' + genData.store_count + '</strong> | ' + '门店数: <strong>' + genData.store_count + '</strong> | ' +
'主机厂门店: <strong>' + genData.factory_count + '</strong> | ' + '主机厂门店: <strong>' + genData.factory_count + '</strong> | ' +
'DB产值数据: <strong>' + genData.db_store_count + '</strong> 家门店'; 'DB产值数据: <strong>' + genData.db_store_count + '</strong> 家门店';
document.getElementById('btn-hm-download').href = genData.download_url; document.getElementById('btn-download-report').href = genData.download_url;
} else { } else {
throw new Error(genData.detail || '报表生成失败'); throw new Error(genData.detail || '报表生成失败');
} }
} catch (err) { } catch (err) {
console.error('鸿蒙分析失败:', err); console.error('鸿蒙分析失败:', err);
document.getElementById('hm-error').style.display = 'block'; document.getElementById('analysis-error').className = 'result-box error';
document.getElementById('hm-error-msg').textContent = err.message || '未知错误'; document.getElementById('analysis-error-msg').textContent = err.message || '未知错误';
} finally { } finally {
btnGenerate.disabled = false; btnGenerate.disabled = false;
btnGenerate.textContent = '\u{1f680} 生成鸿蒙生态分析报表'; btnGenerate.textContent = '\u{1f680} 生成鸿蒙生态分析报表';
...@@ -193,6 +388,186 @@ ...@@ -193,6 +388,186 @@
}); });
} }
}); });
// ========== 辅助函数 ==========
function highlightStep(cardId) {
document.querySelectorAll('.step-card').forEach(c => c.classList.remove('active'));
const card = document.getElementById(cardId);
if (card) card.classList.add('active');
}
async function loadBatchOptions() {
try {
const [storeRes, factoryRes] = await Promise.all([
fetch(window.API_BASE + '/data-import/history?brand=鸿蒙&data_type=store_guarantee'),
fetch(window.API_BASE + '/data-import/history?brand=鸿蒙&data_type=oem_delivery')
]);
const storeData = await storeRes.json();
const factoryData = await factoryRes.json();
function fillSelect(selId, rows) {
const sel = document.getElementById(selId);
if (!sel) return;
while (sel.options.length > 1) sel.remove(1);
(rows || []).forEach(r => {
const opt = document.createElement('option');
opt.value = r.batch_no;
opt.dataset.periodStart = r.data_period_start || '';
opt.dataset.periodEnd = r.data_period_end || '';
opt.textContent = `${r.file_name || r.batch_no} [${r.data_period_start}~${r.data_period_end}]`;
sel.appendChild(opt);
});
}
if (storeData.status === 'success') fillSelect('store-batch-select', storeData.data);
if (factoryData.status === 'success') fillSelect('factory-batch-select', factoryData.data);
} catch (e) {
console.error('加载历史批次失败:', e);
}
}
async function loadBatchPreview(batchNo, title, meta) {
showPreviewLoading(title);
document.getElementById('preview-meta').style.display = 'none';
try {
const res = await fetch(window.API_BASE + '/analysis/batch-data?batch_no=' + encodeURIComponent(batchNo));
const data = await res.json();
if (data.status === 'success') {
renderPreviewTable(data.data, title, meta);
} else {
showPreviewError(data.detail || '加载失败');
}
} catch (e) {
console.error('加载批次数据失败:', e);
showPreviewError('加载失败: ' + e.message);
}
}
async function previewFile(formData, title) {
showPreviewLoading(title);
try {
const res = await fetch(window.API_BASE + '/analysis/preview-file', { method: 'POST', body: formData });
const data = await res.json();
if (data.status === 'success') {
renderPreviewTable(data.data, title);
} else {
showPreviewError(data.detail || '解析失败');
}
} catch (e) {
console.error('预览文件失败:', e);
showPreviewError('预览失败: ' + e.message);
}
}
function showPreviewLoading(title) {
document.getElementById('preview-title').textContent = '\u23f3 ' + title;
document.getElementById('preview-count').textContent = '加载中...';
document.getElementById('preview-meta').style.display = 'none';
document.getElementById('preview-body').innerHTML =
'<div class="right-panel-empty">正在解析数据...</div>';
}
function showPreviewError(msg) {
document.getElementById('preview-title').textContent = '\u274c 加载失败';
document.getElementById('preview-count').textContent = '';
document.getElementById('preview-meta').style.display = 'none';
document.getElementById('preview-body').innerHTML =
'<div class="right-panel-empty" style="color:#f5222d;">' + msg + '</div>';
}
function renderPreviewTable(data, title, meta) {
document.getElementById('preview-title').textContent = '\u{1f4ca} ' + title;
document.getElementById('preview-count').textContent = '共 ' + data.total + ' 条';
const metaDiv = document.getElementById('preview-meta');
if (meta) {
let html = '';
if (meta.type) html += `<span class="meta-item"><span class="meta-label">数据类型:</span><span class="meta-value">${escapeHtml(meta.type)}</span></span>`;
if (meta.period) html += `<span class="meta-item"><span class="meta-label">时间范围:</span><span class="meta-value">${escapeHtml(meta.period)}</span></span>`;
if (meta.source) html += `<span class="meta-item"><span class="meta-label">来源:</span><span class="meta-value">${escapeHtml(meta.source)}</span></span>`;
html += `<span class="meta-item"><span class="meta-label">数据行数:</span><span class="meta-value">${data.total}</span></span>`;
metaDiv.innerHTML = html;
metaDiv.style.display = 'flex';
} else {
metaDiv.style.display = 'none';
}
const { columns, rows } = data;
if (!columns.length || !rows.length) {
document.getElementById('preview-body').innerHTML =
'<div class="right-panel-empty">无数据</div>';
return;
}
let html = '<table class="preview-table"><thead><tr>';
html += '<th style="width:40px;text-align:center;">#</th>';
columns.forEach(c => { html += '<th>' + escapeHtml(String(c)) + '</th>'; });
html += '</tr></thead><tbody>';
rows.forEach((row, i) => {
html += '<tr>';
html += '<td style="text-align:center;color:#999;">' + (i + 1) + '</td>';
columns.forEach(c => {
const val = row[c] !== undefined && row[c] !== null ? String(row[c]) : '';
html += '<td>' + escapeHtml(val) + '</td>';
});
html += '</tr>';
});
html += '</tbody></table>';
document.getElementById('preview-body').innerHTML = html;
}
async function saveBatch(fileType) {
const config = {
store: { inputId: 'store-file-input', btnId: 'btn-save-store' },
factory: { inputId: 'factory-file-input', btnId: 'btn-save-factory', startId: 'hm-start-date', endId: 'hm-end-date' },
};
const cfg = config[fileType];
const input = document.getElementById(cfg.inputId);
if (!input || !input.files.length) { alert('请先上传文件'); return; }
const btn = document.getElementById(cfg.btnId);
btn.disabled = true;
btn.textContent = '\u23f3 保存中...';
const formData = new FormData();
formData.append('file_type', fileType);
formData.append('file', input.files[0]);
formData.append('brand', '鸿蒙');
if (cfg.startId) {
formData.append('period_start', document.getElementById(cfg.startId).value || '');
formData.append('period_end', document.getElementById(cfg.endId).value || '');
}
try {
const res = await fetch(window.API_BASE + '/analysis/save-batch', { method: 'POST', body: formData });
const data = await res.json();
if (data.status === 'success') {
btn.textContent = '\u2705 已保存 (' + (data.data.batch_no || '') + ')';
btn.style.background = '#f6ffed';
btn.style.borderColor = '#b7eb8f';
btn.style.color = '#52c41a';
loadBatchOptions();
} else {
throw new Error(data.detail || '保存失败');
}
} catch (e) {
console.error('保存批次失败:', e);
btn.textContent = '\u274c 保存失败';
btn.style.background = '#fff2f0';
btn.style.borderColor = '#ffccc7';
btn.style.color = '#f5222d';
btn.disabled = false;
}
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
</script> </script>
<script src="./static/js/auth.js"></script> <script src="./static/js/auth.js"></script>
</body> </body>
......
...@@ -21,7 +21,6 @@ ...@@ -21,7 +21,6 @@
<a class="nav-item" href="./analysis">问界生态系数分析</a> <a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./strategy">策略效果盯防(开发中)</a> <a class="nav-item" href="./strategy">策略效果盯防(开发中)</a>
<a class="nav-item" href="./import">数据导入</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
......
...@@ -16,7 +16,6 @@ ...@@ -16,7 +16,6 @@
<a class="nav-item" href="./analysis">问界生态系数分析</a> <a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item" href="./strategy">策略效果盯防(开发中)</a> <a class="nav-item" href="./strategy">策略效果盯防(开发中)</a>
<a class="nav-item" href="./import">数据导入</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
...@@ -83,7 +82,8 @@ ...@@ -83,7 +82,8 @@
<script src="./static/js/common.js"></script> <script src="./static/js/common.js"></script>
<script src="./static/js/auth.js"></script> <script src="./static/js/auth.js"></script>
<script> <script>
const ODS_FILTER = item => item.task_id.includes('ods'); // 只匹配 ODS 同步任务:manual_ods_sync / scheduler_ods_sync / auto_ods_sync
const ODS_FILTER = item => /_ods_sync$/.test(item.task_id);
document.addEventListener('DOMContentLoaded', async () => { document.addEventListener('DOMContentLoaded', async () => {
try { try {
......
...@@ -191,7 +191,6 @@ ...@@ -191,7 +191,6 @@
<a class="nav-item" href="./analysis">问界生态系数分析</a> <a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item active" href="./strategy">策略效果盯防(开发中)</a> <a class="nav-item active" href="./strategy">策略效果盯防(开发中)</a>
<a class="nav-item" href="./import">数据导入</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
......
...@@ -199,7 +199,6 @@ ...@@ -199,7 +199,6 @@
<a class="nav-item" href="./analysis">问界生态系数分析</a> <a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item active" href="./strategy">策略效果盯防(开发中)</a> <a class="nav-item active" href="./strategy">策略效果盯防(开发中)</a>
<a class="nav-item" href="./import">数据导入</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
......
...@@ -199,7 +199,6 @@ ...@@ -199,7 +199,6 @@
<a class="nav-item" href="./analysis">问界生态系数分析</a> <a class="nav-item" href="./analysis">问界生态系数分析</a>
<a class="nav-item" href="./harmony">鸿蒙生态分析</a> <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
<a class="nav-item active" href="./strategy">策略效果盯防</a> <a class="nav-item active" href="./strategy">策略效果盯防</a>
<a class="nav-item" href="./import">数据导入</a>
</nav> </nav>
<div class="user-info" id="user-info">管理员</div> <div class="user-info" id="user-info">管理员</div>
</header> </header>
......
...@@ -67,6 +67,25 @@ async def lifespan(app: FastAPI): ...@@ -67,6 +67,25 @@ async def lifespan(app: FastAPI):
await asyncio.to_thread(StrategyService.ensure_result_table) await asyncio.to_thread(StrategyService.ensure_result_table)
except Exception as e: except Exception as e:
print(f"[!] Failed to create strategy result table: {e}") print(f"[!] Failed to create strategy result table: {e}")
# 清理启动前卡住的 running 状态 ETL 历史记录
try:
from sqlalchemy import text
from app.db.session import SessionLocal
db = SessionLocal()
try:
result = db.execute(text(
"UPDATE _etl_history SET status = 'failed', "
"end_time = NOW(), result_info = 'Server restarted, task interrupted' "
"WHERE status = 'running'"
))
db.commit()
stuck_count = getattr(result, 'rowcount', 0)
if stuck_count:
print(f"[*] Cleaned up {stuck_count} stuck ETL history record(s) (running -> failed)")
finally:
db.close()
except Exception as e:
print(f"[!] Failed to clean up stuck ETL history: {e}")
# 启动定时任务调度器 # 启动定时任务调度器
await SchedulerManager.start() await SchedulerManager.start()
yield yield
...@@ -133,7 +152,6 @@ PAGE_ROUTES = { ...@@ -133,7 +152,6 @@ PAGE_ROUTES = {
"/strategy": "strategy.html", "/strategy": "strategy.html",
"/strategy/detail": "strategy_detail.html", "/strategy/detail": "strategy_detail.html",
"/strategy/info": "strategy_info.html", "/strategy/info": "strategy_info.html",
"/import": "data_import.html",
} }
......
# -*- 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)
# -*- coding: utf-8 -*-
"""
文件名: tests/image_to_excel.py
职责: 将表格截图转为 Excel 文件。支持两种引擎:
1. paddle(默认,推荐)—— PaddleOCR + PP-Structure,本地 OCR + 表格结构识别
2. llm —— 调用 Qwen VL 视觉大模型解析(需要 API Key, 适用于复杂/非标准表格)
用法:
python tests/image_to_excel.py <image_path> # 默认 PaddleOCR
python tests/image_to_excel.py <image_path> --engine paddle # 显式指定 PaddleOCR
python tests/image_to_excel.py <image_path> --engine llm --api-key xxx # 使用 LLM
python tests/image_to_excel.py <image_path> --output output.xlsx
python tests/image_to_excel.py <image_path> --engine llm --split 3 # LLM 长图分片模式
"""
import os
import sys
import json
import re
import io
import base64
import asyncio
import argparse
import logging
from pathlib import Path
import httpx
import pandas as pd
from PIL import Image
# 确保项目根目录在 Python 路径中
_BASE_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(_BASE_DIR))
from app.core.config import settings
logger = logging.getLogger("image_to_excel")
# 默认缩放参数:最长边不超过此值,JPEG 质量
DEFAULT_MAX_SIZE = 2048
DEFAULT_QUALITY = 85
# =============================================================================
# 通用工具函数
# =============================================================================
def _normalize_cell(value):
"""清理 OCR 识别的单元格文本:去掉多余空格/换行,尝试保留数字类型。"""
if value is None or (isinstance(value, float) and pd.isna(value)):
return None
s = str(value).strip()
# 合并多余空白
s = re.sub(r"\s+", " ", s)
if s == "":
return None
# 尝试转数字
try:
if "." in s:
return float(s)
return int(s)
except ValueError:
pass
return s
def _write_table_to_excel(table_data: dict, output_path: str, sheet_name: str = "Sheet1"):
"""将 table_data (headers + rows) 写入 Excel 并自适应列宽。"""
headers = table_data.get("headers", [])
rows = table_data.get("rows", [])
if not headers and not rows:
raise ValueError("表格数据为空,无法写入 Excel")
# 如果没有表头但有数据行,生成默认列名
if not headers and rows:
max_cols = max(len(r) for r in rows)
headers = [f"列{i+1}" for i in range(max_cols)]
elif headers:
max_cols = len(headers)
else:
max_cols = 0
# 补齐不等长的行
padded_rows = []
for r in rows:
if len(r) < max_cols:
r = list(r) + [None] * (max_cols - len(r))
elif len(r) > max_cols:
r = r[:max_cols]
# 规范化每个单元格
r = [_normalize_cell(v) for v in r]
padded_rows.append(r)
df = pd.DataFrame(padded_rows, columns=headers)
with pd.ExcelWriter(output_path, engine="openpyxl") as writer:
df.to_excel(writer, index=False, sheet_name=sheet_name)
worksheet = writer.sheets[sheet_name]
for column in worksheet.columns:
max_length = 0
col_letter = column[0].column_letter
for cell in column:
try:
length = len(str(cell.value)) if cell.value is not None else 0
if length > max_length:
max_length = length
except Exception:
pass
adjusted = min(max_length + 2, 40)
worksheet.column_dimensions[col_letter].width = max(adjusted, 8)
return output_path
# =============================================================================
# PaddleOCR + PP-Structure 引擎(推荐,本地 OCR 表格识别)
# =============================================================================
def _call_paddle_structure(image_path: str) -> list:
"""
使用 PaddleOCR PP-Structure 识别图片中的表格。
返回 list[dict],每个 dict 为 {"headers": [...], "rows": [[...], ...]}。
一张图片可能包含多个表格,每个表格对应 Excel 的一个 sheet。
"""
from paddleocr import PPStructureV3
# 禁用 oneDNN,避免 Windows + Python 3.13 + Paddle 3.3 的 PIR 算子 bug
# NotImplementedError: ConvertPirAttribute2RuntimeAttribute not support
# [pir::ArrayAttribute<pir::DoubleAttribute>] at onednn_instruction.cc:118
import paddle
paddle.set_flags({"FLAGS_use_mkldnn": False})
path = Path(image_path)
if not path.exists():
raise FileNotFoundError(f"图片不存在: {image_path}")
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()
# 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"]
if not tables:
raise RuntimeError("未在图片中检测到表格,请确认图片包含清晰的表格区域")
print(f" [检测] 发现 {len(tables)} 个表格")
all_table_data = []
for i, tbl in enumerate(tables):
html = tbl.get("res", {}).get("html", "")
if not html:
print(f" [表 {i+1}] 跳过:无 HTML 输出")
continue
# 解析 HTML 表格为 DataFrame
try:
dfs: list[pd.DataFrame] = pd.read_html(io.StringIO(html))
if not dfs:
print(f" [表 {i+1}] 跳过:HTML 解析失败")
continue
df = dfs[0]
except Exception as e:
print(f" [表 {i+1}] HTML 解析失败: {e}")
continue
# 用第一行作为表头
headers = [str(c) for c in df.columns.tolist()]
rows = df.values.tolist()
# 如果第一行看起来像是表头(非纯数字),保留为 headers
# 否则可能是无表头表格,把第一行作为数据
all_table_data.append({"headers": headers, "rows": rows})
print(f" [表 {i+1}] {len(rows)} 行 x {len(headers)} 列")
if not all_table_data:
raise RuntimeError("虽然检测到表格区域,但无法解析表格内容")
return all_table_data
def _save_paddle_tables(all_table_data: list, output_path: str):
"""将 PP-Structure 返回的多个表格写入 Excel(多个 sheet)。"""
if len(all_table_data) == 1:
_write_table_to_excel(all_table_data[0], output_path, "Sheet1")
print(f"[+] 已保存: {output_path}")
return output_path
# 多个表格:每个表格一个 sheet
with pd.ExcelWriter(output_path, engine="openpyxl") as writer:
for i, tbl in enumerate(all_table_data):
headers = tbl.get("headers", [])
rows = tbl.get("rows", [])
sheet_name = f"Table_{i+1}"
if not headers and rows:
max_cols = max(len(r) for r in rows)
headers = [f"列{j+1}" for j in range(max_cols)]
padded_rows = []
max_cols = len(headers)
for r in rows:
if len(r) < max_cols:
r = list(r) + [None] * (max_cols - len(r))
elif len(r) > max_cols:
r = r[:max_cols]
r = [_normalize_cell(v) for v in r]
padded_rows.append(r)
df = pd.DataFrame(padded_rows, columns=headers)
df.to_excel(writer, index=False, sheet_name=sheet_name)
print(f"[+] 已保存: {output_path}({len(all_table_data)} 个 Sheet)")
return output_path
# =============================================================================
# LLM 视觉模型引擎(备选,适用于复杂/非标准表格)
# =============================================================================
def _preprocess_image(image_path: str, max_size: int = DEFAULT_MAX_SIZE,
quality: int = DEFAULT_QUALITY) -> tuple:
"""
预处理图片:缩放至 max_size 以内,转 JPEG 压缩以减少 base64 体积。
返回 (base64_data_uri, mime_type, (orig_w, orig_h), (new_w, new_h))
"""
path = Path(image_path)
if not path.exists():
raise FileNotFoundError(f"图片不存在: {image_path}")
img = Image.open(path)
orig_w, orig_h = img.size
# 等比缩放
if max(orig_w, orig_h) > max_size:
ratio = max_size / max(orig_w, orig_h)
new_w, new_h = int(orig_w * ratio), int(orig_h * ratio)
img = img.resize((new_w, new_h), Image.LANCZOS)
else:
new_w, new_h = orig_w, orig_h
# 转 JPEG 压缩输出(PNG 转 JPEG 大幅减小体积)
buf = io.BytesIO()
# 如果原图是 RGBA,填充白色背景后转 RGB
if img.mode in ("RGBA", "LA", "P"):
background = Image.new("RGB", img.size, (255, 255, 255))
if img.mode == "P":
img = img.convert("RGBA")
background.paste(img, mask=img.split()[-1] if img.mode == "RGBA" else None)
img = background
elif img.mode != "RGB":
img = img.convert("RGB")
img.save(buf, format="JPEG", quality=quality)
img.close()
encoded = base64.b64encode(buf.getvalue()).decode("utf-8")
size_kb = len(buf.getvalue()) / 1024
return f"data:image/jpeg;base64,{encoded}", "image/jpeg", (orig_w, orig_h), (new_w, new_h), size_kb
def _extract_json(text: str) -> str:
"""从 LLM 返回文本中提取 JSON,去除 Markdown 代码块标记并尽量容错。"""
text = text.strip()
# 去除 Markdown ```json ... ``` 或 ``` ... ``` 包裹
if text.startswith("```"):
first_newline = text.find("\n")
if first_newline != -1:
text = text[first_newline + 1:]
else:
text = text[3:]
text = re.sub(r"\n?```\s*$", "", text).strip()
# 如果 LLM 在 JSON 前后加了说明文字,尝试提取第一个 JSON 对象
brace_start = text.find("{")
brace_end = text.rfind("}")
if brace_start != -1 and brace_end != -1 and brace_end > brace_start:
text = text[brace_start:brace_end + 1]
return text
async def _call_vision_llm(image_path: str, max_size: int = DEFAULT_MAX_SIZE,
quality: int = DEFAULT_QUALITY,
api_url: str = "", api_key: str = "", model: str = "") -> dict:
"""
调用 VL 模型提取图片中的表格为 JSON。
自动缩放图片以满足 API 长度限制。
"""
api_url = api_url or f"{settings.LLM_QWEN_BASE_URL}/chat/completions"
api_key = api_key or settings.LLM_QWEN_API_KEY
model = model or settings.LLM_QWEN_VISION_MODEL
if not api_key:
raise RuntimeError("API Key 未设置,请通过 --api-key 参数或 LLM_QWEN_API_KEY 环境变量提供")
data_uri, mime_type, (ow, oh), (nw, nh), size_kb = _preprocess_image(image_path, max_size, quality)
if (ow, oh) != (nw, nh):
print(f" [缩放] {ow}x{oh} -> {nw}x{nh}, base64={size_kb:.0f}KB")
else:
print(f" [图片] {ow}x{oh}, base64={size_kb:.0f}KB")
prompt = """你是一名数据录入专家。请仔细观察图片中的表格,将表头和每一行数据以 JSON 格式输出。
要求:
1. 数字保持为数字类型(如 100, 0.5),不要加引号
2. 百分比保持文本形式(如 "23.5%")
3. 空单元格使用 null
4. 不要添加任何解释文字
JSON 格式:
{
"headers": ["列1", "列2", ...],
"rows": [
[值1, 值2, ...],
[值1, 值2, ...]
]
}
仅返回 JSON,不要 Markdown 代码块。"""
try:
client_kwargs = {"timeout": 180.0}
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}")
async with httpx.AsyncClient(**client_kwargs) as client:
response = await client.post(
api_url,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"model": model,
"messages": [
{"role": "system", "content": "You are a data extraction assistant. Return JSON only."},
{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": data_uri}},
{"type": "text", "text": prompt},
],
},
],
"temperature": 0.1,
"max_tokens": 8192,
},
timeout=1800.0,
)
if response.status_code != 200:
logger.error(f"Vision LLM API Error: {response.status_code} - {response.text}")
raise RuntimeError(f"API 请求失败: {response.status_code}")
result = response.json()
content = result["choices"][0]["message"]["content"]
content = _extract_json(content)
return json.loads(content)
except json.JSONDecodeError as e:
logger.error(f"Failed to parse LLM response as JSON. Raw content:\n{content}")
raise RuntimeError(f"LLM 返回内容不是合法 JSON: {e}")
except Exception as e:
logger.error(f"Failed to call vision LLM: {e}")
raise
def _split_image(image_path: str, n_chunks: int, max_size: int = DEFAULT_MAX_SIZE,
quality: int = DEFAULT_QUALITY) -> list:
"""
将长图纵向切成 n_chunks 段,每段有 15% 重叠以确保行不被截断。
返回 [(data_uri, mime_type, chunk_index), ...]
"""
img = Image.open(image_path)
w, h = img.size
chunk_h = h // n_chunks
overlap = int(chunk_h * 0.15)
chunks = []
for i in range(n_chunks):
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))
chunk_img = img.crop((0, y1, w, y2))
if max(chunk_img.size) > max_size:
ratio = max_size / max(chunk_img.size)
nw, nh = int(chunk_img.width * ratio), int(chunk_img.height * ratio)
chunk_img = chunk_img.resize((nw, nh), Image.LANCZOS)
buf = io.BytesIO()
if chunk_img.mode in ("RGBA", "LA", "P"):
bg = Image.new("RGB", chunk_img.size, (255, 255, 255))
if chunk_img.mode == "P":
chunk_img = chunk_img.convert("RGBA")
bg.paste(chunk_img, mask=chunk_img.split()[-1] if chunk_img.mode == "RGBA" else None)
chunk_img = bg
elif chunk_img.mode != "RGB":
chunk_img = chunk_img.convert("RGB")
chunk_img.save(buf, format="JPEG", quality=quality)
chunk_img.close()
encoded = base64.b64encode(buf.getvalue()).decode("utf-8")
size_kb = len(buf.getvalue()) / 1024
data_uri = f"data:image/jpeg;base64,{encoded}"
chunks.append((data_uri, i, y1, y2, size_kb))
print(f" [分片 {i + 1}/{n_chunks}] y={y1}-{y2}, base64={size_kb:.0f}KB")
img.close()
return chunks
async def _call_vision_llm_split(image_path: str, n_chunks: int,
max_size: int = DEFAULT_MAX_SIZE,
quality: int = DEFAULT_QUALITY,
api_url: str = "", api_key: str = "", model: str = "") -> dict:
"""
分片模式:将长图切成 n_chunks 段分别识别,合并结果(去重重叠行)。
"""
api_url = api_url or f"{settings.LLM_QWEN_BASE_URL}/chat/completions"
api_key = api_key or settings.LLM_QWEN_API_KEY
model = model or settings.LLM_QWEN_VISION_MODEL
if not api_key:
raise RuntimeError("API Key 未设置,请通过 --api-key 参数或 LLM_QWEN_API_KEY 环境变量提供")
chunks = _split_image(image_path, n_chunks, max_size, quality)
prompt = """你是一名数据录入专家。这是表格图片的一部分(可能有部分行与上一段重叠)。
请提取这一部分中的所有行数据,第一行是表头(如果图片第一部分有表头的话,否则直接是数据行)。
JSON 格式:
{
"has_header": true,
"headers": ["列1", "列2", ...],
"rows": [
[值1, 值2, ...],
[值1, 值2, ...]
]
}
仅返回 JSON,不要 Markdown 代码块。"""
all_headers = []
all_rows = []
async with httpx.AsyncClient(timeout=180.0) as client:
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_chunks}] 发送请求...")
response = await client.post(
api_url,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"model": model,
"messages": [
{"role": "system", "content": "You are a data extraction assistant. Return JSON only."},
{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": data_uri}},
{"type": "text", "text": chunk_prompt},
],
},
],
"temperature": 0.1,
"max_tokens": 8192,
},
)
if response.status_code != 200:
logger.error(f"Chunk {idx} API Error: {response.status_code} - {response.text}")
raise RuntimeError(f"分片 {idx} API 请求失败: {response.status_code}")
result = response.json()
content = result["choices"][0]["message"]["content"]
content = _extract_json(content)
chunk_data = json.loads(content)
if is_first and chunk_data.get("has_header", True):
all_headers = chunk_data.get("headers", [])
chunk_rows = chunk_data.get("rows", [])
if idx > 0 and all_rows and chunk_rows:
last_row = tuple(str(v) for v in all_rows[-1])
skip = 0
for r in chunk_rows:
if tuple(str(v) for v in r) == last_row:
skip += 1
elif skip > 0:
break
if skip > 0:
print(f" [去重] 分片 {idx + 1} 跳过前 {skip} 行")
chunk_rows = chunk_rows[skip:]
all_rows.extend(chunk_rows)
print(f" [分片 {idx + 1}] 提取 {len(chunk_rows)} 行")
return {"headers": all_headers, "rows": all_rows}
# =============================================================================
# 主入口
# =============================================================================
def main():
parser = argparse.ArgumentParser(
description="图片转 Excel —— 将表格截图识别为 Excel 文件",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
引擎说明:
paddle PaddleOCR + PP-Structure(默认),本地 OCR 引擎,
对密集数字表格更稳定、更准确、免费无限次使用。
llm Qwen VL 等视觉大模型,适合非标准/复杂排版表格,
需要 API Key,有调用成本。
示例:
python image_to_excel.py table.png
python image_to_excel.py table.png --output result.xlsx
python image_to_excel.py table.png --engine llm --api-key sk-xxx
""",
)
parser.add_argument("image", help="表格截图路径")
parser.add_argument("--engine", choices=["paddle", "llm"], default="paddle",
help="识别引擎:paddle(PaddleOCR,默认), llm(视觉大模型)")
parser.add_argument("--output", "-o", default=None,
help="输出路径,默认 <image>.xlsx")
# LLM 专用参数
parser.add_argument("--max-size", type=int, default=DEFAULT_MAX_SIZE,
help=f"LLM 模式:图片最长边缩放上限(像素),默认 {DEFAULT_MAX_SIZE}")
parser.add_argument("--quality", "-q", type=int, default=DEFAULT_QUALITY,
help=f"LLM 模式:JPEG 压缩质量 1-100,默认 {DEFAULT_QUALITY}")
parser.add_argument("--split", type=int, default=0, metavar="N",
help="LLM 模式:将长图纵向切成 N 段分别识别后合并")
parser.add_argument("--api-url", default="",
help="LLM 模式:API 完整地址。不指定则使用 LLM_QWEN_BASE_URL")
parser.add_argument("--api-key", default="",
help="LLM 模式:API Key。不指定则使用 LLM_QWEN_API_KEY")
parser.add_argument("--model", "-m", default="",
help="LLM 模式:模型名称。不指定则使用 LLM_QWEN_VISION_MODEL")
args = parser.parse_args()
output_path = args.output or str(Path(args.image).with_suffix(".xlsx"))
# ── PaddleOCR 引擎 ──
if args.engine == "paddle":
all_table_data = _call_paddle_structure(args.image)
rows_count = sum(len(t.get("rows", [])) for t in all_table_data)
cols_count = max(len(t.get("headers", [])) for t in all_table_data)
_save_paddle_tables(all_table_data, output_path)
print(f"[+] 引擎: PaddleOCR PP-Structure\n 表格数: {len(all_table_data)}\n 总行数: {rows_count}")
# ── LLM 引擎 ──
else:
api_url = args.api_url
api_key = args.api_key
model = args.model
print(f"[*] 调用 {model or settings.LLM_QWEN_VISION_MODEL} 解析图片: {args.image}")
if api_url:
print(f"[*] API: {api_url}")
if args.split > 0:
print(f"[*] 分片模式:{args.split} 段")
table_data = asyncio.run(_call_vision_llm_split(
args.image, args.split, max_size=args.max_size, quality=args.quality,
api_url=api_url, api_key=api_key, model=model,
))
else:
table_data = asyncio.run(_call_vision_llm(
args.image, max_size=args.max_size, quality=args.quality,
api_url=api_url, api_key=api_key, model=model,
))
rows_count = len(table_data.get("rows", []))
cols_count = len(table_data.get("headers", []))
print(f"[*] 识别到 {rows_count} 行 {cols_count} 列数据")
_write_table_to_excel(table_data, output_path)
print(f"[+] 已保存: {output_path}\n 模型: {model or settings.LLM_QWEN_VISION_MODEL}\n 行数: {rows_count}")
if __name__ == "__main__":
main()
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!