|
5 | 5 |
|
6 | 6 | from typing import Any, Dict, Optional |
7 | 7 |
|
8 | | -from llm_web_kit.simple import extract_content_from_main_html |
| 8 | +import httpx |
9 | 9 |
|
10 | | -from ..dependencies import get_inference_service, get_logger, get_settings |
| 10 | +from llm_web_kit.api.dependencies import (get_inference_service, get_logger, |
| 11 | + get_settings) |
| 12 | +from llm_web_kit.simple import extract_content_from_main_html |
11 | 13 |
|
12 | 14 | logger = get_logger(__name__) |
13 | 15 | settings = get_settings() |
@@ -37,8 +39,26 @@ async def parse_html( |
37 | 39 | ) -> Dict[str, Any]: |
38 | 40 | """解析 HTML 内容.""" |
39 | 41 | try: |
| 42 | + if not html_content and url: |
| 43 | + logger.info(f'HTML 内容为空,尝试从 URL 爬取: {url}') |
| 44 | + try: |
| 45 | + async with httpx.AsyncClient() as client: |
| 46 | + response = await client.post(settings.crawl_url, json={'url': url}, timeout=60) |
| 47 | + response.raise_for_status() |
| 48 | + data = response.json() |
| 49 | + html_content = data.get('html') |
| 50 | + if not html_content: |
| 51 | + raise ValueError('爬取成功,但未返回 HTML 内容') |
| 52 | + logger.info(f'URL 爬取成功,内容长度: {len(html_content)}') |
| 53 | + except httpx.RequestError as exc: |
| 54 | + logger.error(f"调用爬虫服务失败: {exc}") |
| 55 | + raise ValueError(f"无法从 URL 爬取内容: {exc}") |
| 56 | + except Exception as e: |
| 57 | + logger.error(f'爬取或解析爬取内容失败: {e}') |
| 58 | + raise ValueError(f'处理爬取内容时发生错误: {e}') |
| 59 | + |
40 | 60 | if not html_content: |
41 | | - raise ValueError('必须提供 HTML 内容') |
| 61 | + raise ValueError('必须提供 HTML 内容或有效的 URL') |
42 | 62 |
|
43 | 63 | # 延迟导入,避免模块导入期异常导致服务类不可用 |
44 | 64 | try: |
@@ -83,3 +103,21 @@ async def _parse_with_model(self, html_content: str, options: Optional[Dict[str, |
83 | 103 | if self._inference_service is None: |
84 | 104 | self._inference_service = get_inference_service() |
85 | 105 | return await self._inference_service.inference(html_content, options or {}) |
| 106 | + |
| 107 | + |
| 108 | +if __name__ == '__main__': |
| 109 | + import asyncio |
| 110 | + |
| 111 | + # 重新导入以确保加载最新的代码,绕过缓存问题 |
| 112 | + from llm_web_kit.api.dependencies import get_settings |
| 113 | + settings = get_settings() |
| 114 | + |
| 115 | + async def main(): |
| 116 | + async with httpx.AsyncClient() as client: |
| 117 | + response = await client.post(settings.crawl_url, json={'url': 'https://aws.amazon.com/what-is/retrieval-augmented-generation/'}, timeout=60) |
| 118 | + response.raise_for_status() |
| 119 | + data = response.json() |
| 120 | + html_content = data.get('html') |
| 121 | + print(html_content) |
| 122 | + |
| 123 | + asyncio.run(main()) |
0 commit comments