output_sync.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """Parse recommendation buckets from the model's final response."""
  2. from __future__ import annotations
  3. import re
  4. _VIDEO_ID_PATTERN = re.compile(r"(?<!\d)\d{15,22}(?!\d)")
  5. _PRIMARY_LABELS = ("主推荐", "正式推荐")
  6. _REJECTED_LABELS = ("淘汰候选", "淘汰")
  7. _END_LABELS = (
  8. "搜索轨迹",
  9. "搜索树",
  10. "缺失数据",
  11. "局限",
  12. "总结",
  13. )
  14. def _normalized_heading(line: str) -> str:
  15. text = line.strip()
  16. text = re.sub(r"^#{1,6}\s*", "", text)
  17. text = re.sub(r"^\d+\s*[.、]\s*", "", text)
  18. return text.replace("*", "").strip()
  19. def extract_model_recommendation_ids(
  20. content: str,
  21. ) -> tuple[list[str], list[str]]:
  22. """Extract video ids from the model's primary and rejected sections."""
  23. primary: list[str] = []
  24. rejected: list[str] = []
  25. section: str | None = None
  26. for line in (content or "").splitlines():
  27. heading = _normalized_heading(line)
  28. if any(heading.startswith(label) for label in _PRIMARY_LABELS):
  29. section = "primary"
  30. elif any(heading.startswith(label) for label in _REJECTED_LABELS):
  31. section = "rejected"
  32. elif any(heading.startswith(label) for label in _END_LABELS):
  33. section = None
  34. if section is None:
  35. continue
  36. target = primary if section == "primary" else rejected
  37. for aweme_id in _VIDEO_ID_PATTERN.findall(line):
  38. if aweme_id not in target:
  39. target.append(aweme_id)
  40. primary_set = set(primary)
  41. return primary, [
  42. aweme_id for aweme_id in rejected if aweme_id not in primary_set
  43. ]