Spaces:
Running
Running
Upload ai_runtime_patch_fast.py
Browse files- ai_runtime_patch_fast.py +228 -22
ai_runtime_patch_fast.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
"""Final patch v2: fix topic rewrite, remove duplicate short slide, full short interaction buttons.
|
| 2 |
-
FIX v3: rewrite slides with images from og_image, short video auto-gen."""
|
| 3 |
-
import re, threading, time, json, os, asyncio
|
| 4 |
import ai_runtime_final6 as f6
|
| 5 |
from ai_runtime_final6 import app, rt, f5, HTMLResponse, JSONResponse, Request, Query
|
| 6 |
import html as html_lib
|
|
@@ -14,6 +14,8 @@ DATA_DIR="/data" if os.path.isdir('/data') else "/app/data"
|
|
| 14 |
os.makedirs(DATA_DIR,exist_ok=True)
|
| 15 |
SHORT_COMMENTS_FILE=os.path.join(DATA_DIR,'short_comments.json')
|
| 16 |
TTL_24H=86400;HAS_PERSISTENT=os.path.isdir('/data')
|
|
|
|
|
|
|
| 17 |
def _lj(p,d):
|
| 18 |
try:
|
| 19 |
if os.path.exists(p):return json.load(open(p,'r',encoding='utf-8'))
|
|
@@ -29,6 +31,219 @@ def _scrape(url,mc=8000):
|
|
| 29 |
try:d=f5.base.scrape_any_url(url);return(d.get('title',''),((d.get('summary','')+'\n'+d.get('text','')).strip())[:mc],d.get('image') or d.get('og_image') or '')
|
| 30 |
except:return('','','')
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
_bg_home={"t":0,"d":[]};_bg_shorts={"t":0,"d":[]};_bg_lock=False
|
| 33 |
def _bg():
|
| 34 |
global _bg_lock
|
|
@@ -89,15 +304,12 @@ async def _rw(request:Request):
|
|
| 89 |
if len(raw)<50:return JSONResponse({'error':'Không đọc được bài'},status_code=422)
|
| 90 |
|
| 91 |
# Get og_image for slides
|
| 92 |
-
og_img = ''
|
| 93 |
-
try:
|
| 94 |
-
d = f5.base.scrape_any_url(url)
|
| 95 |
-
if d:
|
| 96 |
-
og_img = d.get('og_image', '') or d.get('image', '') or ''
|
| 97 |
-
except:
|
| 98 |
-
pass
|
| 99 |
if not og_img:
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
| 101 |
if not og_img:
|
| 102 |
og_img = 'https://image.pollinations.ai/prompt/Vietnamese%20news%20update'
|
| 103 |
|
|
@@ -115,20 +327,15 @@ async def _rw(request:Request):
|
|
| 115 |
for i, pt in enumerate(paragraphs[:8]):
|
| 116 |
slides.append({'text': pt, 'image': og_img, 'index': i + 1})
|
| 117 |
|
| 118 |
-
|
| 119 |
-
post=f5.base.make_post(title or 'Bài viết',text,main_img,url,'rewrite',sources=[{'title':title,'url':url,'via':_domain(url)}])
|
| 120 |
post['images'] = [og_img] if og_img else []
|
| 121 |
post['slides'] = slides
|
| 122 |
ps=f5.base._load_ai_wall();ps.insert(0,post);f5.base._save_ai_wall(ps)
|
| 123 |
|
| 124 |
-
#
|
| 125 |
-
if len(text) > 100
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
t = threading.Thread(target=lambda: auto_scheduler._try_generate_short(post), daemon=True)
|
| 129 |
-
t.start()
|
| 130 |
-
except:
|
| 131 |
-
pass
|
| 132 |
|
| 133 |
return JSONResponse({'post':post})
|
| 134 |
|
|
@@ -171,7 +378,6 @@ PATCH_INJECT=r'''
|
|
| 171 |
.article-ai-ask{margin-top:12px;background:#141414;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.article-ai-ask textarea{width:100%;min-height:60px;background:#222;border:1px solid #444;color:#eee;border-radius:10px;padding:9px}.article-ai-ask button{background:#2d8659;border:0;color:#fff;border-radius:10px;padding:8px 12px;margin-top:6px}.article-ai-answer{white-space:pre-wrap;color:#ccc;font-size:13px;line-height:1.55;margin-top:8px}
|
| 172 |
.storage-warn{background:#332200;border:1px solid #664400;color:#ffcc00;padding:8px 12px;border-radius:8px;font-size:11px;margin:6px 4px}
|
| 173 |
button[onclick*="rewriteCurrentArticle"]{display:none!important}
|
| 174 |
-
/* Hide ALL old Short AI slides from previous layers */
|
| 175 |
#ai-short-home,.ai-short-home,.ai-short-card-final{display:none!important}
|
| 176 |
.source-detail-box a[target="_blank"]{display:none!important}
|
| 177 |
</style>
|
|
@@ -181,7 +387,7 @@ button[onclick*="rewriteCurrentArticle"]{display:none!important}
|
|
| 181 |
function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));}
|
| 182 |
fetch('/api/storage_status').then(r=>r.json()).then(j=>{if(!j.persistent){let h=document.getElementById('view-home');if(h){let w=document.createElement('div');w.className='storage-warn';w.innerHTML='⚠️ <b>Persistent Storage chưa bật.</b> Bật: Space Settings → Persistent Storage → Small.';h.prepend(w);}}});
|
| 183 |
async function renderShortAISlide(){let home=document.getElementById('view-home');if(!home)return;document.getElementById('short-ai-final-slide')?.remove();let wall=(await fetch('/api/ai_wall').then(r=>r.json()).catch(()=>({posts:[]}))).posts||[];let vids=wall.filter(p=>p.video);if(!vids.length)return;let wrap=document.createElement('div');wrap.id='short-ai-final-slide';wrap.className='slider-wrap';wrap.innerHTML='<div class="slider-header"><span class="slider-label">🎬 Short AI</span></div><div class="slider-track">'+vids.slice(0,30).map((p,i)=>`<div class="slider-item shorts-item" onclick="openAIShortFeed(${i})"><div class="slider-thumb shorts-thumb"><video src="${p.video}" muted preload="metadata" style="width:100%;height:100%;object-fit:cover"></video><div class="card-play">▶</div></div><div class="slider-title">${esc(p.title)}</div></div>`).join('')+'</div>';let comp=home.querySelector('.ai-compose');if(comp&&comp.nextSibling)comp.parentNode.insertBefore(wrap,comp.nextSibling);else home.prepend(wrap);}
|
| 184 |
-
setTimeout(renderShortAISlide,2500);
|
| 185 |
function renderSourceDetails(post,container){let det=post.source_details||[];if(!det.length)return;container.querySelectorAll('.source-detail-box').forEach(e=>e.remove());let box=document.createElement('div');box.className='source-detail-box';box.innerHTML='<h3 style="font-size:14px;color:#5cb87a;margin-bottom:8px">📚 Bài nguồn</h3>'+det.map((s,i)=>`<div class="source-detail-item" data-url="${esc(s.url||'')}"><div class="source-detail-title">${i+1}. ${esc(s.title)}</div><div class="source-detail-content">${esc((s.content||'').slice(0,300))}</div><span class="source-vnews-btn">📖 Xem trên VNEWS</span></div>`).join('');container.appendChild(box);box.querySelectorAll('.source-detail-item').forEach(el=>{el.onclick=function(){let u=el.dataset.url;if(u&&typeof readArticle==='function')readArticle(u);}});det.forEach((s,i)=>{if(!s.url)return;fetch('/api/article?url='+encodeURIComponent(s.url)).then(r=>r.json()).then(d=>{if(d&&(d.og_image||d.img)){let items=box.querySelectorAll('.source-detail-item');if(items[i]){let img=document.createElement('img');img.src=d.og_image||d.img;img.loading='lazy';img.onerror=function(){this.style.display='none'};items[i].prepend(img);}}}).catch(()=>{});});}
|
| 186 |
async function readAIWallPost(i){let wall=(await fetch('/api/ai_wall').then(r=>r.json()).catch(()=>({posts:[]}))).posts||[];let p=wall[i];if(!p)return;showView('view-article');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>${p.img?`<img class="article-img" src="${p.img}">`:''}`;h+=`<p class="article-p" style="white-space:pre-wrap">${esc(p.text)}</p>`;h+=`<div class="article-actions"><button class="primary" onclick="doRewriteTopic(this,'${esc(p.id)}')">🤖 Rewrite AI đăng tường</button>${p.video?`<button onclick="openAIShortFeed(${i})">🎬 Xem Short</button>`:''}<button onclick="doShare('${esc(p.title)}','${location.origin}','${esc(p.img||'')}')">📤</button></div>`;h+=`<div class="article-ai-ask"><h3 style="font-size:14px;color:#5cb87a">🤖 Hỏi AI</h3><textarea id="article-ai-q" placeholder="Hỏi về nội dung..."></textarea><button onclick="askAIWall(${i})">Hỏi</button><div id="article-ai-ans" class="article-ai-answer"></div></div></div>`;document.getElementById('view-article').innerHTML=h;let art=document.querySelector('.article-view');if(art)renderSourceDetails(p,art);window.scrollTo(0,0);}
|
| 187 |
window.readAIWallPost=readAIWallPost;window.aiReadWallPatched=window.aiReadWall=window.readWallPost=function(i){readAIWallPost(i)};
|
|
|
|
| 1 |
"""Final patch v2: fix topic rewrite, remove duplicate short slide, full short interaction buttons.
|
| 2 |
+
FIX v3: rewrite slides with images from og_image, short video auto-gen within process."""
|
| 3 |
+
import re, threading, time, json, os, asyncio, hashlib, subprocess
|
| 4 |
import ai_runtime_final6 as f6
|
| 5 |
from ai_runtime_final6 import app, rt, f5, HTMLResponse, JSONResponse, Request, Query
|
| 6 |
import html as html_lib
|
|
|
|
| 14 |
os.makedirs(DATA_DIR,exist_ok=True)
|
| 15 |
SHORT_COMMENTS_FILE=os.path.join(DATA_DIR,'short_comments.json')
|
| 16 |
TTL_24H=86400;HAS_PERSISTENT=os.path.isdir('/data')
|
| 17 |
+
SHORTS_DIR = os.path.join(DATA_DIR, 'ai_shorts')
|
| 18 |
+
os.makedirs(SHORTS_DIR, exist_ok=True)
|
| 19 |
def _lj(p,d):
|
| 20 |
try:
|
| 21 |
if os.path.exists(p):return json.load(open(p,'r',encoding='utf-8'))
|
|
|
|
| 31 |
try:d=f5.base.scrape_any_url(url);return(d.get('title',''),((d.get('summary','')+'\n'+d.get('text','')).strip())[:mc],d.get('image') or d.get('og_image') or '')
|
| 32 |
except:return('','','')
|
| 33 |
|
| 34 |
+
# ===== Self-contained Short Video Generator =====
|
| 35 |
+
def _make_short(post):
|
| 36 |
+
"""Generate short video for a post. Runs in background thread."""
|
| 37 |
+
post_id = post.get('id', '')
|
| 38 |
+
if not post_id:
|
| 39 |
+
return
|
| 40 |
+
try:
|
| 41 |
+
# Check gTTS availability
|
| 42 |
+
try:
|
| 43 |
+
from gtts import gTTS
|
| 44 |
+
except:
|
| 45 |
+
return
|
| 46 |
+
|
| 47 |
+
text = post.get('text', '') or post.get('title', '')
|
| 48 |
+
if len(text) < 100:
|
| 49 |
+
return
|
| 50 |
+
|
| 51 |
+
# Extract segments from text (bullet points or sentences)
|
| 52 |
+
segments = []
|
| 53 |
+
for line in text.split('\n'):
|
| 54 |
+
line = clean(line)
|
| 55 |
+
if line and len(line) > 20:
|
| 56 |
+
segments.append(line)
|
| 57 |
+
if not segments:
|
| 58 |
+
segments = [text[:300]]
|
| 59 |
+
segments = segments[:10]
|
| 60 |
+
|
| 61 |
+
seg_hash = hashlib.md5(('|'.join(segments) + 'nu' + 'neutral' + '1.0').encode('utf-8')).hexdigest()[:8]
|
| 62 |
+
suffix = f"_nu_neutral_1p0_{seg_hash}_scenes_nosub"
|
| 63 |
+
out_mp4 = os.path.join(SHORTS_DIR, f5.base._safe_name(post_id + suffix) + '.mp4')
|
| 64 |
+
|
| 65 |
+
# Check if already generated
|
| 66 |
+
if os.path.exists(out_mp4):
|
| 67 |
+
post['video'] = '/api/ai/short-file/' + post_id + suffix
|
| 68 |
+
wall = f5.base._load_ai_wall()
|
| 69 |
+
for i, p in enumerate(wall):
|
| 70 |
+
if p.get('id') == post_id:
|
| 71 |
+
wall[i] = post
|
| 72 |
+
break
|
| 73 |
+
f5.base._save_ai_wall(wall)
|
| 74 |
+
return
|
| 75 |
+
|
| 76 |
+
work = os.path.join(SHORTS_DIR, f5.base._safe_name(post_id + suffix))
|
| 77 |
+
os.makedirs(work, exist_ok=True)
|
| 78 |
+
|
| 79 |
+
# Download image for background
|
| 80 |
+
img_path = os.path.join(work, 'image.jpg')
|
| 81 |
+
downloaded = False
|
| 82 |
+
try:
|
| 83 |
+
img_url = post.get('img', '')
|
| 84 |
+
if img_url:
|
| 85 |
+
r = requests.get(img_url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=15)
|
| 86 |
+
if r.status_code == 200:
|
| 87 |
+
with open(img_path, 'wb') as f:
|
| 88 |
+
f.write(r.content)
|
| 89 |
+
downloaded = True
|
| 90 |
+
except:
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
# Create scene frames and TTS audio
|
| 94 |
+
part_files = []
|
| 95 |
+
try:
|
| 96 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 97 |
+
has_pil = True
|
| 98 |
+
except:
|
| 99 |
+
has_pil = False
|
| 100 |
+
|
| 101 |
+
for idx, seg in enumerate(segments[:10]):
|
| 102 |
+
frame_path = os.path.join(work, f'frame_{idx:02d}.jpg')
|
| 103 |
+
audio_path = os.path.join(work, f'voice_{idx:02d}.mp3')
|
| 104 |
+
audio_fast = os.path.join(work, f'voice_{idx:02d}_fast.mp3')
|
| 105 |
+
part_path = os.path.join(work, f'part_{idx:02d}.mp4')
|
| 106 |
+
|
| 107 |
+
# Create frame
|
| 108 |
+
if has_pil:
|
| 109 |
+
sz = (1080, 1920)
|
| 110 |
+
bg_color = (15, 23, 38)
|
| 111 |
+
bg = Image.new('RGB', sz, bg_color)
|
| 112 |
+
draw = ImageDraw.Draw(bg)
|
| 113 |
+
|
| 114 |
+
# Try to overlay downloaded image at top
|
| 115 |
+
if downloaded:
|
| 116 |
+
try:
|
| 117 |
+
im = Image.open(img_path).convert('RGB')
|
| 118 |
+
im = im.resize((1080, 760))
|
| 119 |
+
bg.paste(im, (0, 0))
|
| 120 |
+
# Dark overlay for text readability
|
| 121 |
+
overlay = Image.new('RGBA', (1080, 400), (0, 0, 0, 180))
|
| 122 |
+
bg.paste(overlay, (0, 720), overlay)
|
| 123 |
+
except:
|
| 124 |
+
pass
|
| 125 |
+
|
| 126 |
+
try:
|
| 127 |
+
font_title = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 52)
|
| 128 |
+
font_body = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 40)
|
| 129 |
+
except:
|
| 130 |
+
font_title = font_body = None
|
| 131 |
+
|
| 132 |
+
# Title bar
|
| 133 |
+
draw.rectangle([0, 0, sz[0], 100], fill=(25, 118, 210))
|
| 134 |
+
title = post.get('title', '')[:50]
|
| 135 |
+
if font_title:
|
| 136 |
+
draw.text((sz[0]//2, 50), title, fill='white', font=font_title, anchor='mm')
|
| 137 |
+
|
| 138 |
+
# Segment text
|
| 139 |
+
y_start = 820
|
| 140 |
+
seg_text = seg[:150]
|
| 141 |
+
lines = []
|
| 142 |
+
words = seg_text.split()
|
| 143 |
+
cur = ''
|
| 144 |
+
for w in words:
|
| 145 |
+
test = (cur + ' ' + w).strip()
|
| 146 |
+
try:
|
| 147 |
+
tw = draw.textbbox((0, 0), test, font=font_body)[2] if font_body else len(test) * 20
|
| 148 |
+
except:
|
| 149 |
+
tw = len(test) * 20
|
| 150 |
+
if tw <= 920:
|
| 151 |
+
cur = test
|
| 152 |
+
else:
|
| 153 |
+
if cur:
|
| 154 |
+
lines.append(cur)
|
| 155 |
+
cur = w
|
| 156 |
+
if len(lines) >= 6:
|
| 157 |
+
break
|
| 158 |
+
if cur and len(lines) < 6:
|
| 159 |
+
lines.append(cur)
|
| 160 |
+
|
| 161 |
+
y = y_start
|
| 162 |
+
for ln in lines:
|
| 163 |
+
if font_body:
|
| 164 |
+
draw.text((80, y), ln, fill=(255, 255, 255), font=font_body)
|
| 165 |
+
y += 55
|
| 166 |
+
|
| 167 |
+
bg.save(frame_path, quality=88)
|
| 168 |
+
else:
|
| 169 |
+
# Fallback: solid color frame
|
| 170 |
+
if not os.path.exists(img_path):
|
| 171 |
+
from PIL import Image as Img
|
| 172 |
+
Img.new('RGB', (1080, 1920), (15, 23, 38)).save(frame_path, quality=85)
|
| 173 |
+
else:
|
| 174 |
+
try:
|
| 175 |
+
from PIL import Image as Img
|
| 176 |
+
Img.new('RGB', (1080, 1920), (15, 23, 38)).save(frame_path, quality=85)
|
| 177 |
+
except:
|
| 178 |
+
continue
|
| 179 |
+
|
| 180 |
+
# Generate TTS
|
| 181 |
+
tts_text = re.sub(r'^[•\-\*\d\.\)\s]+', '', seg).strip()[:300]
|
| 182 |
+
if not tts_text:
|
| 183 |
+
continue
|
| 184 |
+
try:
|
| 185 |
+
gTTS(tts_text, lang='vi', slow=False).save(audio_path)
|
| 186 |
+
except:
|
| 187 |
+
try:
|
| 188 |
+
gTTS(tts_text, lang='vi', tld='com.vn', slow=False).save(audio_path)
|
| 189 |
+
except:
|
| 190 |
+
continue
|
| 191 |
+
|
| 192 |
+
# Speed up audio
|
| 193 |
+
try:
|
| 194 |
+
subprocess.run(['ffmpeg', '-y', '-i', audio_path, '-filter:a', 'atempo=1.0', '-vn', audio_fast],
|
| 195 |
+
check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=90)
|
| 196 |
+
except:
|
| 197 |
+
audio_fast = audio_path
|
| 198 |
+
|
| 199 |
+
# Get duration
|
| 200 |
+
dur = 10.0
|
| 201 |
+
try:
|
| 202 |
+
pr = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:no_key=1', audio_fast],
|
| 203 |
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20)
|
| 204 |
+
dur = max(6.0, float((pr.stdout or b'').decode().strip() or 10.0)) + 1.0
|
| 205 |
+
except:
|
| 206 |
+
pass
|
| 207 |
+
|
| 208 |
+
# Combine frame + audio
|
| 209 |
+
try:
|
| 210 |
+
subprocess.run(['ffmpeg', '-y', '-loop', '1', '-t', str(dur), '-i', frame_path, '-i', audio_fast,
|
| 211 |
+
'-shortest', '-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p',
|
| 212 |
+
'-c:a', 'aac', '-b:a', '128k', part_path],
|
| 213 |
+
check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=150)
|
| 214 |
+
part_files.append(part_path)
|
| 215 |
+
except:
|
| 216 |
+
continue
|
| 217 |
+
|
| 218 |
+
# Concatenate all parts
|
| 219 |
+
if part_files:
|
| 220 |
+
concat_file = os.path.join(work, 'concat.txt')
|
| 221 |
+
with open(concat_file, 'w', encoding='utf-8') as f:
|
| 222 |
+
for p in part_files:
|
| 223 |
+
f.write("file '" + p.replace("'", "'\\''") + "'\n")
|
| 224 |
+
try:
|
| 225 |
+
subprocess.run(['ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat_file, '-c', 'copy', out_mp4],
|
| 226 |
+
check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=180)
|
| 227 |
+
except:
|
| 228 |
+
return
|
| 229 |
+
|
| 230 |
+
# Update post with video link
|
| 231 |
+
post['video'] = '/api/ai/short-file/' + post_id + suffix
|
| 232 |
+
post['short_voice'] = 'nu'
|
| 233 |
+
post['short_emotion'] = 'neutral'
|
| 234 |
+
post['short_speed'] = 1.0
|
| 235 |
+
post['short_segments'] = segments
|
| 236 |
+
post['short_subtitles'] = False
|
| 237 |
+
|
| 238 |
+
wall = f5.base._load_ai_wall()
|
| 239 |
+
for i, p in enumerate(wall):
|
| 240 |
+
if p.get('id') == post_id:
|
| 241 |
+
wall[i] = post
|
| 242 |
+
break
|
| 243 |
+
f5.base._save_ai_wall(wall)
|
| 244 |
+
except Exception as e:
|
| 245 |
+
pass # Silent fail for background short generation
|
| 246 |
+
|
| 247 |
_bg_home={"t":0,"d":[]};_bg_shorts={"t":0,"d":[]};_bg_lock=False
|
| 248 |
def _bg():
|
| 249 |
global _bg_lock
|
|
|
|
| 304 |
if len(raw)<50:return JSONResponse({'error':'Không đọc được bài'},status_code=422)
|
| 305 |
|
| 306 |
# Get og_image for slides
|
| 307 |
+
og_img = img if img and img.startswith('http') else ''
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
if not og_img:
|
| 309 |
+
try:
|
| 310 |
+
d = f5.base.scrape_any_url(url)
|
| 311 |
+
if d: og_img = d.get('og_image', '') or d.get('image', '') or ''
|
| 312 |
+
except: pass
|
| 313 |
if not og_img:
|
| 314 |
og_img = 'https://image.pollinations.ai/prompt/Vietnamese%20news%20update'
|
| 315 |
|
|
|
|
| 327 |
for i, pt in enumerate(paragraphs[:8]):
|
| 328 |
slides.append({'text': pt, 'image': og_img, 'index': i + 1})
|
| 329 |
|
| 330 |
+
post=f5.base.make_post(title or 'Bài viết',text,og_img,url,'rewrite',sources=[{'title':title,'url':url,'via':_domain(url)}])
|
|
|
|
| 331 |
post['images'] = [og_img] if og_img else []
|
| 332 |
post['slides'] = slides
|
| 333 |
ps=f5.base._load_ai_wall();ps.insert(0,post);f5.base._save_ai_wall(ps)
|
| 334 |
|
| 335 |
+
# Generate short video in background (direct call, no auto_scheduler dependency)
|
| 336 |
+
if len(text) > 100:
|
| 337 |
+
t = threading.Thread(target=_make_short, args=(post,), daemon=True)
|
| 338 |
+
t.start()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
|
| 340 |
return JSONResponse({'post':post})
|
| 341 |
|
|
|
|
| 378 |
.article-ai-ask{margin-top:12px;background:#141414;border:1px solid #2a2a2a;border-radius:10px;padding:10px}.article-ai-ask textarea{width:100%;min-height:60px;background:#222;border:1px solid #444;color:#eee;border-radius:10px;padding:9px}.article-ai-ask button{background:#2d8659;border:0;color:#fff;border-radius:10px;padding:8px 12px;margin-top:6px}.article-ai-answer{white-space:pre-wrap;color:#ccc;font-size:13px;line-height:1.55;margin-top:8px}
|
| 379 |
.storage-warn{background:#332200;border:1px solid #664400;color:#ffcc00;padding:8px 12px;border-radius:8px;font-size:11px;margin:6px 4px}
|
| 380 |
button[onclick*="rewriteCurrentArticle"]{display:none!important}
|
|
|
|
| 381 |
#ai-short-home,.ai-short-home,.ai-short-card-final{display:none!important}
|
| 382 |
.source-detail-box a[target="_blank"]{display:none!important}
|
| 383 |
</style>
|
|
|
|
| 387 |
function esc(s){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));}
|
| 388 |
fetch('/api/storage_status').then(r=>r.json()).then(j=>{if(!j.persistent){let h=document.getElementById('view-home');if(h){let w=document.createElement('div');w.className='storage-warn';w.innerHTML='⚠️ <b>Persistent Storage chưa bật.</b> Bật: Space Settings → Persistent Storage → Small.';h.prepend(w);}}});
|
| 389 |
async function renderShortAISlide(){let home=document.getElementById('view-home');if(!home)return;document.getElementById('short-ai-final-slide')?.remove();let wall=(await fetch('/api/ai_wall').then(r=>r.json()).catch(()=>({posts:[]}))).posts||[];let vids=wall.filter(p=>p.video);if(!vids.length)return;let wrap=document.createElement('div');wrap.id='short-ai-final-slide';wrap.className='slider-wrap';wrap.innerHTML='<div class="slider-header"><span class="slider-label">🎬 Short AI</span></div><div class="slider-track">'+vids.slice(0,30).map((p,i)=>`<div class="slider-item shorts-item" onclick="openAIShortFeed(${i})"><div class="slider-thumb shorts-thumb"><video src="${p.video}" muted preload="metadata" style="width:100%;height:100%;object-fit:cover"></video><div class="card-play">▶</div></div><div class="slider-title">${esc(p.title)}</div></div>`).join('')+'</div>';let comp=home.querySelector('.ai-compose');if(comp&&comp.nextSibling)comp.parentNode.insertBefore(wrap,comp.nextSibling);else home.prepend(wrap);}
|
| 390 |
+
setTimeout(renderShortAISlide,2500);setInterval(renderShortAISlide,15000);
|
| 391 |
function renderSourceDetails(post,container){let det=post.source_details||[];if(!det.length)return;container.querySelectorAll('.source-detail-box').forEach(e=>e.remove());let box=document.createElement('div');box.className='source-detail-box';box.innerHTML='<h3 style="font-size:14px;color:#5cb87a;margin-bottom:8px">📚 Bài nguồn</h3>'+det.map((s,i)=>`<div class="source-detail-item" data-url="${esc(s.url||'')}"><div class="source-detail-title">${i+1}. ${esc(s.title)}</div><div class="source-detail-content">${esc((s.content||'').slice(0,300))}</div><span class="source-vnews-btn">📖 Xem trên VNEWS</span></div>`).join('');container.appendChild(box);box.querySelectorAll('.source-detail-item').forEach(el=>{el.onclick=function(){let u=el.dataset.url;if(u&&typeof readArticle==='function')readArticle(u);}});det.forEach((s,i)=>{if(!s.url)return;fetch('/api/article?url='+encodeURIComponent(s.url)).then(r=>r.json()).then(d=>{if(d&&(d.og_image||d.img)){let items=box.querySelectorAll('.source-detail-item');if(items[i]){let img=document.createElement('img');img.src=d.og_image||d.img;img.loading='lazy';img.onerror=function(){this.style.display='none'};items[i].prepend(img);}}}).catch(()=>{});});}
|
| 392 |
async function readAIWallPost(i){let wall=(await fetch('/api/ai_wall').then(r=>r.json()).catch(()=>({posts:[]}))).posts||[];let p=wall[i];if(!p)return;showView('view-article');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>${p.img?`<img class="article-img" src="${p.img}">`:''}`;h+=`<p class="article-p" style="white-space:pre-wrap">${esc(p.text)}</p>`;h+=`<div class="article-actions"><button class="primary" onclick="doRewriteTopic(this,'${esc(p.id)}')">🤖 Rewrite AI đăng tường</button>${p.video?`<button onclick="openAIShortFeed(${i})">🎬 Xem Short</button>`:''}<button onclick="doShare('${esc(p.title)}','${location.origin}','${esc(p.img||'')}')">📤</button></div>`;h+=`<div class="article-ai-ask"><h3 style="font-size:14px;color:#5cb87a">🤖 Hỏi AI</h3><textarea id="article-ai-q" placeholder="Hỏi về nội dung..."></textarea><button onclick="askAIWall(${i})">Hỏi</button><div id="article-ai-ans" class="article-ai-answer"></div></div></div>`;document.getElementById('view-article').innerHTML=h;let art=document.querySelector('.article-view');if(art)renderSourceDetails(p,art);window.scrollTo(0,0);}
|
| 393 |
window.readAIWallPost=readAIWallPost;window.aiReadWallPatched=window.aiReadWall=window.readWallPost=function(i){readAIWallPost(i)};
|