Reoo88 commited on
Commit
6a7a526
·
verified ·
1 Parent(s): d0fbc4d

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +95 -31
streamlit_app.py CHANGED
@@ -1,67 +1,131 @@
1
- import os, time, threading, subprocess, urllib.request, requests, re
 
 
2
  import streamlit as st
3
 
4
- # استخدم خط "Cairo" المعروف بدعمه الممتاز للعربية
5
- FONT_PATH = "/tmp/Cairo.ttf"
6
- FONT_URL = "https://github.com/google/fonts/raw/main/ofl/cairo/Cairo%5Bwght%5D.ttf"
7
- COMMENTS_FILE = "/tmp/comments.txt"
8
  COMMENTS_URL = "https://reoo88-signserver.hf.space/comments"
9
 
10
  if not os.path.exists(FONT_PATH):
11
  urllib.request.urlretrieve(FONT_URL, FONT_PATH)
12
 
13
- def clean_arabic_text(text):
14
- """تحتفظ فقط بالحروف العربية والإنجليزية والأرقام والمسافات وعلامات الترقيم الأساسية"""
15
- # تسمح بالعربية، الإنجليزية، الأرقام، المسافات، النقطتين، @, ., ,, !, ?
16
- return re.sub(r'[^\u0600-\u06FF\u0750-\u077F\w\s:@.,!?]+', '', text, flags=re.UNICODE)
17
 
 
18
  def fetch_comments():
 
19
  try:
20
  r = requests.get(COMMENTS_URL, timeout=5)
21
  if r.status_code == 200:
22
- # تنظيف النص من الرموز الغريبة
23
- cleaned_lines = [clean_arabic_text(line) for line in r.text.split('\n')]
24
- cleaned_text = '\n'.join(cleaned_lines)
25
- with open(COMMENTS_FILE, "w", encoding="utf-8") as f:
26
- f.write(cleaned_text)
27
  print("✅ تم تحديث التعليقات")
28
  else:
29
  print(f"⚠️ فشل الجلب: {r.status_code}")
30
  except Exception as e:
31
- print(f"❌ خطأ في جلب التعليقات: {e}")
32
 
33
  def comments_updater():
34
  while True:
35
  time.sleep(3)
36
  fetch_comments()
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def start_stream(yt_key, username):
39
- # إنشاء ملف فارغ لتجنب أخطاء ffmpeg
40
- with open(COMMENTS_FILE, "w", encoding="utf-8") as f:
41
- f.write("")
42
  threading.Thread(target=comments_updater, daemon=True).start()
43
  time.sleep(3)
44
 
45
  sl_cmd = f"streamlink https://www.tiktok.com/@{username}/live best --hls-live-edge 3 --stdout"
46
 
47
- # أمر ffmpeg مع drawtext بخط Cairo
48
- ff_cmd = (
49
- f"ffmpeg -thread_queue_size 8192 -i pipe:0 "
50
- f"-vf \"drawtext=textfile='{COMMENTS_FILE}':reload=1:fontfile={FONT_PATH}:fontsize=26:fontcolor=white@0.9:"
51
- f"x=10:y=h-th-50:shadowx=2:shadowy=2:shadowcolor=black@0.6\" "
52
- f"-c:v libx264 -preset ultrafast -tune zerolatency -b:v 1500k -maxrate 2000k -bufsize 3000k -g 30 "
53
- f"-c:a aac -ar 48000 -b:a 192k -ac 2 "
54
- f"-f flv rtmp://a.rtmp.youtube.com/live2/{yt_key}"
55
- )
 
 
 
 
 
 
56
 
57
- full_cmd = f"{sl_cmd} | {ff_cmd}"
58
- subprocess.Popen(full_cmd, shell=True).wait()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- st.title("بث تيك توك مع تعليقات عربية نظيفة")
 
61
  with st.form("f"):
62
  user = st.text_input("معرف تيك توك", "majd.alban")
63
  key = st.text_input("مفتاح يوتيوب", type="password")
64
  if st.form_submit_button("ابدأ"):
65
  if user and key:
66
  threading.Thread(target=start_stream, args=(key, user)).start()
67
- st.success("تم البث! التعليقات ستظهر في الأسفل بدون رموز.")
 
1
+ import os, time, threading, subprocess, urllib.request, requests
2
+ from io import BytesIO
3
+ from PIL import Image, ImageDraw, ImageFont
4
  import streamlit as st
5
 
6
+ # ---------- إعدادات ----------
7
+ FONT_PATH = "/tmp/Palestine.ttf"
8
+ FONT_URL = "https://github.com/mokhtarbsaid/rare-arabic-fonts/raw/main/palestine/palestine-regular.ttf"
 
9
  COMMENTS_URL = "https://reoo88-signserver.hf.space/comments"
10
 
11
  if not os.path.exists(FONT_PATH):
12
  urllib.request.urlretrieve(FONT_URL, FONT_PATH)
13
 
14
+ latest_comments_text = ""
15
+ text_lock = threading.Lock()
 
 
16
 
17
+ # ---------- جلب التعليقات ----------
18
  def fetch_comments():
19
+ global latest_comments_text
20
  try:
21
  r = requests.get(COMMENTS_URL, timeout=5)
22
  if r.status_code == 200:
23
+ with text_lock:
24
+ latest_comments_text = r.text.strip()
 
 
 
25
  print("✅ تم تحديث التعليقات")
26
  else:
27
  print(f"⚠️ فشل الجلب: {r.status_code}")
28
  except Exception as e:
29
+ print(f"❌ خطأ: {e}")
30
 
31
  def comments_updater():
32
  while True:
33
  time.sleep(3)
34
  fetch_comments()
35
 
36
+ # ---------- إنشاء صورة التعليقات ----------
37
+ def create_comment_overlay():
38
+ width, height = 720, 1280
39
+ img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
40
+ draw = ImageDraw.Draw(img)
41
+
42
+ try:
43
+ font = ImageFont.truetype(FONT_PATH, 24)
44
+ except:
45
+ font = ImageFont.load_default()
46
+
47
+ with text_lock:
48
+ lines = latest_comments_text.split('\n')
49
+ # إظهار آخر 6 تعليقات فقط لتجنب الازدحام
50
+ lines = lines[-6:] if len(lines) > 6 else lines
51
+
52
+ # رسم التعليقات من الأسفل إلى الأعلى
53
+ y_offset = height - 40
54
+ for line in reversed(lines):
55
+ if line.strip():
56
+ draw.text(
57
+ (15, y_offset), line.strip(),
58
+ font=font, fill=(255, 255, 255, 255),
59
+ shadow_color=(0, 0, 0, 200), shadow_offset=(2, 2)
60
+ )
61
+ y_offset -= 35
62
+
63
+ buf = BytesIO()
64
+ img.save(buf, format="PNG")
65
+ buf.seek(0)
66
+ return buf.read()
67
+
68
+ # ---------- تشغيل البث ----------
69
  def start_stream(yt_key, username):
70
+ # بدء جلب التعليقات
 
 
71
  threading.Thread(target=comments_updater, daemon=True).start()
72
  time.sleep(3)
73
 
74
  sl_cmd = f"streamlink https://www.tiktok.com/@{username}/live best --hls-live-edge 3 --stdout"
75
 
76
+ ff_cmd = [
77
+ "ffmpeg",
78
+ "-thread_queue_size", "8192",
79
+ "-i", "pipe:0", # فيديو تيك توك
80
+ "-f", "image2pipe",
81
+ "-r", "2", # تحديث الصورة مرتين في الثانية
82
+ "-i", "pipe:1", # صورة التعليقات
83
+ "-filter_complex",
84
+ "[0:v]scale=720:1280[vid];[vid][1:v]overlay=0:0",
85
+ "-map", "[outv]", "-map", "0:a?",
86
+ "-c:v", "libx264", "-preset", "ultrafast", "-tune", "zerolatency",
87
+ "-b:v", "1500k", "-maxrate", "2000k", "-bufsize", "3000k", "-g", "30",
88
+ "-c:a", "aac", "-ar", "48000", "-b:a", "192k", "-ac", "2",
89
+ "-f", "flv", f"rtmp://a.rtmp.youtube.com/live2/{yt_key}"
90
+ ]
91
 
92
+ try:
93
+ sl_process = subprocess.Popen(sl_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
94
+ ffmpeg_process = subprocess.Popen(ff_cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
95
+
96
+ # خيط لتغذية ffmpeg بصورة التعليقات
97
+ def feed_overlay():
98
+ while ffmpeg_process.poll() is None:
99
+ try:
100
+ img_data = create_comment_overlay()
101
+ ffmpeg_process.stdin.write(img_data)
102
+ ffmpeg_process.stdin.flush()
103
+ except:
104
+ break
105
+ time.sleep(0.5)
106
+ ffmpeg_process.stdin.close()
107
+
108
+ threading.Thread(target=feed_overlay, daemon=True).start()
109
+
110
+ # تغذية الفيديو من streamlink
111
+ while ffmpeg_process.poll() is None:
112
+ data = sl_process.stdout.read(8192)
113
+ if not data:
114
+ break
115
+ ffmpeg_process.stdin.write(data)
116
+
117
+ sl_process.stdout.close()
118
+ ffmpeg_process.wait()
119
+ sl_process.wait()
120
+ except Exception as e:
121
+ print(f"[ERROR] {e}")
122
 
123
+ # ---------- واجهة المستخدم ----------
124
+ st.title("بث تيك توك مع تعليقات - وضع الصور")
125
  with st.form("f"):
126
  user = st.text_input("معرف تيك توك", "majd.alban")
127
  key = st.text_input("مفتاح يوتيوب", type="password")
128
  if st.form_submit_button("ابدأ"):
129
  if user and key:
130
  threading.Thread(target=start_stream, args=(key, user)).start()
131
+ st.success("تم البث! التعليقات ستظهر في الأسفل.")