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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, re, subprocess, json, time, hashlib
|
| 2 |
+
import ai_patch as old
|
| 3 |
+
from ai_patch import app
|
| 4 |
+
import ai_ext as base
|
| 5 |
+
from fastapi import Request
|
| 6 |
+
from fastapi.responses import JSONResponse, HTMLResponse, FileResponse
|
| 7 |
+
try:
|
| 8 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 9 |
+
except Exception:
|
| 10 |
+
Image = ImageDraw = ImageFont = None
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def clean(s):
|
| 14 |
+
import html as html_lib
|
| 15 |
+
return re.sub(r"\s+", " ", html_lib.unescape(s or "")).strip()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _domain(url):
|
| 19 |
+
try:
|
| 20 |
+
from urllib.parse import urlparse
|
| 21 |
+
return urlparse(url or '').netloc.replace('www.','')
|
| 22 |
+
except Exception:
|
| 23 |
+
return ''
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _strip_bullet_prefix(s):
|
| 27 |
+
return clean(re.sub(r'^[\s•\-\*·▪▫●○\d\.\)\(]+', '', s or ''))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def source_line(sources):
|
| 31 |
+
names=[]
|
| 32 |
+
for s in (sources or [])[:5]:
|
| 33 |
+
via=s.get('via') or _domain(s.get('url','')) or s.get('title','')
|
| 34 |
+
if via and via not in names:names.append(via)
|
| 35 |
+
return 'Nguồn tham khảo: '+', '.join(names[:5]) if names else 'Nguồn tham khảo: tổng hợp internet'
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _source_badge(post):
|
| 39 |
+
sources=post.get('sources') or []
|
| 40 |
+
for s in sources:
|
| 41 |
+
via=s.get('via') or _domain(s.get('url',''))
|
| 42 |
+
if via:return via
|
| 43 |
+
return _domain(post.get('url','')) or post.get('source') or 'VNEWS'
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _collect_all_images(data):
|
| 47 |
+
imgs=[]
|
| 48 |
+
def add(u):
|
| 49 |
+
u=(u or '').strip()
|
| 50 |
+
if not u or u.startswith('data:') or 'base64' in u:return
|
| 51 |
+
if u.startswith('//'):u='https:'+u
|
| 52 |
+
if u not in imgs:imgs.append(u)
|
| 53 |
+
add(data.get('image') or data.get('og_image') or data.get('img'))
|
| 54 |
+
for u in data.get('images') or []:add(u)
|
| 55 |
+
for b in data.get('body') or []:
|
| 56 |
+
if isinstance(b,dict) and b.get('type')=='img':add(b.get('src'))
|
| 57 |
+
return imgs[:20]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _scrape_url_with_images(url):
|
| 61 |
+
data=base.scrape_any_url(url)
|
| 62 |
+
try:
|
| 63 |
+
import requests
|
| 64 |
+
from bs4 import BeautifulSoup
|
| 65 |
+
r=requests.get(url,headers=base.HEADERS,timeout=18);r.encoding='utf-8'
|
| 66 |
+
soup=BeautifulSoup(r.text,'lxml')
|
| 67 |
+
extra=[]
|
| 68 |
+
for im in soup.find_all('img'):
|
| 69 |
+
src=im.get('data-src') or im.get('data-original') or im.get('data-lazy-src') or im.get('src') or ''
|
| 70 |
+
if src.startswith('//'):src='https:'+src
|
| 71 |
+
if src and 'base64' not in src and src not in extra:
|
| 72 |
+
low=src.lower()
|
| 73 |
+
if any(x in low for x in ['logo','icon','avatar','sprite']):
|
| 74 |
+
continue
|
| 75 |
+
extra.append(src)
|
| 76 |
+
if len(extra)>=20:break
|
| 77 |
+
data['images']=_collect_all_images(data)+[u for u in extra if u not in _collect_all_images(data)]
|
| 78 |
+
except Exception:
|
| 79 |
+
data['images']=_collect_all_images(data)
|
| 80 |
+
data['images']=_collect_all_images(data)
|
| 81 |
+
if data['images'] and not data.get('image'):
|
| 82 |
+
data['image']=data['images'][0]
|
| 83 |
+
return data
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def rich_context(topic, limit=5):
|
| 87 |
+
try: ctx,sources=base.web_context(topic, limit=limit)
|
| 88 |
+
except Exception: ctx,sources='',[]
|
| 89 |
+
rich=[];rs=[];seen=set()
|
| 90 |
+
for s in (sources or [])[:limit*2]:
|
| 91 |
+
url=s.get('url') or ''
|
| 92 |
+
if not url.startswith('http') or url in seen:continue
|
| 93 |
+
seen.add(url)
|
| 94 |
+
try:
|
| 95 |
+
data=base.scrape_any_url(url)
|
| 96 |
+
raw=(data.get('summary','')+'\n'+data.get('text','')).strip()
|
| 97 |
+
if len(raw)<180:continue
|
| 98 |
+
title=data.get('title') or s.get('title') or url
|
| 99 |
+
via=data.get('via') or s.get('via') or _domain(url)
|
| 100 |
+
rich.append(f"### {title} ({via})\n{raw[:2600]}")
|
| 101 |
+
rs.append({'title':title,'url':url,'excerpt':raw[:700],'via':via})
|
| 102 |
+
if len(rich)>=limit:break
|
| 103 |
+
except Exception:continue
|
| 104 |
+
if rich:return '\n\n'.join(rich),rs
|
| 105 |
+
return ctx or f'Chủ đề: {topic}', sources or []
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def postprocess(text):
|
| 109 |
+
if hasattr(old,'_postprocess_ai_text'):
|
| 110 |
+
out=old._postprocess_ai_text(text, max_units=7)
|
| 111 |
+
else:
|
| 112 |
+
out=clean(text)
|
| 113 |
+
return out
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
_PATCH={('/api/topic_post','POST'),('/api/url_wall','POST'),('/api/rewrite_share','POST'),('/api/ai/url','POST'),('/api/ai/short/{post_id}','POST'),('/api/ai/short-file/{file_id}','GET'),('/','GET')}
|
| 117 |
+
app.router.routes=[r for r in app.router.routes if not any(getattr(r,'path',None)==p and m in getattr(r,'methods',set()) for p,m in _PATCH)]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@app.post('/api/url_wall')
|
| 121 |
+
async def url_wall_only(request:Request):
|
| 122 |
+
body=await request.json();url=base._clean_text(body.get('url',''))
|
| 123 |
+
if not url.startswith('http'):return JSONResponse({'error':'missing url'},status_code=400)
|
| 124 |
+
try:data=_scrape_url_with_images(url)
|
| 125 |
+
except Exception as e:return JSONResponse({'error':'Không scrape được URL: '+str(e)[:180]},status_code=422)
|
| 126 |
+
raw=(data.get('summary','')+'\n'+data.get('text','')).strip()
|
| 127 |
+
if len(raw)<120:return JSONResponse({'error':'URL không có đủ nội dung để tóm tắt'},status_code=422)
|
| 128 |
+
prompt=f"""Tóm tắt bài viết nguồn dưới đây để đăng lên Tường AI VNEWS.
|
| 129 |
+
|
| 130 |
+
Yêu cầu b��t buộc:
|
| 131 |
+
- Chỉ tóm tắt nội dung chính, không viết lại toàn bộ bài.
|
| 132 |
+
- Ngắn gọn, cụ thể, dễ hiểu.
|
| 133 |
+
- Không lặp lại ý và không thêm chi tiết ngoài nguồn.
|
| 134 |
+
- Tối đa 5 ý chính hoặc 2 đoạn ngắn.
|
| 135 |
+
- Tránh dùng dấu đầu dòng nếu không thật cần thiết.
|
| 136 |
+
|
| 137 |
+
Tiêu đề gốc: {data.get('title','')}
|
| 138 |
+
Nguồn: {data.get('via','') or _domain(url)}
|
| 139 |
+
Nội dung gốc:
|
| 140 |
+
{raw[:16000]}"""
|
| 141 |
+
text=await base.qwen_generate(prompt,image_url=(data.get('image') or None),max_tokens=900)
|
| 142 |
+
if not text:text=old._fallback_summary_from_prompt(prompt,max_units=5) if hasattr(old,'_fallback_summary_from_prompt') else raw[:900]
|
| 143 |
+
text=postprocess(text)
|
| 144 |
+
src=[{'title':data.get('title'), 'url':url, 'excerpt':raw[:500], 'via':data.get('via') or _domain(url)}]
|
| 145 |
+
if 'Nguồn tham khảo:' not in text:text+='\n\n'+source_line(src)
|
| 146 |
+
images=_collect_all_images(data)
|
| 147 |
+
post=base.make_post(data.get('title') or 'Bài viết',text,images[0] if images else (data.get('image') or ''),url,'url',sources=src)
|
| 148 |
+
post['images']=images
|
| 149 |
+
posts=base._load_ai_wall();posts.insert(0,post);base._save_ai_wall(posts)
|
| 150 |
+
return JSONResponse({'post':post})
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@app.post('/api/rewrite_share')
|
| 154 |
+
async def rewrite_share_url_only(request:Request):
|
| 155 |
+
return await url_wall_only(request)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@app.post('/api/ai/url')
|
| 159 |
+
async def ai_url_compat(request:Request):
|
| 160 |
+
return await url_wall_only(request)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
@app.post('/api/topic_post')
|
| 164 |
+
async def topic_disabled(request:Request):
|
| 165 |
+
return JSONResponse({'error':'Đã tắt tạo bài theo chủ đề. Vui lòng dán URL bài viết để AI tóm tắt.'},status_code=410)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def split_segments(post,max_segments=8):
|
| 169 |
+
text=clean(post.get('text') or post.get('title') or '')
|
| 170 |
+
text=re.sub(r'Nguồn tham khảo:.*$','',text,flags=re.I|re.S).strip()
|
| 171 |
+
lines=[]
|
| 172 |
+
for ln in text.splitlines():
|
| 173 |
+
ln=_strip_bullet_prefix(ln)
|
| 174 |
+
if len(ln)>=18:lines.append(ln)
|
| 175 |
+
if len(lines)<2:
|
| 176 |
+
lines=[_strip_bullet_prefix(s) for s in re.split(r'(?<=[\.\!\?])\s+',text) if len(_strip_bullet_prefix(s))>=25]
|
| 177 |
+
segs=[];cur=''
|
| 178 |
+
for ln in lines:
|
| 179 |
+
ln=_strip_bullet_prefix(ln)
|
| 180 |
+
if not ln:continue
|
| 181 |
+
if len(cur)+len(ln)<180:cur=(cur+' '+ln).strip()
|
| 182 |
+
else:
|
| 183 |
+
if cur:segs.append(_strip_bullet_prefix(cur))
|
| 184 |
+
cur=ln
|
| 185 |
+
if cur:segs.append(_strip_bullet_prefix(cur))
|
| 186 |
+
return segs[:max_segments] or [_strip_bullet_prefix(post.get('title','VNEWS'))]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def wrap_text(draw,text,font,maxw,max_lines):
|
| 190 |
+
words=clean(text).split();lines=[];cur=''
|
| 191 |
+
for w in words:
|
| 192 |
+
test=(cur+' '+w).strip()
|
| 193 |
+
try:width=draw.textbbox((0,0),test,font=font)[2]
|
| 194 |
+
except Exception:width=len(test)*20
|
| 195 |
+
if width<=maxw:cur=test
|
| 196 |
+
else:
|
| 197 |
+
if cur:lines.append(cur)
|
| 198 |
+
cur=w
|
| 199 |
+
if len(lines)>=max_lines:break
|
| 200 |
+
if cur and len(lines)<max_lines:lines.append(cur)
|
| 201 |
+
return lines
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def _draw_center(draw, lines, font, y, fill, W, line_h):
|
| 205 |
+
for ln in lines:
|
| 206 |
+
try:
|
| 207 |
+
box=draw.textbbox((0,0),ln,font=font);tw=box[2]-box[0]
|
| 208 |
+
except Exception:
|
| 209 |
+
tw=len(ln)*24
|
| 210 |
+
x=max(30,(W-tw)//2)
|
| 211 |
+
draw.text((x,y),ln,fill=fill,font=font)
|
| 212 |
+
y+=line_h
|
| 213 |
+
return y
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def make_frame(post,seg,idx,total,img_path,out_path):
|
| 217 |
+
if Image is None:raise RuntimeError('Pillow not ready')
|
| 218 |
+
W,H=1080,1920;bg=Image.new('RGB',(W,H),(12,12,12))
|
| 219 |
+
hero_h=760
|
| 220 |
+
try:
|
| 221 |
+
im=Image.open(img_path).convert('RGB');ratio=im.width/max(1,im.height)
|
| 222 |
+
target=(W,hero_h);tr=target[0]/target[1]
|
| 223 |
+
if ratio>tr:nh=target[1];nw=int(nh*ratio)
|
| 224 |
+
else:nw=target[0];nh=int(nw/ratio)
|
| 225 |
+
im=im.resize((nw,nh));left=(nw-target[0])//2;top=(nh-target[1])//2
|
| 226 |
+
bg.paste(im.crop((left,top,left+target[0],top+target[1])),(0,0))
|
| 227 |
+
except Exception:pass
|
| 228 |
+
draw=ImageDraw.Draw(bg)
|
| 229 |
+
try:
|
| 230 |
+
fb=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',58)
|
| 231 |
+
ft=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',38)
|
| 232 |
+
fs=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',30)
|
| 233 |
+
fsmall=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',28)
|
| 234 |
+
except Exception:fb=ft=fs=fsmall=None
|
| 235 |
+
badge='Nguồn: '+_source_badge(post)
|
| 236 |
+
try:
|
| 237 |
+
b=draw.textbbox((0,0),badge,font=fsmall);bw=b[2]-b[0];bh=b[3]-b[1]
|
| 238 |
+
except Exception:
|
| 239 |
+
bw=len(badge)*16;bh=34
|
| 240 |
+
bx=W-bw-42;by=24
|
| 241 |
+
draw.rounded_rectangle((bx-16,by-8,W-24,by+bh+14),radius=18,fill=(0,0,0,170))
|
| 242 |
+
draw.text((bx,by),badge,fill=(255,255,255),font=fsmall)
|
| 243 |
+
draw.rectangle((0,hero_h-20,W,H),fill=(12,12,12))
|
| 244 |
+
total_w=total*38-14;start=(W-total_w)//2
|
| 245 |
+
for i in range(total):
|
| 246 |
+
fill=(92,184,122) if i==idx else (70,70,70)
|
| 247 |
+
draw.rounded_rectangle((start+i*38,820,start+i*38+24,832),radius=6,fill=fill)
|
| 248 |
+
brand='VNEWS AI SHORT'
|
| 249 |
+
try:
|
| 250 |
+
bb=draw.textbbox((0,0),brand,font=ft);tx=(W-(bb[2]-bb[0]))//2
|
| 251 |
+
except Exception:tx=360
|
| 252 |
+
draw.text((tx,870),brand,fill=(110,231,143),font=ft)
|
| 253 |
+
clean_seg=_strip_bullet_prefix(seg)
|
| 254 |
+
lines=wrap_text(draw,clean_seg,fb,W-120,8)
|
| 255 |
+
block_h=len(lines)*74
|
| 256 |
+
y=max(980, 1250-block_h//2)
|
| 257 |
+
_draw_center(draw,lines,fb,y,(255,255,255),W,74)
|
| 258 |
+
title_lines=wrap_text(draw,_strip_bullet_prefix(post.get('title','')),fs,W-120,3)
|
| 259 |
+
y2=1640
|
| 260 |
+
draw.line((80,y2-26,W-80,y2-26),fill=(70,70,70),width=2)
|
| 261 |
+
_draw_center(draw,title_lines,fs,y2,(220,220,220),W,42)
|
| 262 |
+
bg.save(out_path,quality=92)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def make_tts(text,voice,out_path):
|
| 266 |
+
v={'nam':'vi-VN-NamMinhNeural','male':'vi-VN-NamMinhNeural','nu':'vi-VN-HoaiMyNeural','female':'vi-VN-HoaiMyNeural','mien-nam':'vi-VN-HoaiMyNeural'}.get(voice,'vi-VN-HoaiMyNeural')
|
| 267 |
+
text=_strip_bullet_prefix(text)
|
| 268 |
+
try:subprocess.run(['python','-m','edge_tts','--voice',v,'--text',text,'--write-media',out_path],check=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=160)
|
| 269 |
+
except Exception:
|
| 270 |
+
tld='com.vn' if voice in ('nu','female','mien-nam') else 'com'
|
| 271 |
+
try:base.gTTS(text,lang='vi',tld=tld,slow=False).save(out_path)
|
| 272 |
+
except TypeError:base.gTTS(text,lang='vi',slow=False).save(out_path)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
@app.post('/api/ai/short/{post_id}')
|
| 276 |
+
async def short_segments(post_id:str,request:Request):
|
| 277 |
+
try:body=await request.json()
|
| 278 |
+
except Exception:body={}
|
| 279 |
+
voice=str(body.get('voice','nu')).lower().strip();emotion=str(body.get('emotion','neutral')).lower().strip();speed=max(0.85,min(1.35,float(body.get('speed',1.2) or 1.2)))
|
| 280 |
+
posts=base._load_ai_wall();post=next((p for p in posts if str(p.get('id'))==str(post_id)),None)
|
| 281 |
+
if not post:return JSONResponse({'error':'post not found'},status_code=404)
|
| 282 |
+
segs=split_segments(post,8)
|
| 283 |
+
os.makedirs(base.SHORTS_DIR,exist_ok=True);suffix=f'_{voice}_{emotion}_{str(speed).replace(".","p")}_centered_source_nobullet'
|
| 284 |
+
out=os.path.join(base.SHORTS_DIR,base._safe_name(post_id+suffix)+'.mp4')
|
| 285 |
+
if os.path.exists(out):post['video']='/api/ai/short-file/'+post_id+suffix;base._save_ai_wall(posts);return JSONResponse({'video':post['video'],'segments':len(segs),'subtitles':False})
|
| 286 |
+
work=os.path.join(base.SHORTS_DIR,base._safe_name(post_id+suffix));os.makedirs(work,exist_ok=True)
|
| 287 |
+
img=os.path.join(work,'image.jpg');base._download_image(post.get('img'),post.get('title','AI news'),img)
|
| 288 |
+
clips=[]
|
| 289 |
+
try:
|
| 290 |
+
for i,seg in enumerate(segs):
|
| 291 |
+
frame=os.path.join(work,f'f{i}.jpg');aud=os.path.join(work,f'a{i}.mp3');aud2=os.path.join(work,f'a{i}_fast.mp3');clip=os.path.join(work,f'c{i}.mp4')
|
| 292 |
+
seg=_strip_bullet_prefix(seg)
|
| 293 |
+
make_frame(post,seg,i,len(segs),img,frame)
|
| 294 |
+
prefix={'urgent':'Tin nhanh.','warm':'Câu chuyện đáng chú ý.','serious':'Bản tin nghiêm túc.','energetic':'Cập nhật nổi bật.'}.get(emotion,'')
|
| 295 |
+
spoken=(prefix+' '+seg).strip() if i==0 and prefix else seg
|
| 296 |
+
make_tts(spoken,voice,aud)
|
| 297 |
+
subprocess.run(['ffmpeg','-y','-i',aud,'-filter:a',f'atempo={speed}','-vn',aud2],check=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=120)
|
| 298 |
+
subprocess.run(['ffmpeg','-y','-loop','1','-i',frame,'-i',aud2,'-shortest','-c:v','libx264','-tune','stillimage','-pix_fmt','yuv420p','-c:a','aac','-b:a','128k','-vf','scale=1080:1920',clip],check=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=180)
|
| 299 |
+
clips.append(clip)
|
| 300 |
+
lf=os.path.join(work,'list.txt')
|
| 301 |
+
with open(lf,'w',encoding='utf-8') as f:
|
| 302 |
+
for c in clips:f.write("file '{}".format(c.replace("'","'\\''"))+"'\n")
|
| 303 |
+
subprocess.run(['ffmpeg','-y','-f','concat','-safe','0','-i',lf,'-c','copy',out],check=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=240)
|
| 304 |
+
post['video']='/api/ai/short-file/'+post_id+suffix;post['short_subtitles']=False;post['short_segments']=segs;post['short_speed']=speed;base._save_ai_wall(posts)
|
| 305 |
+
return JSONResponse({'video':post['video'],'segments':len(segs),'subtitles':False})
|
| 306 |
+
except Exception as e:return JSONResponse({'error':'Không tạo được shorts: '+str(e)[:200]},status_code=500)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
@app.get('/api/ai/short-file/{file_id}')
|
| 310 |
+
def short_file(file_id:str):
|
| 311 |
+
path=os.path.join(base.SHORTS_DIR,base._safe_name(file_id)+'.mp4')
|
| 312 |
+
if not os.path.exists(path):return JSONResponse({'error':'not found'},status_code=404)
|
| 313 |
+
return FileResponse(path,media_type='video/mp4',filename=f'vnews-ai-{file_id}.mp4')
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
app.router.routes=[r for r in app.router.routes if not (getattr(r,'path',None)=='/' and 'GET' in getattr(r,'methods',set()))]
|
| 317 |
+
@app.get('/')
|
| 318 |
+
async def index_runtime():
|
| 319 |
+
with open('/app/static/index.html','r',encoding='utf-8') as f:html=f.read()
|
| 320 |
+
inject=getattr(old,'PATCH_INJECT','')+r'''
|
| 321 |
+
<style>
|
| 322 |
+
#ai-topic-input{display:none!important}
|
| 323 |
+
#ai-topic-input,*[onclick*="createTopicPost"]{display:none!important}
|
| 324 |
+
.ai-topic-row,.topic-row,.ai-compose-topic{display:none!important}
|
| 325 |
+
.ai-wall-gallery{display:grid;grid-template-columns:repeat(2,1fr);gap:6px;margin:10px 0}.ai-wall-gallery img{width:100%;aspect-ratio:16/9;object-fit:cover;border-radius:8px;background:#222}.ai-wall-gallery img:first-child{grid-column:1/-1}.ai-url-only-note{font-size:11px;color:#888;margin:5px 0 8px}
|
| 326 |
+
</style>
|
| 327 |
+
<script>
|
| 328 |
+
(function(){
|
| 329 |
+
function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));}
|
| 330 |
+
function hideTopicControls(){
|
| 331 |
+
document.querySelectorAll('#ai-topic-input').forEach(e=>{let p=e.closest('.ai-compose,.ai-compose-topic,.topic-row,div'); if(p&&p.querySelector('#ai-url-input')) e.style.display='none'; else if(p) p.style.display='none';});
|
| 332 |
+
document.querySelectorAll('button').forEach(b=>{let t=(b.textContent||'').toLowerCase();let oc=b.getAttribute('onclick')||'';if(oc.includes('createTopicPost')||t.includes('chủ đề'))b.style.display='none';});
|
| 333 |
+
let url=document.getElementById('ai-url-input'); if(url&&!document.getElementById('ai-url-only-note')){let n=document.createElement('div');n.id='ai-url-only-note';n.className='ai-url-only-note';n.textContent='Dán URL bài viết để AI tóm tắt và lấy ảnh từ bài.';url.insertAdjacentElement('afterend',n);}
|
| 334 |
+
}
|
| 335 |
+
window.createTopicPost=function(){alert('Đã tắt ô nhập chủ đề. Vui lòng dán URL bài viết.');};
|
| 336 |
+
window.createUrlPost=function(){let inp=document.getElementById('ai-url-input');let url=(inp&&inp.value||'').trim();if(!url)return alert('Dán URL trước');if(!/^https?:\/\//i.test(url))return alert('URL cần bắt đầu bằng http:// hoặc https://');fetch('/api/url_wall',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url})}).then(r=>r.json().then(j=>({ok:r.ok,j}))).then(({ok,j})=>{if(ok&&j.post){if(typeof prependWallPost==='function')prependWallPost(j.post);if(window.patchedWall)window.patchedWall=[j.post].concat(window.patchedWall||[]);if(inp)inp.value='';alert('Đã tóm tắt URL, lấy ảnh trong bài và đăng lên Tường AI');location.reload();}else alert(j.error||'Lỗi URL')}).catch(e=>alert(e.message||'Lỗi URL'));};
|
| 337 |
+
function galleryHtml(p){let imgs=(p.images||[]).filter(Boolean);if(!imgs.length&&p.img)imgs=[p.img];if(!imgs.length)return '';return '<div class="ai-wall-gallery">'+imgs.slice(0,12).map(u=>`<img src="${esc(u)}" loading="lazy">`).join('')+'</div>';}
|
| 338 |
+
function patchReaders(){
|
| 339 |
+
let oldRead=window.aiReadWallPatched||window.aiReadWall;
|
| 340 |
+
window.aiReadWallPatched=window.aiReadWall=function(i){let arr=window.patchedWall||window.aiWall||[];let p=arr[i];if(!p&&oldRead)return oldRead(i);if(!p)return;showView('view-article');let sources='';if(p.sources&&p.sources.length){sources='<div class="article-summary"><b>Nguồn tham khảo:</b><br>'+p.sources.slice(0,5).map(s=>`• ${esc(s.title||s.url||'Nguồn')} ${s.url?`(${esc(new URL(s.url).hostname.replace('www.',''))})`:''}`).join('<br>')+'</div>'}let h=`<button class="back-btn" onclick="switchCat('home')">← Quay lại</button><div class="article-view"><span class="badge badge-ai">AI</span><h1 class="article-title">${esc(p.title)}</h1>${galleryHtml(p)}${sources}<p class="article-p" style="white-space:pre-wrap">${esc(p.text)}</p>${p.video?`<video class="article-img" src="${p.video}" controls playsinline></video>`:''}<div class="article-actions">${p.url?`<button onclick="window.open('${p.url}','_blank')">🔗 Nguồn</button>`:''}<button onclick="aiMakeShortPatched?aiMakeShortPatched(${i}):aiMakeShort(${i})">🎬 Tạo video shorts</button></div></div>`;document.getElementById('view-article').innerHTML=h;window.scrollTo(0,0);};
|
| 341 |
+
}
|
| 342 |
+
setInterval(hideTopicControls,1000);setTimeout(hideTopicControls,300);setTimeout(patchReaders,1600);
|
| 343 |
+
})();
|
| 344 |
+
</script>
|
| 345 |
+
'''
|
| 346 |
+
return HTMLResponse(html.replace('</body>',inject+'\n</body>') if '</body>' in html else html+inject)
|