Tolimo commited on
Commit
fd0ebb4
Β·
verified Β·
1 Parent(s): 53ffea7

Create facebook_main.py

Browse files
Files changed (1) hide show
  1. facebook_main.py +125 -0
facebook_main.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yt_dlp
2
+ from fastapi import FastAPI, HTTPException, Query, BackgroundTasks
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from fastapi.responses import FileResponse
5
+ import subprocess
6
+ import os
7
+ import uuid
8
+ import json
9
+ import requests
10
+ import time
11
+ import hashlib
12
+
13
+ app = FastAPI()
14
+
15
+ app.add_middleware(
16
+ CORSMiddleware,
17
+ allow_origins=["*"],
18
+ allow_credentials=True,
19
+ allow_methods=["*"],
20
+ allow_headers=["*"],
21
+ )
22
+
23
+ TEMP_DIR = "/tmp/facebook_downloads"
24
+ if not os.path.exists(TEMP_DIR):
25
+ os.makedirs(TEMP_DIR)
26
+
27
+ # --- CONFIGURATION ---
28
+ # Facebook ထတွက် RapidAPI α€›α€Ύα€­α€œα€»α€Ύα€„α€Ί Key α€‘α€Šα€·α€Ία€•α€« (α€™α€›α€Ύα€­α€žα€±α€Έα€›α€„α€Ί yt-dlp နဲ့ပဲ α€‘α€›α€„α€Ία€‘α€œα€―α€•α€Ία€œα€―α€•α€Ία€•α€«α€™α€šα€Ί)
29
+ RAPID_API_KEY = "YOUR_RAPID_API_KEY"
30
+ RAPID_API_HOST = "facebook-reel-and-video-downloader.p.rapidapi.com"
31
+ MAX_FILE_AGE = 1800 # ၃၀ α€™α€­α€”α€…α€Ί
32
+
33
+ def get_url_hash(url: str):
34
+ return hashlib.md5(url.encode()).hexdigest()
35
+
36
+ def remove_stale_files():
37
+ now = time.time()
38
+ for f in os.listdir(TEMP_DIR):
39
+ file_path = os.path.join(TEMP_DIR, f)
40
+ if os.path.isfile(file_path):
41
+ if 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 Facebook API: Isolated Micro-service Active"}
56
+
57
+ @app.get("/download")
58
+ async def download_fb_video(background_tasks: BackgroundTasks, url: str = Query(...)):
59
+ remove_stale_files()
60
+ logs = []
61
+ file_id = get_url_hash(url)
62
+ video_path = os.path.join(TEMP_DIR, f"{file_id}.mp4")
63
+ audio_path = os.path.join(TEMP_DIR, f"{file_id}.mp3")
64
+
65
+ space_id = os.getenv('SPACE_ID', '').replace("/", "-")
66
+ base_url = f"https://{space_id}.hf.space/get_file?id="
67
+
68
+ # ၁။ CACHE CHECK
69
+ if os.path.exists(video_path):
70
+ os.utime(video_path, None)
71
+ logs.append("Bumiz Cache: Found existing file.")
72
+ return {
73
+ "success": True,
74
+ "method": "Cache",
75
+ "video_url": f"{base_url}{file_id}.mp4",
76
+ "music_url": f"{base_url}{file_id}.mp3" if os.path.exists(audio_path) else None,
77
+ "logs": logs
78
+ }
79
+
80
+ # ၂။ Phase 1: yt-dlp
81
+ logs.append("Phase 1: Attempting yt-dlp (Facebook Optimized)...")
82
+ temp_raw = os.path.join(TEMP_DIR, f"{file_id}_raw.mp4")
83
+ try:
84
+ ydl_opts = {
85
+ 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
86
+ 'outtmpl': temp_raw,
87
+ 'quiet': True,
88
+ 'no_warnings': True
89
+ }
90
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
91
+ ydl.download([url])
92
+
93
+ if os.path.exists(temp_raw):
94
+ streams = get_ffprobe_info(temp_raw)
95
+ if 'video' in streams:
96
+ logs.append("FFmpeg: Forcing H.264 and AAC (128k)...")
97
+ # Video Processing
98
+ subprocess.run(['ffmpeg', '-y', '-i', temp_raw, '-c:v', 'libx264', '-preset', 'superfast', '-crf', '22', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', video_path], check=True)
99
+ # MP3 Extraction
100
+ subprocess.run(['ffmpeg', '-y', '-i', temp_raw, '-vn', '-acodec', 'libmp3lame', '-ab', '192k', audio_path], check=True)
101
+ os.remove(temp_raw)
102
+ return {
103
+ "success": True,
104
+ "method": "yt-dlp (HQ Encoded)",
105
+ "video_url": f"{base_url}{file_id}.mp4",
106
+ "music_url": f"{base_url}{file_id}.mp3",
107
+ "logs": logs
108
+ }
109
+ except Exception as e:
110
+ logs.append(f"yt-dlp failed: {str(e)}")
111
+ if os.path.exists(temp_raw): os.remove(temp_raw)
112
+
113
+ # ၃။ Phase 2: RapidAPI (Fallback)
114
+ logs.append("Phase 2: Switching to RapidAPI...")
115
+ # မှတ်ချက် - FB API key α€›α€Ύα€­α€™α€Ύα€žα€¬ α€‘α€œα€―α€•α€Ία€œα€―α€•α€Ία€•α€«α€™α€Šα€Ί
116
+ return {"success": False, "error": "Could not process Facebook video.", "logs": logs}
117
+
118
+ @app.get("/get_file")
119
+ async def get_file(id: str):
120
+ file_path = os.path.join(TEMP_DIR, id)
121
+ if os.path.exists(file_path):
122
+ os.utime(file_path, None)
123
+ media_type = "video/mp4" if id.endswith(".mp4") else "audio/mpeg"
124
+ return FileResponse(file_path, media_type=media_type, filename=f"fb_download_{id}")
125
+ raise HTTPException(status_code=404, detail="File expired")