Spaces:
Sleeping
Sleeping
Create audio_extractor.py
Browse files- audio_extractor.py +108 -0
audio_extractor.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import subprocess
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
logging.basicConfig(level=logging.INFO)
|
| 7 |
+
|
| 8 |
+
def extract_audio(video_url: str, identifier: str, output_dir: str = "temp_audio") -> str:
|
| 9 |
+
"""
|
| 10 |
+
استخراج الصوت من فيديو باستخدام ffmpeg streaming
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
video_url: رابط الفيديو من Internet Archive
|
| 14 |
+
identifier: معرف الفيديو
|
| 15 |
+
output_dir: مجلد حفظ الملفات المؤقتة
|
| 16 |
+
|
| 17 |
+
Returns:
|
| 18 |
+
مسار ملف الصوت المستخرج
|
| 19 |
+
"""
|
| 20 |
+
try:
|
| 21 |
+
# إنشاء المجلد لو مش موجود
|
| 22 |
+
Path(output_dir).mkdir(exist_ok=True)
|
| 23 |
+
|
| 24 |
+
# مسار الملف النهائي
|
| 25 |
+
output_file = os.path.join(output_dir, f"{identifier}.mp3")
|
| 26 |
+
|
| 27 |
+
# لو الملف موجود من قبل، نرجعه مباشرة (caching)
|
| 28 |
+
if os.path.exists(output_file):
|
| 29 |
+
logging.info(f"Audio file already exists: {output_file}")
|
| 30 |
+
return output_file
|
| 31 |
+
|
| 32 |
+
logging.info(f"Extracting audio from: {video_url}")
|
| 33 |
+
|
| 34 |
+
# أمر ffmpeg مع إعدادات محسّنة للسرعة
|
| 35 |
+
command = [
|
| 36 |
+
'ffmpeg',
|
| 37 |
+
'-y', # Overwrite output file
|
| 38 |
+
'-i', video_url, # Input video URL
|
| 39 |
+
'-vn', # No video
|
| 40 |
+
'-acodec', 'libmp3lame', # MP3 codec
|
| 41 |
+
'-ab', '64k', # 64 kbps (خفيف ومناسب للكلام)
|
| 42 |
+
'-ar', '16000', # 16 kHz sample rate (كافي للـ speech)
|
| 43 |
+
'-ac', '1', # Mono (قناة واحدة)
|
| 44 |
+
'-threads', '2', # استخدام 2 threads فقط
|
| 45 |
+
output_file
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
# تنفيذ الأمر مع timeout
|
| 49 |
+
logging.info("Running ffmpeg...")
|
| 50 |
+
result = subprocess.run(
|
| 51 |
+
command,
|
| 52 |
+
stdout=subprocess.PIPE,
|
| 53 |
+
stderr=subprocess.PIPE,
|
| 54 |
+
timeout=60 # Timeout بعد دقيقة
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
if result.returncode != 0:
|
| 58 |
+
error_msg = result.stderr.decode('utf-8', errors='ignore')
|
| 59 |
+
logging.error(f"FFmpeg error: {error_msg}")
|
| 60 |
+
raise Exception(f"FFmpeg failed: {error_msg[:200]}")
|
| 61 |
+
|
| 62 |
+
# التحقق من وجود الملف وحجمه
|
| 63 |
+
if not os.path.exists(output_file):
|
| 64 |
+
raise Exception("Audio file was not created")
|
| 65 |
+
|
| 66 |
+
file_size = os.path.getsize(output_file)
|
| 67 |
+
file_size_mb = file_size / (1024 * 1024)
|
| 68 |
+
|
| 69 |
+
logging.info(f"✅ Audio extracted successfully! Size: {file_size_mb:.2f} MB")
|
| 70 |
+
|
| 71 |
+
return output_file
|
| 72 |
+
|
| 73 |
+
except subprocess.TimeoutExpired:
|
| 74 |
+
logging.error("FFmpeg timeout - video too long")
|
| 75 |
+
raise Exception("Video too long for processing (max 1 minute)")
|
| 76 |
+
|
| 77 |
+
except Exception as e:
|
| 78 |
+
logging.error(f"Error extracting audio: {e}")
|
| 79 |
+
# حذف الملف الناقص لو موجود
|
| 80 |
+
if os.path.exists(output_file):
|
| 81 |
+
try:
|
| 82 |
+
os.remove(output_file)
|
| 83 |
+
except:
|
| 84 |
+
pass
|
| 85 |
+
raise
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def cleanup_old_files(output_dir: str = "temp_audio", max_age_hours: int = 24):
|
| 89 |
+
"""
|
| 90 |
+
حذف الملفات القديمة لتوفير المساحة
|
| 91 |
+
|
| 92 |
+
Args:
|
| 93 |
+
output_dir: مجلد الملفات المؤقتة
|
| 94 |
+
max_age_hours: حذف الملفات الأقدم من هذا العدد من الساعات
|
| 95 |
+
"""
|
| 96 |
+
try:
|
| 97 |
+
import time
|
| 98 |
+
current_time = time.time()
|
| 99 |
+
|
| 100 |
+
for filename in os.listdir(output_dir):
|
| 101 |
+
filepath = os.path.join(output_dir, filename)
|
| 102 |
+
if os.path.isfile(filepath):
|
| 103 |
+
file_age_hours = (current_time - os.path.getmtime(filepath)) / 3600
|
| 104 |
+
if file_age_hours > max_age_hours:
|
| 105 |
+
os.remove(filepath)
|
| 106 |
+
logging.info(f"Deleted old file: {filename}")
|
| 107 |
+
except Exception as e:
|
| 108 |
+
logging.warning(f"Cleanup error: {e}")
|