File size: 24,983 Bytes
fbd9d3d e5e756a fbd9d3d e5e756a fbd9d3d bb96b1a cc826a1 e5e756a fbd9d3d bb96b1a ae8b600 fbd9d3d bb96b1a fbd9d3d bb96b1a fbd9d3d e5e756a fbd9d3d e5e756a fbd9d3d bb96b1a fbd9d3d bb96b1a fbd9d3d bb96b1a fbd9d3d ae8b600 fbd9d3d bb96b1a fbd9d3d ae8b600 fbd9d3d ae8b600 fbd9d3d bb96b1a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 | """
内容提取核心逻辑
集成 run/log 服务,记录处理过程日志。
"""
import logging
import tempfile
from pathlib import Path
from typing import Optional, Dict, Any
from .extractors.xiaohongshu import XiaohongshuExtractor
from .extractors.weibo import WeiboExtractor
from plugins.ocr.core import get_ocr_service
from app.plugins.run_log import get_run_log_service, RunStatus
logger = logging.getLogger(__name__)
class ContentExtractorCore:
"""内容提取核心逻辑"""
def __init__(self):
self.xhs_extractor = XiaohongshuExtractor()
self.weibo_extractor = WeiboExtractor()
self.ocr_service = get_ocr_service()
def validate_url(self, url: str) -> dict:
"""
验证URL
Args:
url: 待验证的URL
Returns:
{
"valid": bool,
"source_type": str,
"error": str # 错误信息(如果无效)
}
"""
if not url or not url.strip():
return {
"valid": False,
"source_type": "unknown",
"error": "链接不能为空"
}
# 按平台逐个解析,避免把其他平台链接误判成小红书错误。
for extractor in (self.xhs_extractor, self.weibo_extractor):
result = extractor.parse_url(url)
if result["valid"]:
return {
"valid": True,
"source_type": result["source_type"],
"error": None
}
return {
"valid": False,
"source_type": "unknown",
"error": "无效或暂不支持的链接"
}
async def extract_with_run(
self,
url: str,
run_id: str,
include_ocr: bool = True,
cookies: Optional[dict] = None
) -> dict:
"""
提取内容,记录 run 事件
Args:
url: 内容链接
run_id: 运行 ID
include_ocr: 是否对图片进行OCR识别
cookies: Cookie(可选,用于应对反爬)
Returns:
{
"success": bool,
"title": str,
"content": str,
"raw_html": str,
"raw_text": str,
"normalized_content": str,
"images": list,
"images_text": str,
"source_type": str,
"error": str
}
"""
run_service = get_run_log_service()
# 1. 验证URL
run_service.add_event(
run_id=run_id,
stage="validate_url",
message=f"验证 URL: {url}",
)
validation = self.validate_url(url)
if not validation["valid"]:
run_service.add_event(
run_id=run_id,
stage="validate_url",
message=f"URL 验证失败: {validation['error']}",
level="error",
)
return {
"success": False,
"title": "",
"content": "",
"raw_html": "",
"raw_text": "",
"normalized_content": "",
"images": [],
"images_text": "",
"source_type": validation["source_type"],
"error": validation["error"]
}
source_type = validation["source_type"]
run_service.add_event(
run_id=run_id,
stage="validate_url",
message=f"URL 验证通过: {source_type}",
)
# 2. 根据来源类型选择提取器
if source_type == "xiaohongshu":
return await self._extract_xiaohongshu_with_run(url, run_id, include_ocr, cookies)
if source_type == "weibo":
return await self._extract_weibo_with_run(url, run_id, include_ocr, cookies)
else:
error_msg = f"不支持的内容来源: {source_type}"
run_service.add_event(
run_id=run_id,
stage="extract",
message=error_msg,
level="error",
)
return {
"success": False,
"title": "",
"content": "",
"raw_html": "",
"raw_text": "",
"normalized_content": "",
"images": [],
"images_text": "",
"source_type": source_type,
"error": error_msg
}
async def _extract_xiaohongshu_with_run(
self,
url: str,
run_id: str,
include_ocr: bool,
cookies: Optional[dict] = None
) -> dict:
"""提取小红书内容,记录 run 事件"""
run_service = get_run_log_service()
try:
# 1. 获取页面内容
run_service.add_event(
run_id=run_id,
stage="fetch_page",
message="获取页面内容",
)
page_result = await self.xhs_extractor.fetch_page(url, cookies)
if not page_result["success"]:
run_service.add_event(
run_id=run_id,
stage="fetch_page",
message=f"获取页面失败: {page_result['error']}",
level="error",
)
return {
"success": False,
"title": "",
"content": "",
"raw_html": "",
"raw_text": "",
"normalized_content": "",
"images": [],
"images_text": "",
"source_type": "xiaohongshu",
"error": page_result["error"]
}
raw_html = page_result.get("html", "")
run_service.add_event(
run_id=run_id,
stage="fetch_page",
message=f"获取页面成功: {len(raw_html)} 字符",
)
# 2. 解析页面内容
run_service.add_event(
run_id=run_id,
stage="parse_content",
message="解析页面内容",
)
content_result = self.xhs_extractor.parse_content(raw_html)
if not content_result["success"]:
run_service.add_event(
run_id=run_id,
stage="parse_content",
message=f"解析内容失败: {content_result['error']}",
level="error",
)
return {
"success": False,
"title": "",
"content": "",
"raw_html": raw_html,
"raw_text": "",
"normalized_content": "",
"images": [],
"images_text": "",
"source_type": "xiaohongshu",
"error": content_result["error"]
}
images = content_result.get("images", [])
run_service.add_event(
run_id=run_id,
stage="parse_content",
message=f"解析内容成功: {len(images)} 张图片",
)
# 3. OCR识别图片(如果需要)
images_text = ""
if include_ocr and images:
run_service.add_event(
run_id=run_id,
stage="ocr",
message=f"开始 OCR 识别: {len(images)} 张图片",
)
images_text = await self._ocr_images_with_run(
images,
self.xhs_extractor.download_image,
run_id,
)
run_service.add_event(
run_id=run_id,
stage="ocr",
message=f"OCR 识别完成: {len(images_text)} 字符",
)
# 4. 格式化结果
run_service.add_event(
run_id=run_id,
stage="format",
message="格式化结果",
)
return {
"success": True,
"title": content_result.get("title", ""),
"content": content_result.get("content", ""),
"raw_html": raw_html,
"raw_text": content_result.get("raw_text", ""),
"normalized_content": content_result.get("content", ""),
"images": images,
"images_text": images_text,
"source_type": "xiaohongshu",
"error": None
}
except Exception as e:
logger.error(f"提取小红书内容失败: {e}", exc_info=True)
run_service.add_event(
run_id=run_id,
stage="extract",
message=f"提取异常: {str(e)}",
level="error",
)
return {
"success": False,
"title": "",
"content": "",
"raw_html": "",
"raw_text": "",
"normalized_content": "",
"images": [],
"images_text": "",
"source_type": "xiaohongshu",
"error": str(e)
}
async def _extract_weibo_with_run(
self,
url: str,
run_id: str,
include_ocr: bool,
cookies: Optional[dict] = None
) -> dict:
"""提取微博内容,记录 run 事件"""
run_service = get_run_log_service()
try:
# 1. 获取页面内容
run_service.add_event(
run_id=run_id,
stage="fetch_page",
message="获取页面内容",
)
page_result = await self.weibo_extractor.fetch_page(url, cookies)
if not page_result["success"]:
run_service.add_event(
run_id=run_id,
stage="fetch_page",
message=f"获取页面失败: {page_result['error']}",
level="error",
)
return {
"success": False,
"title": "",
"content": "",
"raw_html": "",
"raw_text": "",
"normalized_content": "",
"images": [],
"images_text": "",
"source_type": "weibo",
"error": page_result["error"]
}
raw_html = page_result.get("html", "")
run_service.add_event(
run_id=run_id,
stage="fetch_page",
message=f"获取页面成功: {len(raw_html)} 字符",
)
# 2. 解析页面内容
run_service.add_event(
run_id=run_id,
stage="parse_content",
message="解析页面内容",
)
content_result = self.weibo_extractor.parse_content(raw_html)
if not content_result["success"]:
run_service.add_event(
run_id=run_id,
stage="parse_content",
message=f"解析内容失败: {content_result['error']}",
level="error",
)
return {
"success": False,
"title": "",
"content": "",
"raw_html": raw_html,
"raw_text": "",
"normalized_content": "",
"images": [],
"images_text": "",
"source_type": "weibo",
"error": content_result["error"]
}
images = content_result.get("images", [])
run_service.add_event(
run_id=run_id,
stage="parse_content",
message=f"解析内容成功: {len(images)} 张图片",
)
# 3. OCR识别图片(如果需要)
images_text = ""
if include_ocr and images:
run_service.add_event(
run_id=run_id,
stage="ocr",
message=f"开始 OCR 识别: {len(images)} 张图片",
)
images_text = await self._ocr_images_with_run(
images,
self.weibo_extractor.download_image,
run_id,
)
run_service.add_event(
run_id=run_id,
stage="ocr",
message=f"OCR 识别完成: {len(images_text)} 字符",
)
# 4. 格式化结果
run_service.add_event(
run_id=run_id,
stage="format",
message="格式化结果",
)
return {
"success": True,
"title": content_result.get("title", ""),
"content": content_result.get("content", ""),
"raw_html": raw_html,
"raw_text": content_result.get("raw_text", ""),
"normalized_content": content_result.get("content", ""),
"images": images,
"images_text": images_text,
"source_type": "weibo",
"error": None
}
except Exception as e:
logger.error(f"提取微博内容失败: {e}", exc_info=True)
run_service.add_event(
run_id=run_id,
stage="extract",
message=f"提取异常: {str(e)}",
level="error",
)
return {
"success": False,
"title": "",
"content": "",
"raw_html": "",
"raw_text": "",
"normalized_content": "",
"images": [],
"images_text": "",
"source_type": "weibo",
"error": str(e)
}
async def _ocr_images_with_run(self, image_urls: list, download_image, run_id: str) -> str:
"""对图片进行OCR识别,记录 run 事件"""
run_service = get_run_log_service()
if not image_urls:
run_service.add_event(
run_id=run_id,
stage="ocr",
message="跳过 OCR:页面未解析到可下载图片",
)
return ""
all_text = []
for idx, image_url in enumerate(image_urls[:5]): # 限制最多5张图片
try:
# 下载图片
run_service.add_event(
run_id=run_id,
stage="download_image",
message=f"下载图片 {idx + 1}: {image_url[:50]}...",
)
download_result = await download_image(image_url)
if not download_result["success"]:
run_service.add_event(
run_id=run_id,
stage="download_image",
message=f"下载图片失败: {download_result['error']}",
level="warning",
)
continue
# 保存到临时文件
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp_file:
tmp_file.write(download_result["data"])
tmp_path = tmp_file.name
try:
# 执行OCR识别
run_service.add_event(
run_id=run_id,
stage="ocr",
message=f"OCR 识别图片 {idx + 1}",
)
ocr_result = self.ocr_service.extract_text_from_file(tmp_path)
if ocr_result["success"] and ocr_result["text"]:
all_text.append(f"[图片{idx + 1}]\n{ocr_result['text']}")
run_service.add_event(
run_id=run_id,
stage="ocr",
message=f"OCR 识别成功: {len(ocr_result['text'])} 字符",
)
elif ocr_result["success"]:
run_service.add_event(
run_id=run_id,
stage="ocr",
message=f"OCR 未识别到文字: {image_url[:50]}...",
)
else:
run_service.add_event(
run_id=run_id,
stage="ocr",
message=f"OCR 识别失败: {ocr_result.get('error')}",
level="warning",
)
finally:
# 清理临时文件
Path(tmp_path).unlink(missing_ok=True)
except Exception as e:
logger.error(f"OCR识别图片失败: {e}")
run_service.add_event(
run_id=run_id,
stage="ocr",
message=f"OCR 识别异常: {str(e)}",
level="error",
)
continue
return "\n\n".join(all_text)
async def extract(
self,
url: str,
include_ocr: bool = True,
cookies: Optional[dict] = None
) -> dict:
"""
提取内容(兼容旧接口)
Args:
url: 内容链接
include_ocr: 是否对图片进行OCR识别
cookies: Cookie(可选,用于应对反爬)
Returns:
{
"success": bool,
"title": str,
"content": str,
"images_text": str, # 图片OCR识别的文本
"source_type": str,
"error": str # 错误信息(如果失败)
}
"""
# 1. 验证URL
validation = self.validate_url(url)
if not validation["valid"]:
return {
"success": False,
"title": "",
"content": "",
"images_text": "",
"source_type": validation["source_type"],
"error": validation["error"]
}
source_type = validation["source_type"]
# 2. 根据来源类型选择提取器
if source_type == "xiaohongshu":
return await self._extract_xiaohongshu(url, include_ocr, cookies)
if source_type == "weibo":
return await self._extract_weibo(url, include_ocr, cookies)
else:
return {
"success": False,
"title": "",
"content": "",
"images_text": "",
"source_type": source_type,
"error": f"不支持的内容来源: {source_type}"
}
async def _extract_xiaohongshu(
self,
url: str,
include_ocr: bool,
cookies: Optional[dict] = None
) -> dict:
"""提取小红书内容"""
try:
# 1. 获取页面内容
page_result = await self.xhs_extractor.fetch_page(url, cookies)
if not page_result["success"]:
return {
"success": False,
"title": "",
"content": "",
"images_text": "",
"source_type": "xiaohongshu",
"error": page_result["error"]
}
# 2. 解析页面内容
content_result = self.xhs_extractor.parse_content(page_result["html"])
if not content_result["success"]:
return {
"success": False,
"title": "",
"content": "",
"images_text": "",
"source_type": "xiaohongshu",
"error": content_result["error"]
}
# 3. OCR识别图片(如果需要)
images_text = ""
if include_ocr and content_result["images"]:
images_text = await self._ocr_images(
content_result["images"],
self.xhs_extractor.download_image,
)
return {
"success": True,
"title": content_result["title"],
"content": content_result["content"],
"images_text": images_text,
"source_type": "xiaohongshu",
"error": None
}
except Exception as e:
logger.error(f"提取小红书内容失败: {e}", exc_info=True)
return {
"success": False,
"title": "",
"content": "",
"images_text": "",
"source_type": "xiaohongshu",
"error": str(e)
}
async def _extract_weibo(
self,
url: str,
include_ocr: bool,
cookies: Optional[dict] = None
) -> dict:
"""提取微博内容。"""
try:
page_result = await self.weibo_extractor.fetch_page(url, cookies)
if not page_result["success"]:
return {
"success": False,
"title": "",
"content": "",
"images_text": "",
"source_type": "weibo",
"error": page_result["error"]
}
content_result = self.weibo_extractor.parse_content(page_result["html"])
if not content_result["success"]:
return {
"success": False,
"title": "",
"content": "",
"images_text": "",
"source_type": "weibo",
"error": content_result["error"]
}
images_text = ""
if include_ocr and content_result["images"]:
images_text = await self._ocr_images(
content_result["images"],
self.weibo_extractor.download_image,
)
return {
"success": True,
"title": content_result["title"],
"content": content_result["content"],
"images_text": images_text,
"source_type": "weibo",
"error": None
}
except Exception as e:
logger.error(f"提取微博内容失败: {e}", exc_info=True)
return {
"success": False,
"title": "",
"content": "",
"images_text": "",
"source_type": "weibo",
"error": str(e)
}
async def _ocr_images(self, image_urls: list, download_image) -> str:
"""对图片进行OCR识别"""
if not image_urls:
logger.info("跳过 OCR:页面未解析到可下载图片")
return ""
all_text = []
for idx, image_url in enumerate(image_urls[:5]): # 限制最多5张图片
try:
# 下载图片
download_result = await download_image(image_url)
if not download_result["success"]:
logger.warning(f"下载图片失败: {download_result['error']}")
continue
# 保存到临时文件
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp_file:
tmp_file.write(download_result["data"])
tmp_path = tmp_file.name
try:
# 执行OCR识别
ocr_result = self.ocr_service.extract_text_from_file(tmp_path)
if ocr_result["success"] and ocr_result["text"]:
all_text.append(f"[图片{idx + 1}]\n{ocr_result['text']}")
elif ocr_result["success"]:
logger.info(f"OCR 未识别到文字: {image_url}")
else:
logger.warning(f"OCR 识别失败: {ocr_result.get('error')}")
finally:
# 清理临时文件
Path(tmp_path).unlink(missing_ok=True)
except Exception as e:
logger.error(f"OCR识别图片失败: {e}")
continue
return "\n\n".join(all_text)
|