Update streamlit_app.py
Browse files- streamlit_app.py +179 -80
streamlit_app.py
CHANGED
|
@@ -1,131 +1,230 @@
|
|
|
|
|
| 1 |
import asyncio
|
| 2 |
import os
|
| 3 |
-
import sys
|
| 4 |
import time
|
| 5 |
import subprocess
|
| 6 |
import requests
|
| 7 |
from TikTokLive import TikTokLiveClient
|
| 8 |
|
| 9 |
-
# استيراد الأخطاء من المسار ال
|
| 10 |
try:
|
| 11 |
-
from TikTokLive.client.errors import UserNotFoundError
|
| 12 |
except ImportError:
|
| 13 |
try:
|
| 14 |
-
from TikTokLive.types.errors import UserNotFoundError
|
| 15 |
except ImportError:
|
| 16 |
-
# حل بديل في حال اختلاف إصدار المكتبة لتفادي توقف البرنامج تماماً
|
| 17 |
class UserNotFoundError(Exception): pass
|
| 18 |
-
class UserOfflineError(Exception): pass
|
| 19 |
|
| 20 |
-
#
|
| 21 |
-
|
| 22 |
-
|
| 23 |
|
| 24 |
-
# عدد
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
# ال
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
RECORDING_ENGINE = "streamlink"
|
| 33 |
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
# =======================================================
|
| 37 |
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
def send_notification(message):
|
| 41 |
-
|
| 42 |
-
print(f"[تنبيه] {message}")
|
| 43 |
-
if DISCORD_WEBHOOK_URL:
|
| 44 |
try:
|
| 45 |
-
requests.post(
|
| 46 |
except Exception as e:
|
| 47 |
-
print(f"
|
| 48 |
|
|
|
|
| 49 |
async def check_if_live(username):
|
| 50 |
-
"""
|
| 51 |
-
✅ الدالة المصلحة للتحقق من أن المذيع متصل بالبث المباشر
|
| 52 |
-
"""
|
| 53 |
client = TikTokLiveClient(unique_id=username)
|
| 54 |
try:
|
| 55 |
-
# الاستدعاء الصحيح وال
|
| 56 |
is_live = await client.is_live()
|
| 57 |
-
return is_live
|
| 58 |
except UserNotFoundError:
|
| 59 |
-
|
| 60 |
-
return False
|
| 61 |
except Exception as e:
|
| 62 |
-
|
| 63 |
-
print(f"⚠️ فشل التحقق من الحالة حالياً: {e}")
|
| 64 |
-
return False
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
timestamp = time.strftime("%Y%m%d_%H%M%S")
|
| 69 |
clean_user = username.replace("@", "")
|
| 70 |
-
|
|
|
|
| 71 |
live_url = f"https://www.tiktok.com/{username}/live"
|
| 72 |
|
| 73 |
-
|
|
|
|
| 74 |
|
| 75 |
-
|
| 76 |
-
if RECORDING_ENGINE == "streamlink":
|
| 77 |
command = ["streamlink", live_url, "best", "-o", output_file, "--stream-segment-threads", "3"]
|
| 78 |
-
elif
|
| 79 |
command = ["ffmpeg", "-i", live_url, "-c", "copy", "-y", output_file]
|
| 80 |
else:
|
| 81 |
command = ["yt-dlp", "-o", output_file, live_url]
|
| 82 |
|
| 83 |
-
print(f"🚀 تشغيل أمر التسجيل: {' '.join(command)}")
|
| 84 |
try:
|
| 85 |
-
# تشغيل التسجيل كعملية فرعية لمتابعة تقدم التحميل في الوقت الفعلي
|
| 86 |
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
|
|
|
| 87 |
|
| 88 |
-
#
|
|
|
|
| 89 |
for line in process.stdout:
|
| 90 |
-
|
| 91 |
-
|
|
|
|
| 92 |
|
| 93 |
process.wait()
|
| 94 |
-
|
|
|
|
| 95 |
except Exception as e:
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
print(f"📹 مجلد حفظ الفيديوهات: {SAVE_DIR}")
|
| 104 |
-
print(f"⚙️ محرك التسجيل المعتمد: {RECORDING_ENGINE}")
|
| 105 |
-
print("=" * 50)
|
| 106 |
-
|
| 107 |
-
send_notification(f"🚀 تم تشغيل سكربت المراقبة لـ {TARGET_USERNAME}")
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
-
if
|
| 114 |
-
|
| 115 |
-
|
| 116 |
else:
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
import asyncio
|
| 3 |
import os
|
|
|
|
| 4 |
import time
|
| 5 |
import subprocess
|
| 6 |
import requests
|
| 7 |
from TikTokLive import TikTokLiveClient
|
| 8 |
|
| 9 |
+
# استيراد الأخطاء من المسارات البديلة لتفادي أي تعارض في إصدارات بايثون
|
| 10 |
try:
|
| 11 |
+
from TikTokLive.client.errors import UserNotFoundError
|
| 12 |
except ImportError:
|
| 13 |
try:
|
| 14 |
+
from TikTokLive.types.errors import UserNotFoundError
|
| 15 |
except ImportError:
|
|
|
|
| 16 |
class UserNotFoundError(Exception): pass
|
|
|
|
| 17 |
|
| 18 |
+
# إعداد مجلد الحفظ للفيديوهات المسجلة
|
| 19 |
+
SAVE_DIR = "./recordings"
|
| 20 |
+
os.makedirs(SAVE_DIR, exist_ok=True)
|
| 21 |
|
| 22 |
+
# إعداد واجهة Streamlit الملونة والحديثة
|
| 23 |
+
st.set_page_config(
|
| 24 |
+
page_title="TikTok Live Auto-Recorder Pro",
|
| 25 |
+
page_icon="🔴",
|
| 26 |
+
layout="wide",
|
| 27 |
+
initial_sidebar_state="expanded"
|
| 28 |
+
)
|
| 29 |
|
| 30 |
+
# تنسيق الواجهة بالـ CSS لتظهر بشكل احترافي ومناسب للغة العربية والانجليزية
|
| 31 |
+
st.markdown("""
|
| 32 |
+
<style>
|
| 33 |
+
.main-title {
|
| 34 |
+
font-size: 2.2rem;
|
| 35 |
+
font-weight: 800;
|
| 36 |
+
color: #FF0050;
|
| 37 |
+
text-align: center;
|
| 38 |
+
margin-bottom: 0.5rem;
|
| 39 |
+
font-family: 'Cairo', sans-serif;
|
| 40 |
+
}
|
| 41 |
+
.subtitle {
|
| 42 |
+
font-size: 1rem;
|
| 43 |
+
color: #a0aec0;
|
| 44 |
+
text-align: center;
|
| 45 |
+
margin-bottom: 2rem;
|
| 46 |
+
font-family: 'Cairo', sans-serif;
|
| 47 |
+
}
|
| 48 |
+
.card {
|
| 49 |
+
background-color: #1a202c;
|
| 50 |
+
padding: 1.5rem;
|
| 51 |
+
border-radius: 15px;
|
| 52 |
+
border: 1px solid #2d3748;
|
| 53 |
+
margin-bottom: 1rem;
|
| 54 |
+
}
|
| 55 |
+
</style>
|
| 56 |
+
""", unsafe_allow_html=True)
|
| 57 |
|
| 58 |
+
st.markdown('<div class="main-title">🔴 TikTok Live Auto-Recorder Pro</div>', unsafe_allow_html=True)
|
| 59 |
+
st.markdown('<div class="subtitle">سجل بثوث التيك توك التلقائية 24/7 مع واجهة ويب متكاملة على Hugging Face</div>', unsafe_allow_html=True)
|
|
|
|
| 60 |
|
| 61 |
+
# شريط الإعدادات الجانبي (Sidebar)
|
| 62 |
+
st.sidebar.header("⚙️ إعدادات التسجيل")
|
|
|
|
| 63 |
|
| 64 |
+
# تم وضع اسم الحساب المختار "s.og94" كقيمة افتراضية أساسية ومضمونة
|
| 65 |
+
raw_username = st.sidebar.text_input("👤 معرف المذيع (Target Username)", value="s.og94", help="سيتم مراقبة وتسجيل هذا الحساب تلقائياً")
|
| 66 |
+
|
| 67 |
+
# معالجة ذكية لاسم الحساب للتأكد من وجود علامة @ في البداية
|
| 68 |
+
target_username = raw_username.strip()
|
| 69 |
+
if target_username and not target_username.startswith("@"):
|
| 70 |
+
target_username = "@" + target_username
|
| 71 |
+
|
| 72 |
+
poll_interval = st.sidebar.slider("⏱️ فحص كل (بالثواني)", min_value=15, max_value=300, value=60, step=15)
|
| 73 |
+
recording_engine = st.sidebar.selectbox("📹 محرك حفظ الفيديو", ["streamlink", "ffmpeg", "yt-dlp"], index=0)
|
| 74 |
+
discord_webhook = st.sidebar.text_input("🔔 رابط ديسكورد للتنبيهات (اختياري)", value="")
|
| 75 |
+
|
| 76 |
+
# إدارة حالة التشغيل التلقائي في الخلفية
|
| 77 |
+
if 'is_running' not in st.session_state:
|
| 78 |
+
st.session_state.is_running = False
|
| 79 |
+
if 'logs' not in st.session_state:
|
| 80 |
+
st.session_state.logs = []
|
| 81 |
+
|
| 82 |
+
def log_message(message, type="info"):
|
| 83 |
+
timestamp = time.strftime("%H:%M:%S")
|
| 84 |
+
prefix = "ℹ️"
|
| 85 |
+
if type == "success": prefix = "🟢"
|
| 86 |
+
elif type == "error": prefix = "❌"
|
| 87 |
+
elif type == "warn": prefix = "⚠️"
|
| 88 |
+
|
| 89 |
+
log_str = f"[{timestamp}] {prefix} {message}"
|
| 90 |
+
st.session_state.logs.append(log_str)
|
| 91 |
+
print(log_str)
|
| 92 |
|
| 93 |
def send_notification(message):
|
| 94 |
+
if discord_webhook:
|
|
|
|
|
|
|
| 95 |
try:
|
| 96 |
+
requests.post(discord_webhook, json={"content": message})
|
| 97 |
except Exception as e:
|
| 98 |
+
print(f"Error sending webhook: {e}")
|
| 99 |
|
| 100 |
+
# الفحص الفعلي لحالة البث باستخدام دالة بايثون الصحيحة المصلحة
|
| 101 |
async def check_if_live(username):
|
|
|
|
|
|
|
|
|
|
| 102 |
client = TikTokLiveClient(unique_id=username)
|
| 103 |
try:
|
| 104 |
+
# ✅ الاستدعاء الصحيح والمضمون لحالة البث
|
| 105 |
is_live = await client.is_live()
|
| 106 |
+
return is_live, "success"
|
| 107 |
except UserNotFoundError:
|
| 108 |
+
return False, "not_found"
|
|
|
|
| 109 |
except Exception as e:
|
| 110 |
+
return False, f"error: {str(e)}"
|
|
|
|
|
|
|
| 111 |
|
| 112 |
+
# محرك التسجيل والتقاط البث وحفظه
|
| 113 |
+
def run_recording(username):
|
| 114 |
timestamp = time.strftime("%Y%m%d_%H%M%S")
|
| 115 |
clean_user = username.replace("@", "")
|
| 116 |
+
output_filename = f"{clean_user}_{timestamp}.mp4"
|
| 117 |
+
output_file = os.path.join(SAVE_DIR, output_filename)
|
| 118 |
live_url = f"https://www.tiktok.com/{username}/live"
|
| 119 |
|
| 120 |
+
log_message(f"بدء سحب البث للمذيع {username} باستخدام {recording_engine}...", "success")
|
| 121 |
+
send_notification(f"🔴 المذيع {username} متصل الآن! بدأ التسجيل وحفظ الملف باسم {output_filename}")
|
| 122 |
|
| 123 |
+
if recording_engine == "streamlink":
|
|
|
|
| 124 |
command = ["streamlink", live_url, "best", "-o", output_file, "--stream-segment-threads", "3"]
|
| 125 |
+
elif recording_engine == "ffmpeg":
|
| 126 |
command = ["ffmpeg", "-i", live_url, "-c", "copy", "-y", output_file]
|
| 127 |
else:
|
| 128 |
command = ["yt-dlp", "-o", output_file, live_url]
|
| 129 |
|
|
|
|
| 130 |
try:
|
|
|
|
| 131 |
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
| 132 |
+
log_message(f"تم إطلاق عملية التسجيل بنجاح. جاري الحفظ في المجلد المحلي...", "info")
|
| 133 |
|
| 134 |
+
# قراءة مخرجات التسجيل وعرض أول 5 أسطر لتأكيد الحفظ في الواجهة
|
| 135 |
+
lines_read = 0
|
| 136 |
for line in process.stdout:
|
| 137 |
+
if lines_read < 5:
|
| 138 |
+
log_message(f"[تحميل] {line.strip()}", "info")
|
| 139 |
+
lines_read += 1
|
| 140 |
|
| 141 |
process.wait()
|
| 142 |
+
log_message(f"تم الانتهاء من تسجيل البث وحفظ الملف بنجاح! 💾", "success")
|
| 143 |
+
send_notification(f"⏹️ تم حفظ البث المباشر لـ {username} بنجاح في Hugging Face.")
|
| 144 |
except Exception as e:
|
| 145 |
+
log_message(f"حدث خطأ أثناء التسجيل: {e}", "error")
|
| 146 |
+
|
| 147 |
+
# تقسيم الشاشة لعرض جميل ومنسق
|
| 148 |
+
col1, col2 = st.columns([2, 1])
|
| 149 |
+
|
| 150 |
+
with col1:
|
| 151 |
+
st.subheader("🎮 لوحة التحكم والتشغيل")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
+
# أزرار البدء والإيقاف
|
| 154 |
+
c_btn1, c_btn2 = st.columns(2)
|
| 155 |
+
with c_btn1:
|
| 156 |
+
if st.button("🚀 بدء مراقبة البث المباشر تلقائياً", use_container_width=True, disabled=st.session_state.is_running):
|
| 157 |
+
st.session_state.is_running = True
|
| 158 |
+
st.session_state.logs = []
|
| 159 |
+
log_message(f"تم تفعيل نظام المراقبة التلقائية للمذيع {target_username}...", "success")
|
| 160 |
+
st.rerun()
|
| 161 |
+
|
| 162 |
+
with c_btn2:
|
| 163 |
+
if st.button("⏹️ إيقاف المراقبة مؤقتاً", use_container_width=True, disabled=not st.session_state.is_running):
|
| 164 |
+
st.session_state.is_running = False
|
| 165 |
+
log_message("تم إيقاف نظام المراقبة يدوياً.", "warn")
|
| 166 |
+
st.rerun()
|
| 167 |
+
|
| 168 |
+
# حلقة الفحص المستمر
|
| 169 |
+
if st.session_state.is_running:
|
| 170 |
+
st.info(f"🔄 السكربت نشط ويقوم بمراقبة الحساب {target_username} كل {poll_interval} ثانية...")
|
| 171 |
|
| 172 |
+
if not target_username.strip() or target_username == "@":
|
| 173 |
+
st.warning("⚠️ يرجى كتابة معرف حقيقي للمذيع في القائمة الجانبية لبدء التسجيل بشكل صحيح!")
|
| 174 |
+
st.session_state.is_running = False
|
| 175 |
else:
|
| 176 |
+
# فحص الحالة الفعلي للمذيع s.og94
|
| 177 |
+
with st.spinner(f"جاري التحقق من حالة اتصال {target_username} حالياً..."):
|
| 178 |
+
is_live, status = asyncio.run(check_if_live(target_username))
|
| 179 |
+
|
| 180 |
+
if is_live:
|
| 181 |
+
st.success(f"🔴 المذيع {target_username} متصل حالياً بالبث المباشر!")
|
| 182 |
+
run_recording(target_username)
|
| 183 |
+
else:
|
| 184 |
+
if status == "not_found":
|
| 185 |
+
st.error(f"❌ اسم المستخدم {target_username} غير موجود على تيك توك. يرجى مراجعته.")
|
| 186 |
+
st.session_state.is_running = False
|
| 187 |
+
elif "error" in status:
|
| 188 |
+
st.warning(f"⚠️ تعذر التحقق بسبب قيود الحماية أو الشبكة: {status}. سنحاول مجدداً...")
|
| 189 |
+
else:
|
| 190 |
+
st.info(f"😴 المذيع {target_username} غير متصل بالبث حالياً. سنعيد المحاولة تلقائياً...")
|
| 191 |
+
|
| 192 |
+
# عد تنازلي بسيط قبل التحديث القادم
|
| 193 |
+
time.sleep(5)
|
| 194 |
+
st.rerun()
|
| 195 |
+
else:
|
| 196 |
+
st.warning("💤 النظام متوقف حالياً. اضغط على زر البدء بالأعلى لتنشيط المراقبة التلقائية الحية.")
|
| 197 |
|
| 198 |
+
# سجلات وحدة التحكم المباشرة (Console Logs)
|
| 199 |
+
st.subheader("📋 سجل الأحداث المباشر (Logs)")
|
| 200 |
+
if st.session_state.logs:
|
| 201 |
+
st.code("\n".join(st.session_state.logs), language="bash")
|
| 202 |
+
else:
|
| 203 |
+
st.text("لا توجد سجلات حالياً. ابدأ المراقبة لرؤية التقدم.")
|
| 204 |
+
|
| 205 |
+
with col2:
|
| 206 |
+
st.subheader("📁 الفيديوهات المسجلة (تحميل)")
|
| 207 |
+
|
| 208 |
+
# عرض وتحميل الفيديوهات التي تم تسجيلها وتخزينها على سيرفر Hugging Face
|
| 209 |
+
files = [f for f in os.listdir(SAVE_DIR) if f.endswith(".mp4")]
|
| 210 |
+
if files:
|
| 211 |
+
st.success(f"تم العثور على {len(files)} فيديو مسجل:")
|
| 212 |
+
for file in files:
|
| 213 |
+
file_path = os.path.join(SAVE_DIR, file)
|
| 214 |
+
file_size = os.path.getsize(file_path) / (1024 * 1024) # حجم الملف بالميجابايت
|
| 215 |
+
|
| 216 |
+
with st.container():
|
| 217 |
+
st.markdown(f"**📹 {file}**")
|
| 218 |
+
st.caption(f"الحجم: {file_size:.2f} ميجابايت")
|
| 219 |
+
|
| 220 |
+
with open(file_path, "rb") as f:
|
| 221 |
+
st.download_button(
|
| 222 |
+
label="📥 تنزيل الفيديو لجهازك",
|
| 223 |
+
data=f,
|
| 224 |
+
file_name=file,
|
| 225 |
+
mime="video/mp4",
|
| 226 |
+
key=file
|
| 227 |
+
)
|
| 228 |
+
st.markdown("---")
|
| 229 |
+
else:
|
| 230 |
+
st.info("مجلد التسجيلات فارغ حالياً. بمجرد بدء بث المذيع وتخزين الفيديو ستتمكن من تحميله مباشرة من هنا.")
|