Reoo88 commited on
Commit
a9e6502
·
verified ·
1 Parent(s): 1a2437c

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +134 -91
streamlit_app.py CHANGED
@@ -1,14 +1,16 @@
1
  import os
2
  import time
3
  import subprocess
4
- import json
 
 
 
5
 
6
  TIKTOK_USERNAME = "@lolo33yy"
7
- ANALYSIS_DURATION = 300 # 5 دقائق
8
- ANALYSIS_LOG = "/tmp/analysis_verbose.log"
9
- VSTATS_FILE = "/tmp/vstats.txt"
10
- PROGRESS_FILE = "/tmp/progress.txt"
11
- MONITOR_LOG = "/tmp/analysis_monitor.log"
12
 
13
  TIKTOK_COOKIES = os.getenv("TIKTOK_COOKIES", "")
14
  TIKTOK_COOKIES_ADULT = os.getenv("TIKTOK_COOKIES_ADULT", "")
@@ -20,6 +22,15 @@ def log(msg):
20
  with open(MONITOR_LOG, "a", encoding="utf-8") as f:
21
  f.write(line + "\n")
22
 
 
 
 
 
 
 
 
 
 
23
  def save_cookies():
24
  if TIKTOK_COOKIES:
25
  with open("/tmp/tiktok_cookies.txt", "w") as f:
@@ -50,96 +61,128 @@ def get_tiktok_stream_url():
50
  pass
51
  return None
52
 
53
- def run_deep_analysis(stream_url):
54
- """تشغيل ffmpeg لمدة 5 دقائق لتجميع معلومات شاملة"""
55
- log(f"🔬 بدء تحليل عميق لمدة {ANALYSIS_DURATION} ثانية...")
 
 
56
 
57
  cmd = [
58
- "ffmpeg",
 
59
  "-re",
60
- "-analyzeduration", "100M",
61
- "-probesize", "100M",
 
 
 
 
 
 
 
 
62
  "-i", stream_url,
63
- "-c", "copy", # نسخ بدون ترميز لتسريع التحليل
64
- "-f", "null", "-", # عدم الإخراج
65
- "-t", str(ANALYSIS_DURATION),
66
- "-vstats_file", VSTATS_FILE,
67
- "-progress", PROGRESS_FILE,
68
- "-loglevel", "verbose",
69
- "-report" # ينشئ ملف ffmpeg-*.log إضافي
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  ]
71
 
72
- try:
73
- with open(ANALYSIS_LOG, "w") as log_file:
74
- proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL,
75
- stderr=log_file)
76
- log(f"✅ بدأ التحليل – PID: {proc.pid}")
77
- proc.wait(timeout=ANALYSIS_DURATION + 30)
78
- log("✅ انتهى التحليل.")
79
- except subprocess.TimeoutExpired:
80
- log("⚠️ انتهت مهلة التحليل – تم إيقاف العملية.")
81
- proc.kill()
82
- except Exception as e:
83
- log(f"❌ خطأ أثناء التحليل: {e}")
84
- return
85
-
86
- # تحليل النتائج
87
- summarize_results()
88
-
89
- def summarize_results():
90
- """قراءة الملفات المجمعة وطباعة ملخص"""
91
- log("📊 ====== تقرير التحليل الشامل ======")
92
-
93
- # 1. قراءة ملف التقدم (آخر إحصائيات)
94
- if os.path.exists(PROGRESS_FILE):
95
- with open(PROGRESS_FILE) as f:
96
- lines = f.readlines()
97
- if lines:
98
- log("📈 إحصائيات نهاية التحليل:")
99
- for line in lines[-30:]:
100
- log(f" {line.strip()}")
101
-
102
- # 2. قراءة إحصائيات الإطارات
103
- if os.path.exists(VSTATS_FILE):
104
- with open(VSTATS_FILE) as f:
105
- vstats = f.read()
106
- frames = vstats.count('\n')
107
- log(f"🎞️ عدد الإطارات المعالجة: {frames}")
108
-
109
- # 3. استخراج الأخطاء الهامة من السجل
110
- if os.path.exists(ANALYSIS_LOG):
111
- with open(ANALYSIS_LOG) as f:
112
- log_text = f.read()
113
- errors = {
114
- "Packet corrupt": 0,
115
- "missing picture": 0,
116
- "Could not open encoder": 0,
117
- "Non-monotonous DTS": 0,
118
- "Invalid data found": 0,
119
- "Error": 0,
120
- "EOF": 0,
121
- }
122
- for line in log_text.splitlines():
123
- for keyword in errors:
124
- if keyword in line:
125
- errors[keyword] += 1
126
- log("⚠️ ملخص الأخطاء:")
127
- for k, v in errors.items():
128
- if v > 0:
129
- log(f" {k}: {v} مرة")
130
- # عرض آخر 15 سطراً
131
- lines = log_text.splitlines()
132
- log("📋 آخر 15 سطر من السجل:")
133
- for line in lines[-15:]:
134
- log(f" {line}")
135
-
136
- log("📊 ====== نهاية التقرير ======")
137
 
138
  if __name__ == "__main__":
139
- log("🔍 أداة التحليل العميق (5 دقائق) - انتظر حتى ينتهي")
140
- stream_url = get_tiktok_stream_url()
141
- if stream_url:
142
- log(f"✅ تم جلب رابط البث")
143
- run_deep_analysis(stream_url)
144
- else:
145
- log("❌ لم يتم العثور على بث مباشر للمذيع")
 
1
  import os
2
  import time
3
  import subprocess
4
+ import threading
5
+ import fcntl
6
+ import signal
7
+ import psutil
8
 
9
  TIKTOK_USERNAME = "@lolo33yy"
10
+ STREAM_KEY = "p3dq-5cex-bc1k-vet7-bsyx"
11
+ FFMPEG_LOG = "/tmp/ffmpeg.log"
12
+ MONITOR_LOG = "/tmp/monitor.log"
13
+ LOCK_FILE = "/tmp/app_monitor_core.lock"
 
14
 
15
  TIKTOK_COOKIES = os.getenv("TIKTOK_COOKIES", "")
16
  TIKTOK_COOKIES_ADULT = os.getenv("TIKTOK_COOKIES_ADULT", "")
 
22
  with open(MONITOR_LOG, "a", encoding="utf-8") as f:
23
  f.write(line + "\n")
24
 
25
+ def kill_process_tree(pid):
26
+ try:
27
+ parent = psutil.Process(pid)
28
+ for child in parent.children(recursive=True):
29
+ child.kill()
30
+ parent.kill()
31
+ except:
32
+ pass
33
+
34
  def save_cookies():
35
  if TIKTOK_COOKIES:
36
  with open("/tmp/tiktok_cookies.txt", "w") as f:
 
61
  pass
62
  return None
63
 
64
+ def start_stream_final(stream_key, stream_url):
65
+ if not stream_key or not stream_url:
66
+ return None
67
+ log("🎬 بدء البث (تعويض fps المنخفض)...")
68
+ rtmp_url = f"rtmp://a.rtmp.youtube.com/live2/{stream_key}"
69
 
70
  cmd = [
71
+ "nice", "-n", "19", "ffmpeg",
72
+ "-hide_banner", "-loglevel", "verbose",
73
  "-re",
74
+ "-analyzeduration", "50M",
75
+ "-probesize", "50M",
76
+ "-thread_queue_size", "65535",
77
+ "-rtbufsize", "512M",
78
+ "-reconnect", "1",
79
+ "-reconnect_streamed", "1",
80
+ "-reconnect_delay_max", "15",
81
+ "-timeout", "10000000",
82
+ "-multiple_requests", "1",
83
+ "-http_persistent", "1",
84
  "-i", stream_url,
85
+ "-err_detect", "ignore_err",
86
+ "-fflags", "+genpts+igndts+discardcorrupt",
87
+ "-avoid_negative_ts", "make_zero",
88
+ "-use_wallclock_as_timestamps", "1",
89
+ "-correct_ts_overflow", "1",
90
+ "-max_interleave_delta", "0",
91
+ "-vf", "scale=1080:1920:force_original_aspect_ratio=increase,pad=1080:1920:(ow-iw)/2:(oh-ih)/2:black:eval=frame",
92
+ "-c:v", "libx264",
93
+ "-preset", "ultrafast",
94
+ "-crf", "18",
95
+ "-maxrate", "8000k",
96
+ "-minrate", "5000k",
97
+ "-bufsize", "16000k",
98
+ "-g", "60",
99
+ "-vsync", "2", # ✅ إسقاط / تكرار الإطارات
100
+ "-r", "30", # ✅ إجبار 30fps على الإخراج
101
+ "-x264-params", "nal-hrd=cbr",
102
+ "-pix_fmt", "yuv420p",
103
+ "-color_range", "tv",
104
+ "-color_primaries", "bt709",
105
+ "-color_trc", "bt709",
106
+ "-colorspace", "bt709",
107
+ "-c:a", "aac",
108
+ "-b:a", "192k",
109
+ "-ac", "2",
110
+ "-ar", "44100",
111
+ "-async", "1",
112
+ "-af", "alimiter=limit=0.95:attack=5:release=50",
113
+ "-max_muxing_queue_size", "65535",
114
+ "-max_delay", "5000000",
115
+ "-flvflags", "no_duration_filesize+add_keyframe_index",
116
+ "-f", "flv", rtmp_url
117
  ]
118
 
119
+ with open(FFMPEG_LOG, "w") as stderr_file:
120
+ proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL,
121
+ stderr=stderr_file, preexec_fn=os.setsid)
122
+ log(f"✅ ffmpeg PID: {proc.pid}")
123
+ return {"ffmpeg": proc}
124
+
125
+ def run_monitor():
126
+ if os.path.exists(LOCK_FILE):
127
+ try:
128
+ with open(LOCK_FILE) as f:
129
+ os.kill(int(f.read().strip()), 0)
130
+ log("🔒 محرك آخر يعمل")
131
+ return
132
+ except:
133
+ os.remove(LOCK_FILE)
134
+
135
+ with open(LOCK_FILE, "w") as f:
136
+ f.write(str(os.getpid()))
137
+
138
+ is_streaming = False
139
+ processes = None
140
+ was_streaming = False
141
+ consecutive_fails = 0
142
+
143
+ log("🚀 محرك البث (إصلاح fps)")
144
+
145
+ while True:
146
+ try:
147
+ stream_url = get_tiktok_stream_url()
148
+
149
+ if stream_url:
150
+ if not was_streaming:
151
+ log("🟢 بدء بث جديد...")
152
+ if processes:
153
+ kill_process_tree(processes["ffmpeg"].pid)
154
+ processes = start_stream_final(STREAM_KEY, stream_url)
155
+ if processes:
156
+ is_streaming = True
157
+ was_streaming = True
158
+ consecutive_fails = 0
159
+ else:
160
+ if is_streaming and processes and processes["ffmpeg"].poll() is not None:
161
+ log("⚠️ ffmpeg مات، إعادة تشغيل...")
162
+ processes = start_stream_final(STREAM_KEY, stream_url)
163
+ if not processes:
164
+ is_streaming = False
165
+ was_streaming = False
166
+ else:
167
+ consecutive_fails += 1
168
+ if was_streaming and consecutive_fails > 3:
169
+ log("⏹️ توقف البث")
170
+ if processes:
171
+ kill_process_tree(processes["ffmpeg"].pid)
172
+ processes = None
173
+ is_streaming = False
174
+ was_streaming = False
175
+ consecutive_fails = 0
176
+
177
+ time.sleep(10)
178
+
179
+ except Exception as e:
180
+ log(f"💥 خطأ: {e}")
181
+ time.sleep(10)
 
 
182
 
183
  if __name__ == "__main__":
184
+ log("✅ بدء تشغيل المحرك النهائي")
185
+ t = threading.Thread(target=run_monitor, daemon=True)
186
+ t.start()
187
+ while True:
188
+ time.sleep(3600)