x.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. """
  2. X (Twitter) 平台实现
  3. 后端:crawler.aiddit.com/crawler/x
  4. """
  5. import json
  6. from typing import Any, Dict, List, Optional
  7. import httpx
  8. from agent.tools.models import ToolResult
  9. from agent.tools.utils.image import build_image_grid, encode_base64, load_images
  10. from agent.tools.builtin.content.registry import PlatformDef, register_platform
  11. from agent.tools.builtin.content.quality import get_post_evaluator
  12. CRAWLER_URL = "http://crawler.aiddit.com/crawler/x/keyword"
  13. COMMENT_URL = "http://crawler.aiddit.com/crawler/x/comment"
  14. DEFAULT_TIMEOUT = 60.0
  15. AUTHOR_COMMENT_TOP_N = 10
  16. async def search(
  17. platform_id: str,
  18. keyword: str,
  19. max_count: int = 20,
  20. cursor: str = "",
  21. extras: Optional[Dict[str, Any]] = None,
  22. ) -> ToolResult:
  23. try:
  24. async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) as client:
  25. response = await client.post(CRAWLER_URL, json={"keyword": keyword})
  26. response.raise_for_status()
  27. data = response.json()
  28. if data.get("code") != 0:
  29. return ToolResult(title="X 搜索失败", output="", error=data.get("msg", "未知错误"))
  30. result_data = data.get("data", {})
  31. tweets = result_data.get("data", []) if isinstance(result_data, dict) else []
  32. evaluator = get_post_evaluator()
  33. # 视频帖在评分前先并发探测 mp4 duration(HTTP Range,不下载视频流),
  34. # 让 evaluator 用真实时长替代 body 长度作为内容信号。
  35. if evaluator and tweets:
  36. try:
  37. from agent.tools.builtin.content.transcription import probe_durations_for_posts
  38. await probe_durations_for_posts("x", tweets[:max_count], concurrency=8)
  39. except Exception as e:
  40. import logging
  41. logging.getLogger(__name__).info("duration probe failed for x: %s", e)
  42. summary_list = []
  43. for idx, tweet in enumerate(tweets[:max_count], 1):
  44. text = tweet.get("body_text", "")
  45. score_info = {}
  46. if evaluator:
  47. try:
  48. eval_res = evaluator.evaluate_post(tweet)
  49. score_info = {
  50. "quality_score": eval_res["total_score"],
  51. "quality_grade": eval_res["grade"]
  52. }
  53. tweet["_quality_score"] = eval_res["total_score"]
  54. except Exception:
  55. pass
  56. summary_item = {
  57. "index": idx,
  58. "author": tweet.get("channel_account_name", ""),
  59. "body_text": text[:100] + ("..." if len(text) > 100 else ""),
  60. "like_count": tweet.get("like_count"),
  61. "comment_count": tweet.get("comment_count"),
  62. "link": tweet.get("link"),
  63. }
  64. summary_item.update(score_info)
  65. summary_list.append(summary_item)
  66. # 拼图
  67. images = []
  68. collage_obj = await _build_tweet_collage(tweets[:max_count])
  69. if collage_obj:
  70. images.append(collage_obj)
  71. return ToolResult(
  72. title=f"X: {keyword}",
  73. output=json.dumps({"data": summary_list}, ensure_ascii=False, indent=2),
  74. long_term_memory=f"Searched X for '{keyword}', {len(tweets)} results.",
  75. images=images,
  76. metadata={"posts": tweets[:max_count]},
  77. )
  78. except Exception as e:
  79. return ToolResult(title="X 搜索异常", output="", error=str(e))
  80. MAX_DETAIL_IMAGES = 10
  81. KEEP_INDIVIDUAL = 8
  82. async def _build_images_collage(urls: List[str]) -> Optional[Dict[str, Any]]:
  83. """将一组图片 URL 拼成单张网格图"""
  84. if not urls:
  85. return None
  86. loaded = await load_images(urls)
  87. valid_images = [img for (_, img) in loaded if img is not None]
  88. if not valid_images:
  89. return None
  90. grid = build_image_grid(images=valid_images, labels=None)
  91. import io
  92. buf = io.BytesIO()
  93. grid.save(buf, format="PNG")
  94. img_bytes = buf.getvalue()
  95. try:
  96. from agent.tools.builtin.file.image_cdn import _upload_bytes_to_oss
  97. import hashlib
  98. md5_hash = hashlib.md5(img_bytes).hexdigest()[:12]
  99. filename = f"x_detail_collage_{md5_hash}.png"
  100. cdn_url = await _upload_bytes_to_oss(img_bytes, filename)
  101. return {"type": "url", "url": cdn_url}
  102. except Exception as e:
  103. import logging
  104. logging.getLogger(__name__).warning("Failed to upload x detail collage to CDN: %s", e)
  105. b64, _ = encode_base64(grid, format="PNG")
  106. return {"type": "base64", "media_type": "image/png", "data": b64}
  107. async def _fetch_author_comments(content_id: str, author_id: str) -> List[Dict[str, Any]]:
  108. """拉取该推文评论,仅保留原作者本人发布的回复,按点赞数降序取 Top N。"""
  109. if not content_id or not author_id:
  110. return []
  111. try:
  112. async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) as client:
  113. resp = await client.post(COMMENT_URL, json={"content_id": content_id})
  114. resp.raise_for_status()
  115. payload = resp.json()
  116. except Exception as e:
  117. import logging
  118. logging.getLogger(__name__).warning("Failed to fetch x comments for %s: %s", content_id, e)
  119. return []
  120. if payload.get("code") != 0:
  121. return []
  122. inner = payload.get("data", {})
  123. raw_comments = inner.get("data", []) if isinstance(inner, dict) else []
  124. author_id_str = str(author_id)
  125. author_comments = []
  126. for c in raw_comments:
  127. author = c.get("author") or {}
  128. if str(author.get("rest_id", "")) != author_id_str:
  129. continue
  130. author_comments.append({
  131. "text": c.get("display_text") or c.get("text", ""),
  132. "likes": c.get("likes", 0) or 0,
  133. "replies": c.get("replies", 0) or 0,
  134. "created_at": c.get("created_at", ""),
  135. })
  136. author_comments.sort(key=lambda x: x["likes"], reverse=True)
  137. return author_comments[:AUTHOR_COMMENT_TOP_N]
  138. async def detail(post: Dict[str, Any], extras: Optional[Dict[str, Any]] = None) -> ToolResult:
  139. """X 的详情直接从缓存的搜索结果取完整数据,并补拉作者本人的热门补充评论。"""
  140. author = post.get("channel_account_name", "")
  141. author_id = post.get("channel_account_id", "")
  142. content_id = post.get("channel_content_id", "")
  143. text = post.get("body_text", "")[:30]
  144. img_urls = []
  145. for img_item in post.get("image_url_list", []):
  146. url = img_item.get("image_url") if isinstance(img_item, dict) else img_item
  147. if url:
  148. img_urls.append(url)
  149. all_images = []
  150. if len(img_urls) > MAX_DETAIL_IMAGES:
  151. for u in img_urls[:KEEP_INDIVIDUAL]:
  152. all_images.append({"type": "url", "url": u})
  153. collage = await _build_images_collage(img_urls[KEEP_INDIVIDUAL:])
  154. if collage:
  155. all_images.append(collage)
  156. else:
  157. for u in img_urls:
  158. all_images.append({"type": "url", "url": u})
  159. author_comments = await _fetch_author_comments(content_id, author_id)
  160. extras_d = extras or {}
  161. trace_id = extras_d.get("__trace_id__")
  162. if not trace_id:
  163. import os as _os
  164. trace_id = _os.getenv("TRACE_ID")
  165. # 把作者评论写回 cache,让下游离线流程(如 extract_sources)也能拿到
  166. if author_comments:
  167. from agent.tools.builtin.content import cache as _cache
  168. if trace_id and content_id:
  169. _cache.update_post_field(trace_id, "x", content_id, "author_comments", author_comments)
  170. # 视频字幕:检测到 video_url_list 时通过 Deepgram 转写 (default on, opt-out via extras)
  171. transcript_text: Optional[str] = post.get("video_transcript") # cache hit reuse
  172. if not transcript_text and extras_d.get("include_transcript", True):
  173. from agent.tools.builtin.content.transcription import transcribe_video_from_post
  174. transcript_text = await transcribe_video_from_post("x", post)
  175. if transcript_text:
  176. post["video_transcript"] = transcript_text
  177. from agent.tools.builtin.content import cache as _cache
  178. if trace_id and content_id:
  179. _cache.update_post_field(trace_id, "x", content_id, "video_transcript", transcript_text)
  180. output_json = json.dumps(post, ensure_ascii=False, indent=2)
  181. sections = [output_json]
  182. if author_comments:
  183. lines = [f"=== 作者 @{author} 在评论区的补充(按点赞 Top {len(author_comments)}) ==="]
  184. for i, c in enumerate(author_comments, 1):
  185. lines.append(f"{i}. [赞{c['likes']} · 回复{c['replies']}] {c['text']}")
  186. sections.append("\n".join(lines))
  187. # transcript already embedded as post["video_transcript"] inside output_json above;
  188. # no need to repeat as a separate section.
  189. output_text = "\n\n".join(sections)
  190. memory_extras = []
  191. if author_comments:
  192. memory_extras.append(f"{len(author_comments)} author replies")
  193. if transcript_text:
  194. memory_extras.append("+transcript")
  195. memory_suffix = " + " + ", ".join(memory_extras) if memory_extras else ""
  196. return ToolResult(
  197. title=f"X 详情: @{author}",
  198. output=output_text,
  199. long_term_memory=f"Viewed X post by @{author}: {text}{memory_suffix}",
  200. images=all_images,
  201. )
  202. async def _build_tweet_collage(tweets: List[Dict[str, Any]]) -> Optional[str]:
  203. urls, titles = [], []
  204. for tweet in tweets:
  205. thumb = None
  206. for img_item in tweet.get("image_url_list", []):
  207. url = img_item.get("image_url") if isinstance(img_item, dict) else img_item
  208. if url:
  209. thumb = url
  210. break
  211. if not thumb:
  212. thumb = tweet.get("cover_url")
  213. if thumb:
  214. urls.append(thumb)
  215. base_title = f"@{tweet.get('channel_account_name', '')}"
  216. score = tweet.get("_quality_score")
  217. if score is not None:
  218. title_with_score = f"[{score}分] {base_title}"
  219. else:
  220. title_with_score = base_title
  221. titles.append(title_with_score)
  222. if not urls:
  223. return None
  224. loaded = await load_images(urls)
  225. valid_images, valid_labels = [], []
  226. for (_, img), title in zip(loaded, titles):
  227. if img is not None:
  228. valid_images.append(img)
  229. valid_labels.append(title)
  230. if not valid_images:
  231. return None
  232. grid = build_image_grid(images=valid_images, labels=valid_labels)
  233. import io
  234. buf = io.BytesIO()
  235. grid.save(buf, format="PNG")
  236. img_bytes = buf.getvalue()
  237. try:
  238. from agent.tools.builtin.file.image_cdn import _upload_bytes_to_oss
  239. import hashlib
  240. md5_hash = hashlib.md5(img_bytes).hexdigest()[:12]
  241. filename = f"x_collage_{md5_hash}.png"
  242. cdn_url = await _upload_bytes_to_oss(img_bytes, filename)
  243. return {"type": "url", "url": cdn_url}
  244. except Exception as e:
  245. import logging
  246. logging.getLogger(__name__).warning("Failed to upload x collage to CDN: %s", e)
  247. b64, _ = encode_base64(grid, format="PNG")
  248. return {"type": "base64", "media_type": "image/png", "data": b64}
  249. # ── 注册 ──
  250. _X = PlatformDef(
  251. id="x",
  252. name="X (Twitter)",
  253. aliases=["twitter", "推特"],
  254. )
  255. _X.search_impl = search
  256. _X.detail_impl = detail
  257. register_platform(_X)