CI / check (push) Failing after 15m48s
Signed-off-by: 南通一次元科技有限公司 <guwangtu@icimeta.com>
123 lines
3.9 KiB
Python
123 lines
3.9 KiB
Python
"""网络搜索服务 - 从互联网获取审计相关补充材料"""
|
||
|
||
import json
|
||
import subprocess
|
||
import os
|
||
import urllib.request
|
||
import urllib.parse
|
||
|
||
|
||
def search_web(query: str, max_results: int = 5) -> list[dict]:
|
||
"""使用 DuckDuckGo 搜索获取相关网页摘要
|
||
|
||
Args:
|
||
query: 搜索关键词
|
||
max_results: 最大返回结果数
|
||
|
||
Returns:
|
||
包含 title, url, snippet 的结果列表
|
||
"""
|
||
results = []
|
||
try:
|
||
# 使用 DuckDuckGo Instant Answer API(无需 API Key)
|
||
encoded_query = urllib.parse.quote(query)
|
||
url = f"https://api.duckduckgo.com/?q={encoded_query}&format=json&no_html=1&skip_disambig=1"
|
||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||
data = json.loads(resp.read().decode("utf-8"))
|
||
|
||
# 提取摘要
|
||
abstract = data.get("Abstract", "")
|
||
abstract_source = data.get("AbstractSource", "")
|
||
abstract_url = data.get("AbstractURL", "")
|
||
heading = data.get("Heading", "")
|
||
|
||
if abstract:
|
||
results.append({
|
||
"title": heading or abstract_source or "搜索结果",
|
||
"url": abstract_url or "",
|
||
"snippet": abstract[:500]
|
||
})
|
||
|
||
# 提取相关主题
|
||
for topic in data.get("RelatedTopics", [])[:max_results]:
|
||
if isinstance(topic, dict) and topic.get("Text"):
|
||
results.append({
|
||
"title": topic.get("Text", "")[:80],
|
||
"url": topic.get("FirstURL", ""),
|
||
"snippet": topic.get("Text", "")[:300]
|
||
})
|
||
if len(results) >= max_results:
|
||
break
|
||
|
||
except Exception:
|
||
pass # 网络搜索失败不影响主流程
|
||
|
||
return results
|
||
|
||
|
||
def fetch_url_content(url: str, max_length: int = 2000) -> str:
|
||
"""获取网页文本内容(简单提取)
|
||
|
||
Args:
|
||
url: 网页 URL
|
||
max_length: 最大返回字符数
|
||
"""
|
||
try:
|
||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||
raw = resp.read().decode("utf-8", errors="ignore")
|
||
|
||
# 简单提取文本:去掉 HTML 标签
|
||
import re
|
||
# 移除 script 和 style
|
||
raw = re.sub(r'<script[^>]*>.*?</script>', '', raw, flags=re.DOTALL | re.IGNORECASE)
|
||
raw = re.sub(r'<style[^>]*>.*?</style>', '', raw, flags=re.DOTALL | re.IGNORECASE)
|
||
# 移除所有 HTML 标签
|
||
text = re.sub(r'<[^>]+>', ' ', raw)
|
||
# 清理多余空白
|
||
text = re.sub(r'\s+', ' ', text).strip()
|
||
|
||
if len(text) > max_length:
|
||
text = text[:max_length] + "...(内容已截断)"
|
||
return text
|
||
except Exception:
|
||
return ""
|
||
|
||
|
||
def build_web_context(query: str) -> str:
|
||
"""根据查询关键词搜索网络并构建补充材料文本
|
||
|
||
Args:
|
||
query: 搜索关键词(通常包含审计相关主题)
|
||
|
||
Returns:
|
||
格式化的网络补充材料文本
|
||
"""
|
||
results = search_web(query, max_results=5)
|
||
if not results:
|
||
return ""
|
||
|
||
sections = []
|
||
for i, r in enumerate(results, 1):
|
||
title = r.get("title", "")
|
||
snippet = r.get("snippet", "")
|
||
url = r.get("url", "")
|
||
|
||
# 尝试获取更详细的内容
|
||
detail = ""
|
||
if url:
|
||
detail = fetch_url_content(url, max_length=1500)
|
||
|
||
section = f"### 资料{i}:{title}\n"
|
||
section += f"摘要:{snippet}\n"
|
||
if detail:
|
||
section += f"详细内容:{detail}\n"
|
||
if url:
|
||
section += f"来源:{url}\n"
|
||
sections.append(section)
|
||
|
||
context = "## 网络补充材料\n以下是从互联网搜索获取的相关法规、最佳实践和参考资料:\n\n"
|
||
context += "\n\n---\n\n".join(sections)
|
||
return context
|