bep40 commited on
Commit
17be8c7
·
verified ·
1 Parent(s): 4c90cb6

feat: shorts opens fullscreen TikTok feed (swipe between shorts) + 9:16 crop center

Browse files
Files changed (1) hide show
  1. app_wrapper.py +216 -51
app_wrapper.py CHANGED
@@ -1,30 +1,37 @@
1
- """Entry point that adds shorts carousel + TikTok-style article video, then imports app."""
2
- import sys, os
3
 
4
- # 1. First import shorts_carousel module
5
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
6
- from shorts_carousel import scrape_24h_news_shorts, render_shorts_carousel, SHORTS_CSS
7
 
8
- # 2. Now import and monkey-patch app
9
  import app
10
 
11
- # Extra CSS for TikTok-style article video (9:16)
12
- TIKTOK_ARTICLE_CSS = """
13
- /* TikTok-style video in article (9:16) */
14
- .bdp-tiktok-article-video{position:relative;width:100%;max-width:400px;margin:14px auto;aspect-ratio:9/16;background:#000;border-radius:14px;overflow:hidden}
15
- .bdp-tiktok-article-video video{width:100%;height:100%;object-fit:contain;display:block}
16
- .bdp-tiktok-article-video .tiktok-unmute-hint{position:absolute;top:10px;right:10px;background:rgba(0,0,0,.6);color:#fff;font-size:11px;padding:5px 10px;border-radius:14px;cursor:pointer;z-index:4}
17
- .bdp-tiktok-article-video .tiktok-seek-controls{position:absolute;bottom:50px;left:50%;transform:translateX(-50%);display:flex;gap:30px;z-index:4}
18
- .bdp-tiktok-article-video .tiktok-seek-btn{background:rgba(0,0,0,.4);color:#fff;border:none;padding:6px 12px;border-radius:16px;font-size:11px;cursor:pointer;backdrop-filter:blur(4px)}
 
 
 
 
 
 
 
 
 
 
19
  """
20
 
21
- # Patch CSS
22
  if "vslide-shorts-item" not in app.CSS:
23
  app.CSS += SHORTS_CSS
24
- if "bdp-tiktok-article-video" not in app.CSS:
25
- app.CSS += TIKTOK_ARTICLE_CSS
26
 
27
- # Patch render_homepage_html to include shorts carousel
28
  _orig_render_homepage = app.render_homepage_html
29
  def _patched_render_homepage(articles, *args, **kwargs):
30
  html = _orig_render_homepage(articles, *args, **kwargs)
@@ -44,41 +51,199 @@ def _patched_render_homepage(articles, *args, **kwargs):
44
  return html
45
  app.render_homepage_html = _patched_render_homepage
46
 
47
- # Patch render_article_html: when 24h article has video, show in TikTok 9:16 style
48
- _orig_render_article = app.render_article_html
49
- def _patched_render_article(article):
50
- html = _orig_render_article(article)
51
- # Only patch 24h articles that have video
52
- if article.get("source") == "24h" and any(item.get("type") == "video" for item in article.get("body", [])):
53
- # Replace standard video-wrap with TikTok 9:16 container
54
- html = html.replace(
55
- '<div class="bdp-video-wrap">',
56
- '<div class="bdp-tiktok-article-video">'
57
- )
58
- # Add seek controls and unmute hint after each video tag
59
- # Find video tags and add controls
60
- import re as _re
61
- def _add_controls(match):
62
- video_html = match.group(0)
63
- controls = (
64
- '<div class="tiktok-unmute-hint" onclick="var v=this.parentElement.querySelector(\'video\');v.muted=!v.muted;this.textContent=v.muted?\'🔇 Bật tiếng\':\'🔊 Đang phát\'">🔇 Bật tiếng</div>'
65
- '<div class="tiktok-seek-controls">'
66
- '<button class="tiktok-seek-btn" onclick="var v=this.closest(\'.bdp-tiktok-article-video\').querySelector(\'video\');v.currentTime=Math.max(0,v.currentTime-10)">⏪ 10s</button>'
67
- '<button class="tiktok-seek-btn" onclick="var v=this.closest(\'.bdp-tiktok-article-video\').querySelector(\'video\');v.currentTime=Math.min(v.duration||9999,v.currentTime+10)">10s ⏩</button>'
68
- '</div>'
69
- )
70
- return video_html + controls
71
- html = _re.sub(r'</video>', lambda m: '</video>' +
72
- '<div class="tiktok-unmute-hint" onclick="var v=this.parentElement.querySelector(\'video\');v.muted=!v.muted;this.textContent=v.muted?\'🔇 Bật tiếng\':\'🔊 Đang phát\'">🔇 Bật tiếng</div>'
73
- '<div class="tiktok-seek-controls">'
74
- '<button class="tiktok-seek-btn" onclick="var v=this.closest(\'.bdp-tiktok-article-video\').querySelector(\'video\');v.currentTime=Math.max(0,v.currentTime-10)">⏪ 10s</button>'
75
- '<button class="tiktok-seek-btn" onclick="var v=this.closest(\'.bdp-tiktok-article-video\').querySelector(\'video\');v.currentTime=Math.min(v.duration||9999,v.currentTime+10)">10s ⏩</button>'
76
- '</div>',
77
- html, count=1)
78
- return html
79
- app.render_article_html = _patched_render_article
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- # Re-create the Gradio demo with patched CSS
82
  app.demo.css = app.CSS
83
 
84
  # Export demo for Gradio to find
 
1
+ """Entry point that adds shorts TikTok feed + carousel, then imports app."""
2
+ import sys, os, re as _re
3
 
 
4
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
5
+ from shorts_carousel import scrape_24h_news_shorts, render_shorts_carousel, SHORTS_CSS, _extract_24h_video_url
6
 
 
7
  import app
8
 
9
+ # ══ Extra CSS ══
10
+ SHORTS_TIKTOK_CSS = """
11
+ /* Shorts TikTok Feed (9:16 fullscreen) */
12
+ .shorts-tiktok-container{width:100%;background:#000;position:relative;height:calc(100vh - 60px);max-height:900px;min-height:500px}
13
+ .shorts-tiktok-feed{height:100%;overflow-y:scroll;scroll-snap-type:y mandatory;-webkit-overflow-scrolling:touch;scrollbar-width:none}
14
+ .shorts-tiktok-feed::-webkit-scrollbar{display:none}
15
+ .shorts-slide{height:calc(100vh - 60px);max-height:900px;min-height:500px;scroll-snap-align:start;scroll-snap-stop:always;position:relative;display:flex;align-items:center;justify-content:center;background:#000}
16
+ .shorts-slide video{width:100%;height:100%;object-fit:cover;display:block}
17
+ .shorts-slide .tiktok-bottom{position:absolute;bottom:0;left:0;right:0;padding:16px 14px 24px;background:linear-gradient(transparent,rgba(0,0,0,.85));z-index:3}
18
+ .shorts-slide .tiktok-title{color:#fff;font-size:14px;font-weight:600;margin:4px 0 8px;line-height:1.4;text-shadow:0 1px 4px rgba(0,0,0,.8);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
19
+ .shorts-slide .tiktok-counter{position:absolute;top:12px;left:12px;background:rgba(0,0,0,.5);color:#fff;font-size:11px;padding:3px 10px;border-radius:12px;z-index:4}
20
+ .shorts-slide .tiktok-unmute-hint{position:absolute;top:12px;right:12px;background:rgba(0,0,0,.6);color:#fff;font-size:12px;padding:6px 12px;border-radius:18px;cursor:pointer;z-index:4}
21
+ .shorts-slide .shorts-seek{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);display:flex;gap:40px;z-index:6;opacity:0;transition:opacity .3s;pointer-events:none}
22
+ .shorts-slide.show-controls .shorts-seek{opacity:1;pointer-events:auto}
23
+ .shorts-seek button{background:rgba(0,0,0,.5);color:#fff;border:none;padding:8px 14px;border-radius:20px;font-size:12px;cursor:pointer;font-weight:600}
24
+ .shorts-slide .shorts-pause{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:70px;height:70px;background:rgba(0,0,0,.5);border-radius:50%;color:#fff;font-size:28px;z-index:5;pointer-events:none;display:none;line-height:70px;text-align:center}
25
+ .shorts-slide.paused .shorts-pause{display:block}
26
+ .shorts-back-btn{position:absolute;top:12px;left:50%;transform:translateX(-50%);background:rgba(255,255,255,.15);color:#fff;border:none;padding:6px 16px;border-radius:18px;font-size:12px;cursor:pointer;z-index:10;backdrop-filter:blur(4px)}
27
  """
28
 
 
29
  if "vslide-shorts-item" not in app.CSS:
30
  app.CSS += SHORTS_CSS
31
+ if "shorts-tiktok-container" not in app.CSS:
32
+ app.CSS += SHORTS_TIKTOK_CSS
33
 
34
+ # ══ Patch render_homepage_html ══
35
  _orig_render_homepage = app.render_homepage_html
36
  def _patched_render_homepage(articles, *args, **kwargs):
37
  html = _orig_render_homepage(articles, *args, **kwargs)
 
51
  return html
52
  app.render_homepage_html = _patched_render_homepage
53
 
54
+ # ══ Patch read_article: when 24h article render as shorts TikTok feed ══
55
+ _orig_read_article = app.read_article
56
+ def _patched_read_article(url):
57
+ if not url or url == "#" or len(url) < 10:
58
+ return "<p>Không tìm thấy bài viết.</p>"
59
+ # Check if this is a 24h article opened from shorts - render TikTok feed
60
+ if "24h.com.vn" in url:
61
+ return _render_shorts_tiktok_feed(url)
62
+ return _orig_read_article(url)
63
+
64
+ def _render_shorts_tiktok_feed(current_url):
65
+ """Render a TikTok-style fullscreen feed of shorts videos.
66
+ Shows the clicked video first, then others from the shorts list."""
67
+ from concurrent.futures import ThreadPoolExecutor, as_completed
68
+
69
+ # Get all shorts
70
+ try:
71
+ all_shorts = scrape_24h_news_shorts()[:15]
72
+ except:
73
+ all_shorts = []
74
+
75
+ if not all_shorts:
76
+ return _orig_read_article(current_url)
77
+
78
+ # Fetch video URLs in parallel
79
+ def _fetch_video(art):
80
+ vid = _extract_24h_video_url(art["link"])
81
+ if vid:
82
+ return {"title": art["title"], "link": art["link"], "src": vid["src"],
83
+ "poster": vid["poster"], "vtype": vid["vtype"]}
84
+ return None
85
+
86
+ videos = []
87
+ with ThreadPoolExecutor(max_workers=6) as ex:
88
+ futures = {ex.submit(_fetch_video, a): a for a in all_shorts}
89
+ for f in as_completed(futures):
90
+ try:
91
+ r = f.result()
92
+ if r:
93
+ videos.append(r)
94
+ except:
95
+ pass
96
+
97
+ if not videos:
98
+ return _orig_read_article(current_url)
99
+
100
+ # Reorder: put current video first
101
+ current_aid = app.make_id(current_url)
102
+ ordered = []
103
+ rest = []
104
+ for v in videos:
105
+ if app.make_id(v["link"]) == current_aid:
106
+ ordered.insert(0, v)
107
+ else:
108
+ rest.append(v)
109
+ ordered.extend(rest)
110
+
111
+ # Build TikTok feed HTML
112
+ slides = []
113
+ for vi, v in enumerate(ordered):
114
+ poster = app.safe_url(v.get("poster", ""))
115
+ poster_attr = f' poster="{poster}"' if poster else ""
116
+ vsrc = v["src"]
117
+ vtype = v.get("vtype", "hls")
118
+ aid = app.make_id(v["link"])
119
+ sl = app.slug(v["title"])
120
+ share_js = f"event.stopPropagation();window.bdpShareHash('{app.esc(v['title'])}','{sl}','{aid}')"
121
+
122
+ if vtype == "hls":
123
+ video_tag = f'<video class="shorts-video" playsinline preload="metadata"{poster_attr} data-hls-src="{vsrc}" muted loop></video>'
124
+ else:
125
+ video_tag = f'<video class="shorts-video" playsinline preload="metadata"{poster_attr} muted loop><source src="{app.safe_url(vsrc)}" type="video/mp4"></video>'
126
+
127
+ slides.append(f'''<div class="shorts-slide" data-index="{vi}">
128
+ {video_tag}
129
+ <div class="shorts-pause">\u25b6</div>
130
+ <div class="shorts-seek">
131
+ <button onclick="event.stopPropagation();var v=this.closest('.shorts-slide').querySelector('video');v.currentTime=Math.max(0,v.currentTime-10)">\u23ea 10s</button>
132
+ <button onclick="event.stopPropagation();var v=this.closest('.shorts-slide').querySelector('video');v.currentTime=Math.min(v.duration||9999,v.currentTime+10)">10s \u23e9</button>
133
+ </div>
134
+ <div class="tiktok-bottom">
135
+ <p class="tiktok-title">{v["title"]}</p>
136
+ <div class="tiktok-actions">
137
+ <button class="tiktok-action-btn" onclick="{share_js}">\U0001f4e4 Chia s\u1ebb</button>
138
+ </div>
139
+ </div>
140
+ <div class="tiktok-unmute-hint" onclick="var f=this.closest('.shorts-tiktok-feed');var vd=this.closest('.shorts-slide').querySelector('video');vd.muted=!vd.muted;var m=vd.muted;f.querySelectorAll('video').forEach(function(x){{x.muted=m}});f.querySelectorAll('.tiktok-unmute-hint').forEach(function(h){{h.textContent=m?'\U0001f507 B\u1eadt ti\u1ebfng':'\U0001f50a \u0110ang ph\u00e1t'}});">\U0001f507 B\u1eadt ti\u1ebfng</div>
141
+ <span class="tiktok-counter">{vi+1}/{len(ordered)}</span>
142
+ </div>''')
143
+
144
+ back_btn = '<button class="shorts-back-btn" onclick="document.querySelector(\'[id=\\\'btn-read-article\\\'] button,button:has(+ [id=\\\'btn-read-article\\\'])\')?.click();var bb=document.querySelectorAll(\'button\');bb.forEach(function(b){if(b.textContent.indexOf(\'Quay\')>-1)b.click()});">\u2190 Quay l\u1ea1i</button>'
145
+
146
+ return f'''<div class="shorts-tiktok-container" id="shorts-tiktok-feed">
147
+ {back_btn}
148
+ <div class="shorts-tiktok-feed">{''.join(slides)}</div>
149
+ </div>'''
150
+
151
+ app.read_article = _patched_read_article
152
+
153
+ # ══ Add JS for shorts TikTok feed initialization ══
154
+ _orig_js = app.JS_FUNC
155
+ # Inject shorts feed init into the JS
156
+ _shorts_js_patch = """
157
+ /* ══ Shorts TikTok Feed ══ */
158
+ function initShortsFeed(container){
159
+ if(container._sInit) return;
160
+ container._sInit=true;
161
+ var feed=container.querySelector('.shorts-tiktok-feed');
162
+ if(!feed) return;
163
+ var slides=feed.querySelectorAll('.shorts-slide');
164
+ if(!slides.length) return;
165
+
166
+ slides.forEach(function(sl){
167
+ var v=sl.querySelector('video[data-hls-src]');
168
+ if(v) initHlsVideo(v);
169
+ var v2=sl.querySelector('video:not([data-hls-src])');
170
+ if(v2&&!v2._initDone){v2._initDone=true;v2.load();}
171
+ });
172
+
173
+ var currentIdx=-1;
174
+ function tryPlay(v){var p=v.play();if(p&&p.catch)p.catch(function(){setTimeout(function(){v.play().catch(function(){});},500);});}
175
+
176
+ function activateSlide(idx){
177
+ if(idx===currentIdx) return;
178
+ slides.forEach(function(sl,i){
179
+ var v=sl.querySelector('video');
180
+ if(!v) return;
181
+ if(i===idx){v.currentTime=0;tryPlay(v);sl.classList.remove('paused');}
182
+ else{v.pause();sl.classList.remove('paused');}
183
+ });
184
+ currentIdx=idx;
185
+ }
186
+
187
+ var scrollT=null;
188
+ feed.addEventListener('scroll',function(){
189
+ if(scrollT)clearTimeout(scrollT);
190
+ scrollT=setTimeout(function(){
191
+ var rect=feed.getBoundingClientRect();
192
+ var center=rect.top+rect.height/2;
193
+ var best=-1,bestD=99999;
194
+ slides.forEach(function(sl,i){
195
+ var r=sl.getBoundingClientRect();
196
+ var d=Math.abs(r.top+r.height/2-center);
197
+ if(d<bestD){bestD=d;best=i;}
198
+ });
199
+ if(best>=0)activateSlide(best);
200
+ },150);
201
+ });
202
+
203
+ setTimeout(function(){activateSlide(0);},800);
204
+
205
+ slides.forEach(function(sl){
206
+ var v=sl.querySelector('video');
207
+ if(v){
208
+ var hideT=null;
209
+ v.addEventListener('click',function(e){
210
+ e.preventDefault();
211
+ if(sl.classList.contains('show-controls')){
212
+ if(v.paused){tryPlay(v);sl.classList.remove('paused');}
213
+ else{v.pause();sl.classList.add('paused');}
214
+ sl.classList.remove('show-controls');
215
+ } else {
216
+ sl.classList.add('show-controls');
217
+ if(hideT)clearTimeout(hideT);
218
+ hideT=setTimeout(function(){sl.classList.remove('show-controls');},3000);
219
+ }
220
+ });
221
+ }
222
+ });
223
+ }
224
+ """
225
+
226
+ # Inject before the MutationObserver section
227
+ _orig_js = _orig_js.replace(
228
+ "new MutationObserver(function(muts)",
229
+ _shorts_js_patch + "\nnew MutationObserver(function(muts)"
230
+ )
231
+
232
+ # Add shorts feed detection to MutationObserver
233
+ _orig_js = _orig_js.replace(
234
+ "n.querySelectorAll('.tiktok-fullscreen-container').forEach(initTikTokFullscreen);",
235
+ "n.querySelectorAll('.tiktok-fullscreen-container').forEach(initTikTokFullscreen);\n n.querySelectorAll('.shorts-tiktok-container').forEach(initShortsFeed);\n if(n.classList && n.classList.contains('shorts-tiktok-container')) initShortsFeed(n);"
236
+ )
237
+
238
+ # Add to setInterval too
239
+ _orig_js = _orig_js.replace(
240
+ "document.querySelectorAll('.tiktok-fullscreen-container').forEach(initTikTokFullscreen);",
241
+ "document.querySelectorAll('.tiktok-fullscreen-container').forEach(initTikTokFullscreen);\n document.querySelectorAll('.shorts-tiktok-container').forEach(initShortsFeed);"
242
+ )
243
+
244
+ app.JS_FUNC = _orig_js
245
 
246
+ # Re-create demo with patched CSS and JS
247
  app.demo.css = app.CSS
248
 
249
  # Export demo for Gradio to find