helpers.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # -*- coding: utf-8 -*-
  2. """
  3. 工具函数
  4. """
  5. import os
  6. from datetime import datetime
  7. from typing import Optional
  8. def parse_datetime(date_str: str) -> Optional[datetime]:
  9. """
  10. 解析日期时间字符串
  11. 支持多种格式
  12. """
  13. if not date_str:
  14. return None
  15. formats = [
  16. "%Y-%m-%d %H:%M:%S",
  17. "%Y-%m-%d %H:%M",
  18. "%Y/%m/%d %H:%M:%S",
  19. "%Y/%m/%d %H:%M",
  20. "%Y-%m-%dT%H:%M:%S",
  21. "%Y-%m-%dT%H:%M:%SZ",
  22. ]
  23. for fmt in formats:
  24. try:
  25. return datetime.strptime(date_str, fmt)
  26. except ValueError:
  27. continue
  28. return None
  29. def validate_video_file(video_path: str) -> bool:
  30. """
  31. 验证视频文件是否存在且有效
  32. """
  33. if not video_path:
  34. return False
  35. if not os.path.exists(video_path):
  36. return False
  37. if not os.path.isfile(video_path):
  38. return False
  39. # 检查文件扩展名
  40. valid_extensions = ['.mp4', '.mov', '.avi', '.mkv', '.flv', '.wmv', '.webm']
  41. ext = os.path.splitext(video_path)[1].lower()
  42. if ext not in valid_extensions:
  43. return False
  44. # 检查文件大小(至少 1KB)
  45. if os.path.getsize(video_path) < 1024:
  46. return False
  47. return True
  48. def get_video_duration(video_path: str) -> Optional[float]:
  49. """
  50. 获取视频时长(秒)
  51. 需要安装 ffprobe
  52. """
  53. try:
  54. import subprocess
  55. result = subprocess.run(
  56. ['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
  57. '-of', 'default=noprint_wrappers=1:nokey=1', video_path],
  58. capture_output=True,
  59. text=True
  60. )
  61. return float(result.stdout.strip())
  62. except:
  63. return None
  64. def format_file_size(size_bytes: int) -> str:
  65. """
  66. 格式化文件大小
  67. """
  68. for unit in ['B', 'KB', 'MB', 'GB']:
  69. if size_bytes < 1024.0:
  70. return f"{size_bytes:.2f} {unit}"
  71. size_bytes /= 1024.0
  72. return f"{size_bytes:.2f} TB"