bep40 commited on
Commit
eb55d03
·
verified ·
1 Parent(s): a435547

Restore complete ai_runtime.py from c93b544 (18.9KB)

Browse files
Files changed (1) hide show
  1. ai_runtime.py +195 -2
ai_runtime.py CHANGED
@@ -24,7 +24,7 @@ def _domain(url):
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):
@@ -125,7 +125,19 @@ async def url_wall_only(request:Request):
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.\n\nYêu cầu bắt buộc:\n- Chỉ tóm tắt nội dung chính, không viết lại toàn bộ bài.\n- Ngắn gọn, cụ thể, dễ hiểu.\n- Không lặp lại ý và không thêm chi tiết ngoài nguồn.\n- Tối đa 5 ý chính hoặc 2 đoạn ngắn.\n- Tránh dùng dấu đầu dòng nếu không thật cần thiết.\n\nTiêu đề gốc: {data.get('title','')}\nNguồn: {data.get('via','') or _domain(url)}\nNội dung gốc:\n{raw[:16000]}"
 
 
 
 
 
 
 
 
 
 
 
 
129
  text=await base.qwen_generate(prompt,image_url=(data.get('image') or None),max_tokens=900)
130
  if not text:text=old._fallback_summary_from_prompt(prompt,max_units=5) if hasattr(old,'_fallback_summary_from_prompt') else raw[:900]
131
  text=postprocess(text)
@@ -151,3 +163,184 @@ async def ai_url_compat(request:Request):
151
  @app.post('/api/topic_post')
152
  async def topic_disabled(request:Request):
153
  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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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):
 
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)
 
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=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[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)