Tolimo commited on
Commit
cd6602e
·
verified ·
1 Parent(s): e08910b

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +54 -71
main.py CHANGED
@@ -21,15 +21,14 @@ app.add_middleware(
21
  allow_headers=["*"],
22
  )
23
 
24
- TEMP_DIR = "/tmp/facebook_downloads"
25
  if not os.path.exists(TEMP_DIR):
26
  os.makedirs(TEMP_DIR)
27
 
28
- MAX_FILE_AGE = 1800
29
-
30
  # --- CONFIGURATION ---
31
- RAPID_API_KEY = "76af57b863msh20fecf9aaa3b6c6p1bbc52jsn3b00ca30e34f" # <--- BRO ရဲ့ KEY ကို ဒီမှာပြန်ထည့်ပါ
32
- RAPID_API_HOST = "facebook-reel-and-video-downloader.p.rapidapi.com"
 
33
 
34
  def get_url_hash(url: str):
35
  return hashlib.md5(url.encode()).hexdigest()
@@ -41,18 +40,9 @@ def remove_stale_files():
41
  if os.path.isfile(file_path) and os.path.getmtime(file_path) < now - MAX_FILE_AGE:
42
  os.remove(file_path)
43
 
44
- def get_ffprobe_info(file_path):
45
- try:
46
- cmd = ['ffprobe', '-v', 'error', '-show_entries', 'stream=codec_type', '-of', 'json', file_path]
47
- result = subprocess.run(cmd, capture_output=True, text=True)
48
- data = json.loads(result.stdout)
49
- return [s['codec_type'] for s in data.get('streams', [])]
50
- except:
51
- return []
52
-
53
  @app.get("/")
54
  def root():
55
- return {"message": "Bumiz FB API: Strict Failure Protection Active"}
56
 
57
  @app.get("/download")
58
  async def download_fb_video(background_tasks: BackgroundTasks, url: str = Query(...)):
@@ -67,80 +57,73 @@ async def download_fb_video(background_tasks: BackgroundTasks, url: str = Query(
67
 
68
  # 1. CACHE CHECK
69
  if os.path.exists(video_path):
70
- logs.append("Cache hit! Serving existing file.")
71
  return {
72
  "success": True,
73
  "method": "Bumiz Cache",
74
- "video_url": f"{base_url}{file_id}.mp4",
75
- "music_url": f"{base_url}{file_id}.mp3" if os.path.exists(audio_path) else None,
76
  "logs": logs
77
  }
78
 
79
- # 2. PHASE 1: yt-dlp with Fail-safe
80
- temp_raw = os.path.join(TEMP_DIR, f"{file_id}_raw.mp4")
81
- logs.append("Phase 1: Attempting yt-dlp (HQ Encoded Mode)...")
82
-
83
  try:
84
- ydl_opts = {
85
- 'socket_timeout': 10,
86
- 'format': 'best',
87
- 'outtmpl': temp_raw,
88
- 'merge_output_format': 'mp4',
89
- 'quiet': True,
90
- 'no_warnings': True,
91
- 'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
92
  }
93
 
94
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
95
- ydl.download([url])
96
-
97
- if os.path.exists(temp_raw):
98
- streams = get_ffprobe_info(temp_raw)
99
- if 'video' in streams:
100
- logs.append("yt-dlp successful. Encoding to H.264/AAC...")
101
- # Video Encoding
102
- subprocess.run([
103
- 'ffmpeg', '-y', '-i', temp_raw,
104
- '-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '28',
105
- '-c:a', 'aac', '-b:a', '128k',
106
- '-movflags', '+faststart', video_path
107
- ], check=True)
108
- # MP3 Extraction
109
- subprocess.run(['ffmpeg', '-y', '-i', temp_raw, '-vn', '-acodec', 'libmp3lame', '-ab', '192k', audio_path], check=True)
110
-
111
- os.remove(temp_raw)
112
- return {"success": True, "method": "yt-dlp (HQ Encoded)", "video_url": f"{base_url}{file_id}.mp4", "music_url": f"{base_url}{file_id}.mp3", "logs": logs}
113
-
114
- except Exception as e:
115
- logs.append(f"yt-dlp skipped due to error: {str(e)}")
116
- if os.path.exists(temp_raw): os.remove(temp_raw)
117
-
118
- # 3. PHASE 2: RapidAPI Fallback (Last Resort)
119
- logs.append("Phase 2: Switching to RapidAPI for guaranteed success...")
120
- try:
121
- api_url = f"https://{RAPID_API_HOST}/index"
122
- headers = {"X-RapidAPI-Key": RAPID_API_KEY, "X-RapidAPI-Host": RAPID_API_HOST}
123
- response = requests.get(api_url, headers=headers, params={"url": url}, timeout=15)
124
  data = response.json()
125
 
126
- if data and "video" in data:
127
- logs.append("RapidAPI success! Returning HD link.")
 
 
 
 
 
 
 
128
  return {
129
- "success": True,
130
- "method": "RapidAPI",
131
- "video_url": data["video"][0],
132
- "music_url": data["music"][0],
133
  "logs": logs
134
  }
 
 
135
  except Exception as e:
136
- logs.append(f"RapidAPI also failed: {str(e)}")
137
-
138
- return {"success": False, "error": "All methods failed to process this video.", "logs": logs}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
  @app.get("/get_file")
141
  async def get_file(id: str):
142
  file_path = os.path.join(TEMP_DIR, id)
143
  if os.path.exists(file_path):
144
  media_type = "video/mp4" if id.endswith(".mp4") else "audio/mpeg"
145
- return FileResponse(file_path, media_type=media_type, filename=f"fb_download_{id}")
146
- raise HTTPException(status_code=404, detail="File expired or not found")
 
21
  allow_headers=["*"],
22
  )
23
 
24
+ TEMP_DIR = "/tmp/fb_cache"
25
  if not os.path.exists(TEMP_DIR):
26
  os.makedirs(TEMP_DIR)
27
 
 
 
28
  # --- CONFIGURATION ---
29
+ RAPID_API_KEY = "3a2dadb7dcms..." # <--- ိုရဲ့ KEY အရှည်ကြီးကို ဒီမှာထည့်ပါ
30
+ RAPID_API_HOST = "facebook-media-downloader1.p.rapidapi.com"
31
+ MAX_FILE_AGE = 1800
32
 
33
  def get_url_hash(url: str):
34
  return hashlib.md5(url.encode()).hexdigest()
 
40
  if os.path.isfile(file_path) and os.path.getmtime(file_path) < now - MAX_FILE_AGE:
41
  os.remove(file_path)
42
 
 
 
 
 
 
 
 
 
 
43
  @app.get("/")
44
  def root():
45
+ return {"message": "Bumiz FB API: JSON POST Method Active"}
46
 
47
  @app.get("/download")
48
  async def download_fb_video(background_tasks: BackgroundTasks, url: str = Query(...)):
 
57
 
58
  # 1. CACHE CHECK
59
  if os.path.exists(video_path):
60
+ logs.append("Cache Hit: Found existing file on server.")
61
  return {
62
  "success": True,
63
  "method": "Bumiz Cache",
64
+ "video_url": f"{base_url}{file_id}.mp4",
65
+ "music_url": f"{base_url}{file_id}.mp3" if os.path.exists(audio_path) else None,
66
  "logs": logs
67
  }
68
 
69
+ # 2. PHASE 1: RapidAPI (POST Method with JSON Body)
70
+ # ဘရိုပြောတဲ့ --data '{"url":"..."}' ပုံစံအတိုင်း ခေါ်မှာဖြစ်ပါတယ်
71
+ logs.append(f"Phase 1: Requesting RapidAPI via POST...")
 
72
  try:
73
+ api_url = f"https://{RAPID_API_HOST}/" # Endpoint URL ကို သတိပြုပါ
74
+ payload = {"url": url}
75
+ headers = {
76
+ "content-type": "application/json",
77
+ "X-RapidAPI-Key": RAPID_API_KEY,
78
+ "X-RapidAPI-Host": RAPID_API_HOST
 
 
79
  }
80
 
81
+ response = requests.post(api_url, json=payload, headers=headers, timeout=15)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  data = response.json()
83
 
84
+ # API ကနေ ဘာတွေပြန်ပေးလဲဆိုတာ သိရအောင် Log ထုတ်ကြည့်ခြင်း
85
+ logs.append(f"API Response Received.")
86
+
87
+ # API JSON Structure အလိုက် လင့်ခ်များကို ဆွဲထုတ်ခြင်း (AssadAzeem API Format)
88
+ video_url = data.get("hd") or data.get("sd") or data.get("url")
89
+ audio_url = data.get("audio") or data.get("mp3")
90
+
91
+ if video_url:
92
+ logs.append("API Success: High Quality link found.")
93
  return {
94
+ "success": True,
95
+ "method": "RapidAPI (POST)",
96
+ "video_url": video_url,
97
+ "music_url": audio_url,
98
  "logs": logs
99
  }
100
+ else:
101
+ logs.append(f"API Error: No video link in response. JSON: {str(data)[:100]}")
102
  except Exception as e:
103
+ logs.append(f"API Connection Failed: {str(e)}")
104
+
105
+ # 3. PHASE 2: yt-dlp (Fallback)
106
+ logs.append("Phase 2: yt-dlp Fallback started...")
107
+ temp_raw = os.path.join(TEMP_DIR, f"{file_id}_raw.mp4")
108
+ try:
109
+ ydl_opts = {'format': 'best', 'outtmpl': temp_raw, 'quiet': True, 'socket_timeout': 10}
110
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
111
+ ydl.download([url])
112
+
113
+ if os.path.exists(temp_raw):
114
+ logs.append("yt-dlp success! Encoding file...")
115
+ subprocess.run(['ffmpeg', '-y', '-i', temp_raw, '-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '28', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', video_path], check=True)
116
+ os.remove(temp_raw)
117
+ return {"success": True, "method": "yt-dlp (Fallback)", "video_url": f"{base_url}{file_id}.mp4", "logs": logs}
118
+ except Exception as e:
119
+ logs.append(f"yt-dlp failed: {str(e)}")
120
+
121
+ return {"success": False, "error": "Could not download this Facebook video.", "logs": logs}
122
 
123
  @app.get("/get_file")
124
  async def get_file(id: str):
125
  file_path = os.path.join(TEMP_DIR, id)
126
  if os.path.exists(file_path):
127
  media_type = "video/mp4" if id.endswith(".mp4") else "audio/mpeg"
128
+ return FileResponse(file_path, media_type=media_type, filename=f"fb_{id}")
129
+ raise HTTPException(status_code=404, detail="File expired")