service.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """Media stabilization service for the formal acquisition pipeline."""
  2. from __future__ import annotations
  3. from dataclasses import dataclass
  4. from typing import Callable
  5. from acquisition.media.oss_client import to_oss
  6. from core.config import Settings
  7. @dataclass(frozen=True)
  8. class StabilizedMedia:
  9. media_type: str
  10. source_url: str
  11. cdn_url: str
  12. position: int
  13. status: str = "ready"
  14. Uploader = Callable[[str, str], str]
  15. def stabilize_media_urls(
  16. *,
  17. image_urls: list[str] | None = None,
  18. video_urls: list[str] | None = None,
  19. settings: Settings | None = None,
  20. uploader: Uploader | None = None,
  21. ) -> list[StabilizedMedia]:
  22. """Transfer image/video URLs to OSS/CDN and return DB-ready media rows.
  23. The uploader falls back to the original source URL when OSS transfer fails,
  24. so acquisition can still store the candidate and make the failure visible in
  25. later review instead of dropping the item.
  26. """
  27. upload = uploader or (
  28. lambda url, media_type: to_oss(url, media_type, settings=settings)
  29. )
  30. rows: list[StabilizedMedia] = []
  31. position = 0
  32. for url in image_urls or []:
  33. if not url:
  34. continue
  35. position += 1
  36. try:
  37. cdn = upload(url, "image")
  38. except Exception:
  39. cdn = url
  40. rows.append(
  41. StabilizedMedia(
  42. media_type="image",
  43. source_url=url,
  44. cdn_url=cdn,
  45. position=position,
  46. status="ready" if cdn else "failed",
  47. )
  48. )
  49. for url in video_urls or []:
  50. if not url:
  51. continue
  52. position += 1
  53. try:
  54. cdn = upload(url, "video")
  55. except Exception:
  56. cdn = url
  57. rows.append(
  58. StabilizedMedia(
  59. media_type="video",
  60. source_url=url,
  61. cdn_url=cdn,
  62. position=position,
  63. status="ready" if cdn else "failed",
  64. )
  65. )
  66. return rows