bep40 commited on
Commit
de6789e
·
verified ·
1 Parent(s): f785063

Kill renderTopicWallE BEFORE old injects run, not after"

Browse files
Files changed (1) hide show
  1. app_entry.py +17 -27
app_entry.py CHANGED
@@ -1,4 +1,4 @@
1
- """Wrapper: fast load, no FINAL6E, highlight 1:1, auto title, source image."""
2
  from ai_runtime_patch_fast import *
3
  from ai_runtime_patch_fast import app, f5, f6, rt, PATCH_INJECT, _scrape, _domain, clean, _bg, _bg_home, _bg_shorts
4
  from patch_extra import EXTRA_FIX
@@ -8,7 +8,6 @@ import asyncio, re, threading, time
8
 
9
  DEFAULT_IMG="https://s1.vnecdn.net/vnexpress/restruct/i/v9505/logo_default.jpg"
10
 
11
- # Remove ALL routes we want to override (including homepage/shorts that may block)
12
  app.router.routes=[r for r in app.router.routes if not (
13
  (getattr(r,'path',None)=='/api/homepage' and 'GET' in getattr(r,'methods',set())) or
14
  (getattr(r,'path',None)=='/api/shorts' and 'GET' in getattr(r,'methods',set())) or
@@ -19,13 +18,11 @@ app.router.routes=[r for r in app.router.routes if not (
19
  (getattr(r,'path',None)=='/' and 'GET' in getattr(r,'methods',set()))
20
  )]
21
 
22
- # === FAST HOMEPAGE: never block, always return immediately ===
23
  @app.get('/api/homepage')
24
  def _homepage_fast():
25
  if _bg_home['d']:
26
  if time.time()-_bg_home['t']>300:threading.Thread(target=_bg,daemon=True).start()
27
  return JSONResponse(_bg_home['d'])
28
- # No cache yet — trigger background and return empty immediately (page will reload sections)
29
  threading.Thread(target=_bg,daemon=True).start()
30
  return JSONResponse([])
31
 
@@ -37,7 +34,6 @@ def _shorts_fast(refresh:int=Query(default=0)):
37
  threading.Thread(target=_bg,daemon=True).start()
38
  return JSONResponse([])
39
 
40
- # === Auto title + source image ===
41
  def _extract_title(text):
42
  if not text:return 'Bài viết AI'
43
  lines=[l.strip() for l in text.strip().split('\n') if l.strip()]
@@ -45,7 +41,6 @@ def _extract_title(text):
45
  first=re.sub(r'^[#*\-•\d\.\)\s]+','',lines[0]).strip()
46
  if 10<=len(first)<=120:return first
47
  return lines[0][:100] if lines else 'Bài viết AI'
48
-
49
  def _source_image(sources, details):
50
  for s in (details or []):
51
  if s.get('url'):
@@ -58,7 +53,6 @@ def _source_image(sources, details):
58
  except:img=''
59
  if img and 'pollinations' not in img and len(img)>20:return img
60
  return ''
61
-
62
  def _ensure_img(img):
63
  if img and len(img)>20 and img.startswith('http'):return img
64
  return DEFAULT_IMG
@@ -78,7 +72,6 @@ async def _tp(request:Request):
78
  if not text or len(text)<300: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')}))
79
  post=f5.base.make_post(topic,text,img,'','topic_focused',sources=[s for s in src if s.get('url')]);post['images']=[img];post['source_details']=det
80
  ps=f5.base._load_ai_wall();ps.insert(0,post);f5.base._save_ai_wall(ps);return JSONResponse({'post':post})
81
-
82
  @app.post('/api/rewrite_share')
83
  @app.post('/api/url_wall')
84
  async def _rw(request:Request):
@@ -88,22 +81,14 @@ async def _rw(request:Request):
88
  if len(raw)<50:raw=ctx[:14000]
89
  if len(raw)<50:return JSONResponse({'error':'Không đọc được bài'},status_code=422)
90
  img=_ensure_img(img)
91
- prompt=f"""Tóm tắt bài viết đăng Tường AI. Dòng đầu tiên là TIÊU ĐỀ MỚI hấp dẫn phù hợp nội dung.
92
-
93
- Tiêu đề gốc: {title}
94
- Nội dung:
95
- {raw[:14000]}
96
-
97
- Dòng 1: Tiêu đề mới. Tiếp: 4-6 ý chính. Cuối: nguồn."""
98
  text=None
99
- try:text=await asyncio.wait_for(f5.base.qwen_generate(prompt,image_url=img,max_tokens=1000),timeout=30)
100
  except:pass
101
  if not text or len(text)<80:text=f"{title}\n\n{raw[:1200]}\n\nNguồn: {_domain(url)}"
102
  ai_title=_extract_title(text);lines=text.strip().split('\n')
103
  body_text='\n'.join(lines[1:]).strip() if lines and lines[0].strip()==ai_title else text
104
  post=f5.base.make_post(ai_title,body_text,img,url,'rewrite',sources=[{'title':title,'url':url,'via':_domain(url)}])
105
  ps=f5.base._load_ai_wall();ps.insert(0,post);f5.base._save_ai_wall(ps);return JSONResponse({'post':post})
106
-
107
  @app.post('/api/topic/rewrite')
108
  async def _tr(request:Request):
109
  b=await request.json();pid=str(b.get('post_id','')).strip()
@@ -118,15 +103,8 @@ async def _tr(request:Request):
118
  if not best_img and uimg and len(uimg)>20:best_img=uimg
119
  ac='\n---\n'.join(parts) if parts else (p.get('text') or '')
120
  img=_ensure_img(best_img or p.get('img',''))
121
- prompt=f"""Viết lại tóm tắt mới. Dòng đầu là TIÊU ĐỀ MỚI hấp dẫn.
122
-
123
- Chủ đề: {p.get('title','')}
124
- Nguồn:
125
- {ac[:16000]}
126
-
127
- Dòng 1: Tiêu đề mới. Tiếp: 4-6 ý. Cuối: nguồn."""
128
  text=None
129
- try:text=await asyncio.wait_for(f5.base.qwen_generate(prompt,image_url=img,max_tokens=1200),timeout=35)
130
  except:pass
131
  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"
132
  ai_title=_extract_title(text);lines=text.strip().split('\n')
@@ -134,6 +112,16 @@ Dòng 1: Tiêu đề mới. Tiếp: 4-6 ý. Cuối: nguồn."""
134
  np=f5.base.make_post(ai_title,body_text,img,'','rewrite_topic',sources=p.get('sources',[]));np['images']=[img]
135
  all_p=f5.base._load_ai_wall();all_p.insert(0,np);f5.base._save_ai_wall(all_p);return JSONResponse({'post':np})
136
 
 
 
 
 
 
 
 
 
 
 
137
  HIGHLIGHT_FIX = r'''
138
  <style>
139
  .vp-wrap{aspect-ratio:1/1!important;width:100%!important;max-height:100vh!important;background:#000!important;position:relative!important}
@@ -145,10 +133,12 @@ HIGHLIGHT_FIX = r'''
145
  @app.get('/')
146
  async def _index_final():
147
  html=f5.f4.f3.f2.f1._load_index_html()
148
- body=getattr(rt.old,'PATCH_INJECT','')+f5.f4.f3.f2.f1.FINAL_INJECT+f5.f4.f3.FINAL3_INJECT+f5.f4.FINAL4_INJECT+f5.FINAL5_INJECT
 
 
149
  body+=getattr(f6,'FINAL6_INJECT','')
150
  body+=getattr(f6,'FINAL6_FAST_HOME_INJECT','')
151
- # NO FINAL6E_INJECT — it destroys slides
152
  body+=PATCH_INJECT
153
  body+=EXTRA_FIX
154
  body+=HIGHLIGHT_FIX
 
1
+ """Wrapper: kill old renderers FIRST, then inject everything."""
2
  from ai_runtime_patch_fast import *
3
  from ai_runtime_patch_fast import app, f5, f6, rt, PATCH_INJECT, _scrape, _domain, clean, _bg, _bg_home, _bg_shorts
4
  from patch_extra import EXTRA_FIX
 
8
 
9
  DEFAULT_IMG="https://s1.vnecdn.net/vnexpress/restruct/i/v9505/logo_default.jpg"
10
 
 
11
  app.router.routes=[r for r in app.router.routes if not (
12
  (getattr(r,'path',None)=='/api/homepage' and 'GET' in getattr(r,'methods',set())) or
13
  (getattr(r,'path',None)=='/api/shorts' and 'GET' in getattr(r,'methods',set())) or
 
18
  (getattr(r,'path',None)=='/' and 'GET' in getattr(r,'methods',set()))
19
  )]
20
 
 
21
  @app.get('/api/homepage')
22
  def _homepage_fast():
23
  if _bg_home['d']:
24
  if time.time()-_bg_home['t']>300:threading.Thread(target=_bg,daemon=True).start()
25
  return JSONResponse(_bg_home['d'])
 
26
  threading.Thread(target=_bg,daemon=True).start()
27
  return JSONResponse([])
28
 
 
34
  threading.Thread(target=_bg,daemon=True).start()
35
  return JSONResponse([])
36
 
 
37
  def _extract_title(text):
38
  if not text:return 'Bài viết AI'
39
  lines=[l.strip() for l in text.strip().split('\n') if l.strip()]
 
41
  first=re.sub(r'^[#*\-•\d\.\)\s]+','',lines[0]).strip()
42
  if 10<=len(first)<=120:return first
43
  return lines[0][:100] if lines else 'Bài viết AI'
 
44
  def _source_image(sources, details):
45
  for s in (details or []):
46
  if s.get('url'):
 
53
  except:img=''
54
  if img and 'pollinations' not in img and len(img)>20:return img
55
  return ''
 
56
  def _ensure_img(img):
57
  if img and len(img)>20 and img.startswith('http'):return img
58
  return DEFAULT_IMG
 
72
  if not text or len(text)<300: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')}))
73
  post=f5.base.make_post(topic,text,img,'','topic_focused',sources=[s for s in src if s.get('url')]);post['images']=[img];post['source_details']=det
74
  ps=f5.base._load_ai_wall();ps.insert(0,post);f5.base._save_ai_wall(ps);return JSONResponse({'post':post})
 
75
  @app.post('/api/rewrite_share')
76
  @app.post('/api/url_wall')
77
  async def _rw(request:Request):
 
81
  if len(raw)<50:raw=ctx[:14000]
82
  if len(raw)<50:return JSONResponse({'error':'Không đọc được bài'},status_code=422)
83
  img=_ensure_img(img)
 
 
 
 
 
 
 
84
  text=None
85
+ try:text=await asyncio.wait_for(f5.base.qwen_generate(f'Tóm tắt đăng Tường AI. Dòng 1: TIÊU ĐỀ MỚI.\n\nTiêu đề gốc: {title}\nNội dung:\n{raw[:14000]}\n\nDòng 1: Tiêu đề mới. Tiếp: 4-6 ý. Cuối: nguồn.',image_url=img,max_tokens=1000),timeout=30)
86
  except:pass
87
  if not text or len(text)<80:text=f"{title}\n\n{raw[:1200]}\n\nNguồn: {_domain(url)}"
88
  ai_title=_extract_title(text);lines=text.strip().split('\n')
89
  body_text='\n'.join(lines[1:]).strip() if lines and lines[0].strip()==ai_title else text
90
  post=f5.base.make_post(ai_title,body_text,img,url,'rewrite',sources=[{'title':title,'url':url,'via':_domain(url)}])
91
  ps=f5.base._load_ai_wall();ps.insert(0,post);f5.base._save_ai_wall(ps);return JSONResponse({'post':post})
 
92
  @app.post('/api/topic/rewrite')
93
  async def _tr(request:Request):
94
  b=await request.json();pid=str(b.get('post_id','')).strip()
 
103
  if not best_img and uimg and len(uimg)>20:best_img=uimg
104
  ac='\n---\n'.join(parts) if parts else (p.get('text') or '')
105
  img=_ensure_img(best_img or p.get('img',''))
 
 
 
 
 
 
 
106
  text=None
107
+ try:text=await asyncio.wait_for(f5.base.qwen_generate(f'Viết lại tóm tắt. Dòng 1: TIÊU ĐỀ MỚI.\n\nChủ đề: {p.get("title","")}\nNguồn:\n{ac[:16000]}\n\nDòng 1: Tiêu đề mới. Tiếp: 4-6 ý. Cuối: nguồn.',image_url=img,max_tokens=1200),timeout=35)
108
  except:pass
109
  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"
110
  ai_title=_extract_title(text);lines=text.strip().split('\n')
 
112
  np=f5.base.make_post(ai_title,body_text,img,'','rewrite_topic',sources=p.get('sources',[]));np['images']=[img]
113
  all_p=f5.base._load_ai_wall();all_p.insert(0,np);f5.base._save_ai_wall(all_p);return JSONResponse({'post':np})
114
 
115
+ # === CRITICAL: Script that runs BEFORE all old injects to prevent slide destruction ===
116
+ PRE_KILL_SCRIPT = r'''
117
+ <script>
118
+ // PRE-KILL: Override destructive functions BEFORE old inject code defines and calls them
119
+ Object.defineProperty(window,'renderTopicWallE',{get:function(){return function(){}},set:function(){},configurable:true});
120
+ Object.defineProperty(window,'renderAIShortHome',{get:function(){return function(){}},set:function(){},configurable:true});
121
+ Object.defineProperty(window,'renderAIShorts7',{get:function(){return function(){}},set:function(){},configurable:true});
122
+ </script>
123
+ '''
124
+
125
  HIGHLIGHT_FIX = r'''
126
  <style>
127
  .vp-wrap{aspect-ratio:1/1!important;width:100%!important;max-height:100vh!important;background:#000!important;position:relative!important}
 
133
  @app.get('/')
134
  async def _index_final():
135
  html=f5.f4.f3.f2.f1._load_index_html()
136
+ # PRE-KILL goes FIRST before any old inject can run
137
+ body=PRE_KILL_SCRIPT
138
+ body+=getattr(rt.old,'PATCH_INJECT','')+f5.f4.f3.f2.f1.FINAL_INJECT+f5.f4.f3.FINAL3_INJECT+f5.f4.FINAL4_INJECT+f5.FINAL5_INJECT
139
  body+=getattr(f6,'FINAL6_INJECT','')
140
  body+=getattr(f6,'FINAL6_FAST_HOME_INJECT','')
141
+ # NO FINAL6E_INJECT
142
  body+=PATCH_INJECT
143
  body+=EXTRA_FIX
144
  body+=HIGHLIGHT_FIX