Kingoteam commited on
Commit
ee35bb6
·
verified ·
1 Parent(s): 753992c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -12
app.py CHANGED
@@ -4,6 +4,7 @@ import subprocess
4
  import os
5
  import uuid
6
  import logging
 
7
 
8
  # تنظیم لاگ برای دیباگ
9
  logging.basicConfig(level=logging.INFO)
@@ -11,6 +12,24 @@ logger = logging.getLogger(__name__)
11
 
12
  app = FastAPI()
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  def compress_video(input_path: str, crf: int, resolution: str) -> str:
15
  logger.info(f"Starting video compression for {input_path}")
16
  try:
@@ -21,17 +40,30 @@ def compress_video(input_path: str, crf: int, resolution: str) -> str:
21
  # تولید نام یکتا برای فایل خروجی
22
  output_path = f"compressed_{uuid.uuid4().hex}.mp4"
23
 
24
- # تنظیم رزولوشن
 
 
 
25
  scale_filter = None
26
- if resolution != "original":
27
- scale_filter = {
28
- "720p": "1280:720",
29
- "480p": "854:480",
30
- "360p": "640:360",
31
- "240p": "426:240"
32
- }.get(resolution)
33
- if not scale_filter:
34
- raise ValueError("رزولوشن نامعتبر!")
 
 
 
 
 
 
 
 
 
 
35
 
36
  # ساخت دستور FFmpeg
37
  command = [
@@ -41,7 +73,7 @@ def compress_video(input_path: str, crf: int, resolution: str) -> str:
41
  ]
42
 
43
  if scale_filter:
44
- command.extend(["-vf", f"scale={scale_filter}"])
45
 
46
  command.append(output_path)
47
 
@@ -100,7 +132,6 @@ async def compress_video_api(
100
  # فقط فایل ورودی رو حذف کن
101
  if input_path and os.path.exists(input_path):
102
  os.remove(input_path)
103
- # فایل خروجی رو بعد از ارسال نگه دار (یا بعداً با یه مکانیزم پاک‌سازی حذف کن)
104
 
105
  if __name__ == "__main__":
106
  import uvicorn
 
4
  import os
5
  import uuid
6
  import logging
7
+ import json
8
 
9
  # تنظیم لاگ برای دیباگ
10
  logging.basicConfig(level=logging.INFO)
 
12
 
13
  app = FastAPI()
14
 
15
+ def get_video_resolution(input_path: str) -> tuple[int, int]:
16
+ """دریافت رزولوشن ویدیوی ورودی با استفاده از ffprobe"""
17
+ try:
18
+ command = [
19
+ "ffprobe", "-v", "error", "-select_streams", "v:0",
20
+ "-show_entries", "stream=width,height", "-of", "json",
21
+ input_path
22
+ ]
23
+ result = subprocess.run(command, capture_output=True, text=True, check=True)
24
+ data = json.loads(result.stdout)
25
+ width = data["streams"][0]["width"]
26
+ height = data["streams"][0]["height"]
27
+ logger.info(f"Input resolution: {width}x{height}")
28
+ return width, height
29
+ except subprocess.CalledProcessError as e:
30
+ logger.error(f"ffprobe error: {e.stderr}")
31
+ raise ValueError("خطا در دریافت رزولوشن ویدیو")
32
+
33
  def compress_video(input_path: str, crf: int, resolution: str) -> str:
34
  logger.info(f"Starting video compression for {input_path}")
35
  try:
 
40
  # تولید نام یکتا برای فایل خروجی
41
  output_path = f"compressed_{uuid.uuid4().hex}.mp4"
42
 
43
+ # دریافت رزولوشن ورودی
44
+ input_width, input_height = get_video_resolution(input_path)
45
+
46
+ # تنظیم رزولوشن خروجی
47
  scale_filter = None
48
+ target_resolutions = {
49
+ "720p": (1280, 720),
50
+ "480p": (854, 480),
51
+ "360p": (640, 360),
52
+ "240p": (426, 240),
53
+ "original": (input_width, input_height)
54
+ }
55
+
56
+ if resolution not in target_resolutions:
57
+ raise ValueError("رزولوشن نامعتبر!")
58
+
59
+ target_width, target_height = target_resolutions[resolution]
60
+
61
+ # محدود کردن رزولوشن خروجی به حداکثر رزولوشن ورودی
62
+ if target_width > input_width or target_height > input_height:
63
+ logger.info(f"Target resolution {target_width}x{target_height} is larger than input {input_width}x{input_height}, using input resolution")
64
+ target_width, target_height = input_width, input_height
65
+
66
+ scale_filter = f"scale={target_width}:{target_height}:force_original_aspect_ratio=decrease"
67
 
68
  # ساخت دستور FFmpeg
69
  command = [
 
73
  ]
74
 
75
  if scale_filter:
76
+ command.extend(["-vf", scale_filter])
77
 
78
  command.append(output_path)
79
 
 
132
  # فقط فایل ورودی رو حذف کن
133
  if input_path and os.path.exists(input_path):
134
  os.remove(input_path)
 
135
 
136
  if __name__ == "__main__":
137
  import uvicorn