This commit is contained in:
HuangHai
2026-01-15 11:46:59 +08:00
parent f038929687
commit 8cbcca472b
11 changed files with 178 additions and 41 deletions

View File

@@ -6,7 +6,7 @@ import sys
import json
import time
from datetime import datetime
from Apps.YeLiTe.Kit import take_screenshot, clean_station_name, get_image_content_md5, find_template
from Apps.YeLiTe.Kit import take_screenshot, clean_station_name, get_image_content_md5, detect_price_info_container_cv
from Apps.YeLiTe.ReadImageKit import ReadImageKit
from Apps.YeLiTe.Service import YiLaiTeService
from Apps.YeLiTe.Config.Setting import (
@@ -107,6 +107,7 @@ class YiLaiTeCrawler(BaseCrawler):
name = station.get('name')
address = station.get('address')
distance = station.get('distance')
point = station.get('point')
if not name or not point:
@@ -182,7 +183,9 @@ class YiLaiTeCrawler(BaseCrawler):
logger.info(f"成功进入详情页: {name}")
# --- 新增:点击“阶段性电价”按钮以获取完整电价列表 ---
dqdf_pos = find_template(detail_shot, "dqdf.jpg")
# 使用 OCR 探测价格入口
dqdf_pos = detect_price_info_container_cv(detail_shot)
detail_shots = []
if dqdf_pos:
@@ -219,7 +222,7 @@ class YiLaiTeCrawler(BaseCrawler):
# --------------------------------------------------
# 启动后台任务处理详情页
task = asyncio.create_task(self.analyze_detail_background(name, detail_shots, address=address))
task = asyncio.create_task(self.analyze_detail_background(name, detail_shots, address=address, distance=distance))
background_tasks.append(task)
processed_count += 1
@@ -268,7 +271,7 @@ class YiLaiTeCrawler(BaseCrawler):
return processed_count
async def analyze_detail_background(self, station_name, image_paths, address=None):
async def analyze_detail_background(self, station_name, image_paths, address=None, distance=None):
"""
后台异步分析详情页 (支持多张截图合并)
"""
@@ -304,8 +307,8 @@ class YiLaiTeCrawler(BaseCrawler):
unique_prices.sort(key=lambda x: x.get('start', '00:00'))
if unique_prices:
await self.service.process_price_detail_data(station_name, unique_prices, address=address)
logger.info(f"场站 {station_name} 价格分析完成并入库 (记录数: {len(unique_prices)}, 地址: {address})")
await self.service.process_price_detail_data(station_name, unique_prices, address=address, distance=distance)
logger.info(f"场站 {station_name} 价格分析完成并入库 (记录数: {len(unique_prices)}, 地址: {address}, 距离: {distance})")
else:
logger.warning(f"场站 {station_name} 未识别到价格信息")

View File

@@ -270,6 +270,45 @@ def draw_rectangles(image_path, points, output_path=None):
logger.error(f"绘制矩形框失败: {e}")
return image_path
from Util.EasyOcrKit import get_easyocr_reader
# 预加载 EasyOCR Reader (单例模式)
def get_ocr_reader():
return get_easyocr_reader(gpu=True)
def detect_price_info_container_cv(image_path):
"""
使用 OCR 精准定位详情页中的价格入口文本(“阶段性电价”)。
返回: [x1, y1, x2, y2] 绝对像素坐标,如果未找到则返回 None
"""
img = read_image(image_path)
if img is None:
return None
h, w = img.shape[:2]
keywords = ['阶段性电价']
try:
reader = get_ocr_reader()
results = reader.read_text(img)
for (quad, text, prob) in results:
if any(kw in text for kw in keywords) and prob >= 0.5:
pts = np.array(quad).astype(int)
x_min = np.min(pts[:, 0])
y_min = np.min(pts[:, 1])
x_max = np.max(pts[:, 0])
y_max = np.max(pts[:, 1])
center_x = (x_min + x_max) // 2
center_y = (y_min + y_max) // 2
logger.info(f"[OCR识别] 找到文本: '{text}', 置信度: {prob:.4f}, 中心坐标: ({center_x}, {center_y})")
return (center_x, center_y)
except Exception as e:
logger.error(f"OCR 识别发生异常: {e}")
return None
def setup_logger(name, log_file=None, clear_old_log=False):
"""
配置日志,支持同时输出到控制台和文件。

View File

@@ -153,9 +153,10 @@ class ReadImageKit:
每个对象包含:
- "name": 场站名称 (仅提取名称文字)
- "address": 场站地址 (通常在名称下方,请完整提取地址文字)
- "distance": 距离 (如 "1.2km", "800m" 等,如果存在请提取)
- "is_valid": true/false (是否为真实的场站卡片)
注意:仅提取名称和地址,不要包含距离或价格。
注意:仅提取名称、地址和距离,不要包含价格。
"""
else:
# 如果 CV 没检测到,退回到纯 VLM 模式
@@ -165,6 +166,7 @@ class ReadImageKit:
输出格式为 JSON 数组,每个对象包含:
- "name": 场站名称
- "address": 场站地址 (请仔细识别并提取场站的详细地址信息)
- "distance": 距离 (如 "1.2km", "800m" 等,如果存在请提取)
- "point": 场站卡片的中心点击坐标 [x, y]
- "bbox": 场站卡片的边界框 [x1, y1, x2, y2]
"""
@@ -187,6 +189,7 @@ class ReadImageKit:
final_stations.append({
"name": res.get("name"),
"address": res.get("address"),
"distance": res.get("distance"),
"point": [(bbox[0] + bbox[2]) // 2, (bbox[1] + bbox[3]) // 2],
"bbox": bbox
})

View File

@@ -90,16 +90,71 @@ class YiLaiTeService:
except Exception as e:
logger.error(f"更新任务结束日志失败: {e}")
async def process_price_detail_data(self, station_name, hourly_schedule, address=None) -> bool:
async def process_price_detail_data(self, station_name, prices, address=None, distance=None) -> bool:
"""
直接保存已处理好的小时段价格数据
保存场站数据:名称、地址、24小时价格计划、距离
"""
if not station_name or not hourly_schedule:
if not station_name or not prices:
return False
station_hash = self.get_hash(station_name)
now = datetime.now()
# 1. 预处理价格:生成 24 小时的价格映射
hourly_schedule = [None] * 24
for p in prices:
try:
start_str = p.get('start') or '00:00'
end_str = p.get('end') or '00:00'
# 解析小时
start_hour = int(start_str.split(':')[0])
end_hour = int(end_str.split(':')[0])
# 处理 00:00 作为结束时间
if end_hour == 0 and start_hour != 0:
end_hour = 24
elif end_hour == 0 and start_hour == 0 and len(prices) == 1:
end_hour = 24
# 如果跨天
if end_hour < start_hour:
end_hour += 24
price_val = self._to_float(p.get('price'))
curr = start_hour
while curr < end_hour:
hour_idx = curr % 24
hourly_schedule[hour_idx] = {
"start": f"{hour_idx:02d}:00",
"end": f"{(hour_idx + 1):02d}:00",
"price": price_val
}
curr += 1
except Exception as e:
logger.error(f"解析价格时段失败: {p}, error: {e}")
# 2. 兜底填充 (补全 24 小时)
last_valid = None
for item in hourly_schedule:
if item:
last_valid = item
break
if last_valid:
for i in range(24):
if hourly_schedule[i] is None:
new_item = last_valid.copy()
new_item["start"] = f"{i:02d}:00"
new_item["end"] = f"{(i+1):02d}:00"
hourly_schedule[i] = new_item
else:
last_valid = hourly_schedule[i]
else:
logger.warning(f"场站 {station_name} 未能生成有效的 24 小时价格表")
async with await self.db.get_session() as session:
# 1. 保存 Profile (如果不存在)
profile_id = self.generate_id()
@@ -122,7 +177,27 @@ class YiLaiTeService:
schedule_json=hourly_schedule,
valid_start_time=now
)
# 3. 保存状态 (记录距离和当前价格)
current_hour = now.hour
current_price_info = hourly_schedule[current_hour] or {}
status_id = self.generate_id()
await self.station_status_model.save(
session=session,
id=status_id,
station_hash=station_hash,
total_piles=None,
free_piles=None,
piles_detail_json=None,
current_price=current_price_info.get('price'),
distance=distance,
valid_start_time=now
)
await session.commit()
logger.info(f"成功保存驿来特场站数据: {station_name} | 距离: {distance} | 价格条数: {len([x for x in hourly_schedule if x])}")
return True
async def process_station_list_vl(self, image_path, json_metadata, device_info=None, max_count=None) -> list:

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB