Spaces:
Running
Running
Upload app_patch_unified.py with huggingface_hub
Browse files- app_patch_unified.py +273 -0
app_patch_unified.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
VNEWS Unified Patch v2
|
| 3 |
+
======================
|
| 4 |
+
Single file replacing app_entry.py + patch_extra.py functionality.
|
| 5 |
+
No conflicts, no duplicate slides, no DOM destruction.
|
| 6 |
+
|
| 7 |
+
Features:
|
| 8 |
+
1. Tường AI persistent (fix FINAL6E destroying DOM)
|
| 9 |
+
2. Source details with image + description + "Xem trên VNEWS"
|
| 10 |
+
3. Highlight = TikTok fullheight 1:1 crop center with interaction buttons
|
| 11 |
+
4. Rewrite auto-title, no "xem trên VNEWS" junk
|
| 12 |
+
5. Topic post uses source og:image instead of AI image
|
| 13 |
+
6. Fast homepage load (non-blocking)
|
| 14 |
+
"""
|
| 15 |
+
from ai_runtime_patch_fast import *
|
| 16 |
+
from ai_runtime_patch_fast import app, f5, f6, rt, PATCH_INJECT, _scrape, _domain, clean, _bg, _bg_home, _bg_shorts
|
| 17 |
+
from fastapi.responses import HTMLResponse, JSONResponse
|
| 18 |
+
from fastapi import Request, Query
|
| 19 |
+
import asyncio, re, threading, time
|
| 20 |
+
|
| 21 |
+
DEFAULT_IMG = "https://s1.vnecdn.net/vnexpress/restruct/i/v9505/logo_default.jpg"
|
| 22 |
+
|
| 23 |
+
# ============================================================
|
| 24 |
+
# REMOVE ALL CONFLICTING ROUTES — we redefine them cleanly
|
| 25 |
+
# ============================================================
|
| 26 |
+
_OVERRIDE_PATHS = {'/api/homepage','/api/shorts','/api/topic_post','/api/topic/rewrite','/api/rewrite_share','/api/url_wall','/'}
|
| 27 |
+
app.router.routes = [r for r in app.router.routes if not (getattr(r,'path',None) in _OVERRIDE_PATHS and any(m in getattr(r,'methods',set()) for m in ('GET','POST')))]
|
| 28 |
+
|
| 29 |
+
# ============================================================
|
| 30 |
+
# FAST HOMEPAGE + SHORTS (non-blocking)
|
| 31 |
+
# ============================================================
|
| 32 |
+
@app.get('/api/homepage')
|
| 33 |
+
def _homepage():
|
| 34 |
+
if _bg_home['d']:
|
| 35 |
+
if time.time()-_bg_home['t']>300:threading.Thread(target=_bg,daemon=True).start()
|
| 36 |
+
return JSONResponse(_bg_home['d'])
|
| 37 |
+
threading.Thread(target=_bg,daemon=True).start()
|
| 38 |
+
return JSONResponse([])
|
| 39 |
+
|
| 40 |
+
@app.get('/api/shorts')
|
| 41 |
+
def _shorts(refresh:int=Query(default=0)):
|
| 42 |
+
if _bg_shorts['d']:
|
| 43 |
+
if time.time()-_bg_shorts['t']>600:threading.Thread(target=_bg,daemon=True).start()
|
| 44 |
+
return JSONResponse(_bg_shorts['d'])
|
| 45 |
+
threading.Thread(target=_bg,daemon=True).start()
|
| 46 |
+
return JSONResponse([])
|
| 47 |
+
|
| 48 |
+
# ============================================================
|
| 49 |
+
# HELPERS
|
| 50 |
+
# ============================================================
|
| 51 |
+
def _extract_title(text):
|
| 52 |
+
if not text:return 'Bài viết AI'
|
| 53 |
+
lines=[l.strip() for l in text.strip().split('\n') if l.strip()]
|
| 54 |
+
if lines:
|
| 55 |
+
first=re.sub(r'^[#*\-•\d\.\)\s]+','',lines[0]).strip()
|
| 56 |
+
if 10<=len(first)<=120:return first
|
| 57 |
+
return lines[0][:100] if lines else 'Bài viết AI'
|
| 58 |
+
|
| 59 |
+
def _clean_text(text):
|
| 60 |
+
if not text:return text
|
| 61 |
+
for junk in ['xem trên VNEWS','Xem trên VNEWS','📖 Xem trên VNEWS','đọc trên VNEWS','Đọc trên VNEWS','Mở nguồn gốc','mở nguồn gốc','📖 Đọc trên']:
|
| 62 |
+
text=text.replace(junk,'')
|
| 63 |
+
return re.sub(r'\n{3,}','\n\n',text).strip()
|
| 64 |
+
|
| 65 |
+
def _source_image(sources, details):
|
| 66 |
+
for s in (details or [])+(sources or []):
|
| 67 |
+
url=s.get('url','')
|
| 68 |
+
if not url:continue
|
| 69 |
+
try:_,_,img=_scrape(url,500)
|
| 70 |
+
except:img=''
|
| 71 |
+
if img and 'pollinations' not in img and len(img)>20:return img
|
| 72 |
+
return ''
|
| 73 |
+
|
| 74 |
+
def _ensure_img(img):
|
| 75 |
+
return img if (img and len(img)>20 and img.startswith('http')) else DEFAULT_IMG
|
| 76 |
+
|
| 77 |
+
# ============================================================
|
| 78 |
+
# TOPIC POST (source image instead of AI image)
|
| 79 |
+
# ============================================================
|
| 80 |
+
@app.post('/api/topic_post')
|
| 81 |
+
async def _topic(request:Request):
|
| 82 |
+
b=await request.json();topic=clean(b.get('topic',''))
|
| 83 |
+
if not topic:return JSONResponse({'error':'missing topic'},status_code=400)
|
| 84 |
+
research=f6._fast_context(topic) if hasattr(f6,'_fast_context') else f6._web_research_context(topic)
|
| 85 |
+
ctx=research.get('context','');src=research.get('sources',[])
|
| 86 |
+
det=f6._extract_source_details_from_context(ctx,src) if hasattr(f6,'_extract_source_details_from_context') else []
|
| 87 |
+
if not ctx or not src:return JSONResponse({'error':'Không tìm được nội dung.'},status_code=422)
|
| 88 |
+
img=_ensure_img(_source_image(src,det) or f6._topic_image(topic))
|
| 89 |
+
sb='\n\n'.join([f"[{i+1}] {d.get('title','')} ({d.get('via','')})\n{d.get('content','')[:1400]}" for i,d in enumerate(det)]) if det else ctx[:18000]
|
| 90 |
+
text=None
|
| 91 |
+
try:text=await asyncio.wait_for(f5.base.qwen_generate(f'Viết bài tiếng Việt VỀ: "{topic}"\nNGUỒN:\n{sb[:18000]}\nCHỈ viết về "{topic}". 5-8 đoạn. Cuối có nguồn.',image_url=img,max_tokens=1700),timeout=35)
|
| 92 |
+
except:pass
|
| 93 |
+
if not text or len(text)<300:
|
| 94 |
+
text=f"{topic}: tổng hợp\n\n"+'\n'.join([f"• {d['title']}: {d.get('content','')[:300]}" for d in (det or [])[:6]])+"\n\nNguồn: "+', '.join(sorted({d.get('via','') for d in (det or []) if d.get('via')}))
|
| 95 |
+
text=_clean_text(text)
|
| 96 |
+
post=f5.base.make_post(topic,text,img,'','topic_focused',sources=[s for s in src if s.get('url')])
|
| 97 |
+
post['images']=[img];post['source_details']=det
|
| 98 |
+
ps=f5.base._load_ai_wall();ps.insert(0,post);f5.base._save_ai_wall(ps)
|
| 99 |
+
return JSONResponse({'post':post})
|
| 100 |
+
|
| 101 |
+
# ============================================================
|
| 102 |
+
# REWRITE (auto-title, clean text)
|
| 103 |
+
# ============================================================
|
| 104 |
+
@app.post('/api/rewrite_share')
|
| 105 |
+
@app.post('/api/url_wall')
|
| 106 |
+
async def _rewrite(request:Request):
|
| 107 |
+
b=await request.json();url=clean(b.get('url',''));ctx=clean(b.get('context',''))
|
| 108 |
+
if not url.startswith('http'):return JSONResponse({'error':'URL không hợp lệ'},status_code=400)
|
| 109 |
+
title,raw,img=_scrape(url,14000)
|
| 110 |
+
if len(raw)<50:raw=ctx[:14000]
|
| 111 |
+
if len(raw)<50:return JSONResponse({'error':'Không đọc được bài'},status_code=422)
|
| 112 |
+
img=_ensure_img(img)
|
| 113 |
+
prompt=f"""Tóm tắt bài viết thành bản tin ngắn. Dòng đầu tiên là tiêu đề mới hấp dẫn (tự đặt, không copy gốc).
|
| 114 |
+
|
| 115 |
+
Tiêu đề gốc: {title}
|
| 116 |
+
Nội dung:
|
| 117 |
+
{raw[:14000]}
|
| 118 |
+
|
| 119 |
+
Yêu cầu:
|
| 120 |
+
- Dòng 1: Tiêu đề MỚI ngắn gọn hấp dẫn.
|
| 121 |
+
- Tiếp: 4-6 ý chính.
|
| 122 |
+
- Cuối: nguồn.
|
| 123 |
+
- KHÔNG viết bất kỳ cụm điều hướng nào."""
|
| 124 |
+
text=None
|
| 125 |
+
try:text=await asyncio.wait_for(f5.base.qwen_generate(prompt,image_url=img,max_tokens=1000),timeout=30)
|
| 126 |
+
except:pass
|
| 127 |
+
if not text or len(text)<80:text=f"{title}\n\n{raw[:1200]}\n\nNguồn: {_domain(url)}"
|
| 128 |
+
text=_clean_text(text)
|
| 129 |
+
ai_title=_extract_title(text)
|
| 130 |
+
lines=text.strip().split('\n')
|
| 131 |
+
body='\n'.join(lines[1:]).strip() if lines and lines[0].strip()==ai_title else text
|
| 132 |
+
post=f5.base.make_post(ai_title,_clean_text(body),img,url,'rewrite',sources=[{'title':title,'url':url,'via':_domain(url)}])
|
| 133 |
+
ps=f5.base._load_ai_wall();ps.insert(0,post);f5.base._save_ai_wall(ps)
|
| 134 |
+
return JSONResponse({'post':post})
|
| 135 |
+
|
| 136 |
+
@app.post('/api/topic/rewrite')
|
| 137 |
+
async def _topic_rewrite(request:Request):
|
| 138 |
+
b=await request.json();pid=str(b.get('post_id','')).strip()
|
| 139 |
+
if not pid:return JSONResponse({'error':'missing post_id'},status_code=400)
|
| 140 |
+
ps=f5.base._load_ai_wall();p=next((x for x in ps if str(x.get('id'))==pid),None)
|
| 141 |
+
if not p:return JSONResponse({'error':'Bài không tồn tại'},status_code=404)
|
| 142 |
+
urls=list(dict.fromkeys([s['url'] for s in (p.get('source_details') or []) if s.get('url')]+[s['url'] for s in (p.get('sources') or []) if s.get('url')]))[:5]
|
| 143 |
+
parts=[];best_img=''
|
| 144 |
+
for u in urls:
|
| 145 |
+
t,r,uimg=_scrape(u,6000)
|
| 146 |
+
if r and len(r)>150:parts.append(f"[{_domain(u)}] {t}\n{r}")
|
| 147 |
+
if not best_img and uimg and len(uimg)>20:best_img=uimg
|
| 148 |
+
ac='\n---\n'.join(parts) if parts else (p.get('text') or '')
|
| 149 |
+
img=_ensure_img(best_img or p.get('img',''))
|
| 150 |
+
prompt=f"""Viết lại thành bản tóm tắt mới. Dòng đầu là tiêu đề mới hấp dẫn.
|
| 151 |
+
|
| 152 |
+
Chủ đề: {p.get('title','')}
|
| 153 |
+
Nguồn:
|
| 154 |
+
{ac[:16000]}
|
| 155 |
+
|
| 156 |
+
Yêu cầu: Dòng 1 = tiêu đề mới. Tiếp: 4-6 ý. Cuối: nguồn. KHÔNG viết cụm điều hướng."""
|
| 157 |
+
text=None
|
| 158 |
+
try:text=await asyncio.wait_for(f5.base.qwen_generate(prompt,image_url=img,max_tokens=1200),timeout=35)
|
| 159 |
+
except:pass
|
| 160 |
+
if not text or len(text)<100:text=f"Tóm tắt: {p.get('title','')}\n\n{ac[:1500]}\n\nNguồn: VNEWS AI"
|
| 161 |
+
text=_clean_text(text)
|
| 162 |
+
ai_title=_extract_title(text)
|
| 163 |
+
lines=text.strip().split('\n')
|
| 164 |
+
body='\n'.join(lines[1:]).strip() if lines and lines[0].strip()==ai_title else text
|
| 165 |
+
np=f5.base.make_post(ai_title,_clean_text(body),img,'','rewrite_topic',sources=p.get('sources',[]));np['images']=[img]
|
| 166 |
+
all_p=f5.base._load_ai_wall();all_p.insert(0,np);f5.base._save_ai_wall(all_p)
|
| 167 |
+
return JSONResponse({'post':np})
|
| 168 |
+
|
| 169 |
+
# ============================================================
|
| 170 |
+
# UNIFIED INJECT: everything in one clean block
|
| 171 |
+
# ============================================================
|
| 172 |
+
UNIFIED_INJECT = r'''
|
| 173 |
+
<script>
|
| 174 |
+
// === PRE-KILL: prevent old code from destroying Tường AI and Short AI slides ===
|
| 175 |
+
Object.defineProperty(window,'renderTopicWallE',{get:function(){return function(){}},set:function(){},configurable:true});
|
| 176 |
+
Object.defineProperty(window,'renderAIShortHome',{get:function(){return function(){}},set:function(){},configurable:true});
|
| 177 |
+
Object.defineProperty(window,'renderAIShorts7',{get:function(){return function(){}},set:function(){},configurable:true});
|
| 178 |
+
</script>
|
| 179 |
+
<style>
|
| 180 |
+
/* Tiktok right panel for shorts/highlights */
|
| 181 |
+
.tiktok-slide{position:relative!important}
|
| 182 |
+
.tiktok-right{position:absolute!important;right:8px!important;bottom:100px!important;display:flex!important;flex-direction:column!important;align-items:center!important;gap:14px!important;z-index:5!important}
|
| 183 |
+
.tiktok-right-btn{display:flex!important;flex-direction:column!important;align-items:center!important;gap:2px!important;background:none!important;border:0!important;color:#fff!important;cursor:pointer!important}
|
| 184 |
+
.tiktok-right-btn .icon{width:42px!important;height:42px!important;border-radius:50%!important;background:rgba(255,255,255,.12)!important;display:flex!important;align-items:center!important;justify-content:center!important;font-size:20px!important}
|
| 185 |
+
.tiktok-right-btn .count{font-size:10px!important;color:#ddd!important}
|
| 186 |
+
/* Highlight: TikTok feed with 1:1 crop center */
|
| 187 |
+
.tiktok-slide video{object-fit:cover!important}
|
| 188 |
+
/* Hide duplicate slides/walls from old layers */
|
| 189 |
+
#ai-short-home,.ai-short-home,.ai-short-card-final,[id*="ai-shorts-patched"]{display:none!important}
|
| 190 |
+
/* Progress toast */
|
| 191 |
+
#short-progress-toast{position:fixed;bottom:70px;left:50%;transform:translateX(-50%);background:#2d8659;color:#fff;padding:10px 20px;border-radius:20px;font-size:12px;z-index:99998;box-shadow:0 4px 12px rgba(0,0,0,.4);display:none}
|
| 192 |
+
/* Source details */
|
| 193 |
+
.source-detail-box{margin-top:14px;background:#151515;border:1px solid #2b2b2b;border-radius:10px;padding:10px}
|
| 194 |
+
.source-detail-item{background:#202020;border-radius:8px;padding:9px;margin:7px 0;cursor:pointer}
|
| 195 |
+
.source-detail-item:active{opacity:.8}
|
| 196 |
+
.source-detail-title{font-size:12px;font-weight:700;color:#eee}
|
| 197 |
+
.source-detail-content{font-size:11px;color:#bbb;line-height:1.4;max-height:80px;overflow:hidden;margin-top:4px}
|
| 198 |
+
.source-detail-item img{width:100%;aspect-ratio:16/9;object-fit:cover;border-radius:6px;margin-bottom:6px;background:#222}
|
| 199 |
+
.source-vnews-btn{display:inline-block;margin-top:6px;background:#2d8659;color:#fff;padding:4px 10px;border-radius:10px;font-size:10px;font-weight:700}
|
| 200 |
+
/* Livescore */
|
| 201 |
+
.ls-content{max-height:480px;overflow-y:auto;padding:0 6px 8px;font-size:12px;color:#ddd}.ls-content ul{list-style:none;padding:0;margin:0}.ls-content .title-content{display:flex;gap:6px;align-items:center;background:#222;border-radius:4px;margin:4px 0;padding:5px 8px}.ls-content .title-content img{width:18px;height:18px}.ls-content .title-content strong{font-size:11px;color:#ccc}.ls-content .match-detail{padding:6px;border-bottom:1px solid #262626;cursor:pointer}.ls-content .match-detail:hover{background:#1a2a1f}.ls-content .match{display:flex;flex-wrap:wrap;align-items:center;gap:4px}.ls-content .datetime{width:100%;font-size:9px;color:#888}.ls-content .teams{display:flex;width:100%;align-items:center;gap:4px}.ls-content .team{flex:1;display:flex;align-items:center;gap:4px;min-width:0}.ls-content .team .name{font-size:11px;color:#ddd;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ls-content .team .logo img{width:18px;height:18px}.ls-content .home-team{justify-content:flex-end;text-align:right}.ls-content .status{flex:0 0 54px;text-align:center}.ls-content .status a{color:#fff;text-decoration:none;font-weight:800;font-size:12px}.ls-content .status .label{font-size:8px;color:#888;display:block}.ls-content .status .label.live{color:#e74c3c}.ls-content .info,.ls-content .btns{display:none}.ls-content table,.mo-body table{width:100%;border-collapse:collapse;font-size:11px;color:#ccc}.ls-content table th,.mo-body table th{background:#222;color:#999;padding:5px 4px;font-size:10px;border-bottom:1px solid #333}.ls-content table td,.mo-body table td{padding:4px 3px;border-bottom:1px solid #1a1a1a}.ls-content table .team-name,.mo-body table .team-name{display:flex;align-items:center;gap:4px}.ls-content table .team-name img,.mo-body table .team-name img{width:16px;height:16px}.ls-content table .pts{font-weight:800;color:#f0c040}.mo-body{padding:8px;font-size:12px;color:#ddd}.mo-body ul{list-style:none;padding:0}.mo-body li{padding:5px 0;border-bottom:1px solid #222}
|
| 202 |
+
</style>
|
| 203 |
+
<div id="short-progress-toast"></div>
|
| 204 |
+
<script>
|
| 205 |
+
(function(){
|
| 206 |
+
function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));}
|
| 207 |
+
|
| 208 |
+
// === Progress toast ===
|
| 209 |
+
window.showShortProgress=function(msg){var t=document.getElementById('short-progress-toast');if(t){t.textContent=msg;t.style.display='block';}};
|
| 210 |
+
window.hideShortProgress=function(){var t=document.getElementById('short-progress-toast');if(t)t.style.display='none';};
|
| 211 |
+
window.makeShortFromPost=async function(pid,btn){
|
| 212 |
+
showShortProgress('⏳ Đang tạo Short AI...');if(btn){btn.disabled=true;btn.textContent='Đang tạo...';}
|
| 213 |
+
try{var r=await fetch('/api/ai/short/'+pid,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({voice:'nu',emotion:'neutral',speed:1.2})});var j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');showShortProgress('✅ Đã tạo!');setTimeout(hideShortProgress,3000);if(typeof renderShortAISlide==='function')renderShortAISlide();}catch(e){showShortProgress('❌ '+e.message);setTimeout(hideShortProgress,4000);}finally{if(btn){btn.disabled=false;btn.textContent='🎬 Tạo Short AI';}}
|
| 214 |
+
};
|
| 215 |
+
|
| 216 |
+
// === Remove duplicate slides ===
|
| 217 |
+
setInterval(function(){document.querySelectorAll('#ai-short-home,.ai-short-home,[id*="ai-shorts-patched"]').forEach(function(el){if(el.id!=='short-ai-final-slide')el.remove();});},3000);
|
| 218 |
+
|
| 219 |
+
// === Override openLeaguePlayer: TikTok vertical feed, 1:1 crop center ===
|
| 220 |
+
window.openLeaguePlayer=async function(league,idx){
|
| 221 |
+
showView('view-tiktok');document.querySelectorAll('.cat').forEach(x=>x.classList.remove('active'));
|
| 222 |
+
var el=document.getElementById('view-tiktok');el.innerHTML='<div class="loading">Đang tải...</div>';
|
| 223 |
+
var cfg=(window.HL_CONFIG||{})[league]||{name:league,emoji:'🎬'};
|
| 224 |
+
var articles=(window._hlLeagueData||{})[league]||[];
|
| 225 |
+
if(!articles.length){el.innerHTML='<div class="loading">Không có video</div>';return;}
|
| 226 |
+
var vids=[];
|
| 227 |
+
var results=await Promise.all(articles.map(async function(a,i){try{var r=await fetch('/api/video_url?url='+encodeURIComponent(a.link));var v=await r.json();if(v&&v.src)return Object.assign({},a,v,{_idx:i});}catch(e){}return null;}));
|
| 228 |
+
results.forEach(function(r){if(r)vids.push(r);});
|
| 229 |
+
vids.sort(function(a,b){return a._idx-b._idx;});
|
| 230 |
+
if(!vids.length){el.innerHTML='<div class="loading">Không tìm thấy video</div>';return;}
|
| 231 |
+
var ti=vids.findIndex(function(v){return v._idx===idx;});if(ti<0)ti=0;
|
| 232 |
+
var ordered=ti>0?vids.slice(ti).concat(vids.slice(0,ti)):vids;
|
| 233 |
+
var h='<button class="back-btn" onclick="switchCat(\'home\')">← '+cfg.emoji+' '+cfg.name+'</button><div class="tiktok-container"><div class="tiktok-feed" id="tiktok-feed">';
|
| 234 |
+
ordered.forEach(function(v,i){
|
| 235 |
+
var isYT=v.type==='youtube';var isHLS=!isYT&&v.src&&v.src.indexOf('.m3u8')>-1;
|
| 236 |
+
var poster=v.poster?' poster="'+v.poster+'"':'';
|
| 237 |
+
var vtag=isYT?'<iframe data-yt-src="'+v.src+'" allowfullscreen allow="accelerometer;autoplay;clipboard-write;encrypted-media;gyroscope;picture-in-picture" style="width:100%;height:100%;border:none"></iframe>':isHLS?'<video playsinline preload="none"'+poster+' data-hls="'+v.src+'" loop controls style="width:100%;height:100%;object-fit:cover"></video>':'<video playsinline preload="none"'+poster+' loop controls style="width:100%;height:100%;object-fit:cover"><source src="'+v.src+'" type="video/mp4"></video>';
|
| 238 |
+
h+='<div class="tiktok-slide" id="tslide-'+i+'">'+vtag+'<div class="tiktok-bottom"><span class="badge badge-fpt">'+esc(cfg.name)+'</span><p class="tiktok-title">'+esc(v.title)+'</p></div><div class="tiktok-right"><button class="tiktok-right-btn" onclick="event.stopPropagation()"><div class="icon">👁</div></button><button class="tiktok-right-btn" onclick="event.stopPropagation()"><div class="icon">❤️</div></button><button class="tiktok-right-btn" onclick="event.stopPropagation();if(typeof doShareVideo===\'function\')doShareVideo(\''+esc(v.title)+'\',\''+esc(v.link||'')+'\',\''+esc(v.poster||v.img||'')+'\',\'highlights\')"><div class="icon">📤</div></button></div><span class="tiktok-counter">'+(i+1)+'/'+ordered.length+'</span></div>';
|
| 239 |
+
});
|
| 240 |
+
h+='</div></div>';el.innerHTML=h;
|
| 241 |
+
// Init feed
|
| 242 |
+
var feed=document.getElementById('tiktok-feed');if(!feed)return;
|
| 243 |
+
var slides=feed.querySelectorAll('.tiktok-slide');var cur=-1;
|
| 244 |
+
function act(i){if(i===cur)return;slides.forEach(function(sl,idx){var v=sl.querySelector('video');var fr=sl.querySelector('iframe');if(idx===i){if(v&&v.dataset.hls){if(!v._hls&&typeof Hls!=='undefined'&&Hls.isSupported()){var hls=new Hls();hls.loadSource(v.dataset.hls);hls.attachMedia(v);hls.on(Hls.Events.MANIFEST_PARSED,function(){v.play().catch(function(){});});v._hls=hls;}else if(v._hls)v.play().catch(function(){});}else if(v)v.play().catch(function(){});if(fr&&!fr.src&&fr.dataset.ytSrc)fr.src=fr.dataset.ytSrc;}else{if(v){v.pause();if(v._hls){v._hls.destroy();v._hls=null;}}if(fr&&fr.src)fr.src='';}});cur=i;}
|
| 245 |
+
var sT;feed.addEventListener('scroll',function(){clearTimeout(sT);sT=setTimeout(function(){var rect=feed.getBoundingClientRect(),ctr=rect.top+rect.height/2,best=-1,bestD=1e9;slides.forEach(function(sl,i){var d=Math.abs(sl.getBoundingClientRect().top+sl.getBoundingClientRect().height/2-ctr);if(d<bestD){bestD=d;best=i;}});if(best>=0)act(best);},150);});
|
| 246 |
+
setTimeout(function(){act(0);},400);
|
| 247 |
+
slides.forEach(function(sl){var v=sl.querySelector('video');if(v)v.addEventListener('click',function(e){e.preventDefault();v.paused?v.play().catch(function(){}):v.pause();});});
|
| 248 |
+
};
|
| 249 |
+
|
| 250 |
+
// === Block slow YouTube refresh on first load ===
|
| 251 |
+
var _origFetch=window.fetch,_allowRefresh=false;
|
| 252 |
+
window.fetch=function(url,opts){try{if(String(url).indexOf('/api/shorts?refresh=1')>-1&&!_allowRefresh)url='/api/shorts';}catch(e){}return _origFetch.call(this,url,opts);};
|
| 253 |
+
setTimeout(function(){_allowRefresh=true;},8000);
|
| 254 |
+
})();
|
| 255 |
+
</script>
|
| 256 |
+
'''
|
| 257 |
+
|
| 258 |
+
# ============================================================
|
| 259 |
+
# ROOT ROUTE: inject order matters
|
| 260 |
+
# ============================================================
|
| 261 |
+
@app.get('/')
|
| 262 |
+
async def _index():
|
| 263 |
+
html = f5.f4.f3.f2.f1._load_index_html()
|
| 264 |
+
# Inject order: PRE_KILL (in UNIFIED) → old injects → PATCH_INJECT → UNIFIED
|
| 265 |
+
body = ''
|
| 266 |
+
body += getattr(rt.old,'PATCH_INJECT','')
|
| 267 |
+
body += f5.f4.f3.f2.f1.FINAL_INJECT + f5.f4.f3.FINAL3_INJECT + f5.f4.FINAL4_INJECT + f5.FINAL5_INJECT
|
| 268 |
+
body += getattr(f6,'FINAL6_INJECT','')
|
| 269 |
+
body += getattr(f6,'FINAL6_FAST_HOME_INJECT','')
|
| 270 |
+
body += getattr(f6,'FINAL6E_INJECT','') # Keep it — our PRE_KILL in UNIFIED neutralizes its destructive parts
|
| 271 |
+
body += PATCH_INJECT
|
| 272 |
+
body += UNIFIED_INJECT # This goes LAST and contains PRE_KILL at the TOP (runs first in browser)
|
| 273 |
+
return HTMLResponse(html.replace('</body>', body + '\n</body>') if '</body>' in html else html + body)
|