bep40 commited on
Commit
c680c2b
·
verified ·
1 Parent(s): 38fa5da

Upload app_run.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app_run.py +221 -0
app_run.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Wrapper: hashtag via Google News with pagination, strict relevance, load more."""
2
+ from app_final import *
3
+ from app_final import app, f6, f5, rt, PATCH_INJECT, UNIFIED_INJECT_FIXED, HIGHLIGHT_FULL_OVERRIDE, EXTRA_WALL_FIX
4
+ from fastapi.responses import HTMLResponse, JSONResponse
5
+ from fastapi import Query, Request
6
+ import requests as req
7
+ from urllib.parse import quote
8
+ from bs4 import BeautifulSoup
9
+ import re, html as html_lib
10
+
11
+ def _clean(s):return re.sub(r"\s+"," ",html_lib.unescape(str(s or ""))).strip()
12
+
13
+ def _follow_redirect(url):
14
+ try:
15
+ r=req.head(url,allow_redirects=True,timeout=10,headers={'User-Agent':'Mozilla/5.0'})
16
+ return r.url
17
+ except:
18
+ try:r=req.get(url,allow_redirects=True,timeout=10,headers={'User-Agent':'Mozilla/5.0'},stream=True);u=r.url;r.close();return u
19
+ except:return url
20
+
21
+ def _scrape_any_article(url):
22
+ if 'news.google.com' in url or 'google.com/rss' in url:url=_follow_redirect(url)
23
+ try:
24
+ r=req.get(url,headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36','Accept-Language':'vi-VN,vi;q=0.9,en;q=0.8'},timeout=15,allow_redirects=True)
25
+ r.encoding='utf-8';soup=BeautifulSoup(r.text,'lxml')
26
+ for tag in soup.find_all(['script','style','nav','footer','aside','form','noscript','iframe']):tag.decompose()
27
+ h1=soup.find('h1');ogt=soup.find('meta',property='og:title')
28
+ title=(h1.get_text(' ',strip=True) if h1 else '') or (ogt.get('content','') if ogt else '') or (soup.title.get_text(strip=True) if soup.title else '')
29
+ ogd=soup.find('meta',property='og:description') or soup.find('meta',attrs={'name':'description'})
30
+ summary=ogd.get('content','') if ogd else ''
31
+ ogi=soup.find('meta',property='og:image') or soup.find('meta',attrs={'name':'twitter:image'})
32
+ og_image=ogi.get('content','') if ogi else ''
33
+ if og_image and og_image.startswith('//'):og_image='https:'+og_image
34
+ selectors=['article','main','.article-content','.detail-content','.singular-content','.fck_detail','.content-detail','.entry-content','.story-body','.knc-content','.cms-body']
35
+ block=None
36
+ for sel in selectors:
37
+ el=soup.select_one(sel)
38
+ if el and len(el.find_all('p'))>=2:block=el;break
39
+ if not block:
40
+ best=None;best_score=0
41
+ for el in soup.find_all(['article','main','section','div']):
42
+ ps=el.find_all('p');score=len(ps)*100+sum(len(p.get_text())for p in ps[:10])
43
+ if score>best_score:best=el;best_score=score
44
+ block=best or soup.body or soup
45
+ body=[]
46
+ for el in block.find_all(['p','h2','h3','figure','img'],recursive=True):
47
+ if el.name=='p':
48
+ t=_clean(el.get_text(' ',strip=True))
49
+ if len(t)>30:body.append({'type':'p','text':t})
50
+ elif el.name in ('h2','h3'):
51
+ t=_clean(el.get_text(' ',strip=True))
52
+ if t:body.append({'type':'heading','text':t})
53
+ elif el.name in ('figure','img'):
54
+ im=el if el.name=='img' else el.find('img')
55
+ if im:
56
+ src=im.get('data-src') or im.get('data-original') or im.get('src') or ''
57
+ if src and 'base64' not in src:
58
+ if src.startswith('//'):src='https:'+src
59
+ body.append({'type':'img','src':src})
60
+ if not body and summary:body=[{'type':'p','text':summary}]
61
+ return {'title':_clean(title),'summary':_clean(summary),'og_image':og_image,'body':body[:50],'source':'generic','url':url}
62
+ except:return None
63
+
64
+ def _google_news_search_all(topic, limit=30):
65
+ """Get ALL results from Google News RSS for a topic — no filtering here, filter in endpoint."""
66
+ items=[]
67
+ try:
68
+ url='https://news.google.com/rss/search?q='+quote(topic)+'&hl=vi&gl=VN&ceid=VN:vi'
69
+ r=req.get(url,headers={'User-Agent':'Mozilla/5.0'},timeout=10);r.encoding='utf-8'
70
+ soup=BeautifulSoup(r.text,'xml')
71
+ for it in soup.find_all('item')[:limit]:
72
+ title=_clean(it.find('title').get_text(' ',strip=True) if it.find('title') else '')
73
+ link=_clean(it.find('link').get_text(strip=True) if it.find('link') else '')
74
+ src=_clean(it.find('source').get_text(' ',strip=True) if it.find('source') else '')
75
+ pub=_clean(it.find('pubDate').get_text(strip=True) if it.find('pubDate') else '')
76
+ if not title or not link:continue
77
+ items.append({'title':title,'url':link,'via':src,'snippet':'','pubDate':pub})
78
+ except:pass
79
+ return items
80
+
81
+ def _filter_relevant(items, topic):
82
+ """Strict filter: topic keywords MUST appear in title."""
83
+ topic_lower=topic.lower()
84
+ topic_words=[w for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',topic_lower) if len(w)>2]
85
+ filtered=[]
86
+ for s in items:
87
+ title_lower=s.get('title','').lower()
88
+ # Whole phrase match OR majority of words match
89
+ if topic_lower in title_lower:
90
+ filtered.append(s);continue
91
+ if topic_words:
92
+ match=sum(1 for w in topic_words if w in title_lower)
93
+ if match>=len(topic_words)*0.6:
94
+ filtered.append(s)
95
+ return filtered
96
+
97
+ # Override endpoints
98
+ app.router.routes=[r for r in app.router.routes if not (
99
+ (getattr(r,'path',None)=='/api/hashtag/sources' and 'GET' in getattr(r,'methods',set())) or
100
+ (getattr(r,'path',None)=='/api/article' and 'GET' in getattr(r,'methods',set())) or
101
+ (getattr(r,'path',None)=='/' and 'GET' in getattr(r,'methods',set()))
102
+ )]
103
+
104
+ @app.get('/api/article')
105
+ def _article_universal(url:str=Query(...)):
106
+ data=_scrape_any_article(url)
107
+ if data and data.get('body'):return JSONResponse(data)
108
+ from main import scrape_vne_article,scrape_bbc_article,scrape_dantri_article,scrape_genk_article,scrape_ttvh_article
109
+ if 'vnexpress.net' in url:d=scrape_vne_article(url)
110
+ elif 'bbc.com' in url:d=scrape_bbc_article(url)
111
+ elif 'dantri.com.vn' in url:d=scrape_dantri_article(url)
112
+ elif 'genk.vn' in url:d=scrape_genk_article(url)
113
+ elif 'thethaovanhoa.vn' in url:d=scrape_ttvh_article(url)
114
+ else:d=None
115
+ if d and d.get('body'):return JSONResponse(d)
116
+ return JSONResponse({'error':'Không đọc được bài viết','url':url})
117
+
118
+ @app.get('/api/hashtag/sources')
119
+ def _hashtag_paged(topic:str=Query(...),page:int=Query(default=0)):
120
+ """Google News search with pagination. page=0 returns first 6, page=1 returns next 6, etc."""
121
+ all_items=_google_news_search_all(topic,30)
122
+ filtered=_filter_relevant(all_items,topic)
123
+ # If strict filter too harsh, fallback to all
124
+ if len(filtered)<3:filtered=all_items
125
+ per_page=6;start=page*per_page;end=start+per_page
126
+ page_items=filtered[start:end]
127
+ has_more=end<len(filtered)
128
+ return JSONResponse({'sources':page_items,'topic':topic,'page':page,'has_more':has_more,'total':len(filtered)})
129
+
130
+ FAST_HASHTAG_JS = r'''
131
+ <style>
132
+ .hashtag-loading{display:flex;align-items:center;gap:8px;padding:12px;color:#888;font-size:12px}
133
+ .hashtag-spinner{width:16px;height:16px;border:2px solid #333;border-top-color:#5cb87a;border-radius:50%;animation:ht-spin .8s linear infinite}
134
+ @keyframes ht-spin{to{transform:rotate(360deg)}}
135
+ .hashtag-load-more{width:100%;margin-top:8px;background:#222;border:1px solid #333;color:#ccc;padding:9px;border-radius:10px;font-size:12px;cursor:pointer}.hashtag-load-more:active{opacity:.7}
136
+ </style>
137
+ <script>
138
+ (function(){
139
+ function esc(s){return String(s||'').replace(/[&<>"']/g,function(m){return{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]});}
140
+ var _htPage=0,_htTopic='',_htImgIdx=0;
141
+
142
+ window.readArticle=async function(url){
143
+ showView('view-article');var el=document.getElementById('view-article');el.innerHTML='<div class="loading">Đang tải...</div>';
144
+ try{var r=await fetch('/api/article?url='+encodeURIComponent(url));var data=await r.json();
145
+ if(data&&!data.error&&data.body&&data.body.length){window._currentArticle={url:url,data:data};var h='<button class="back-btn" onclick="switchCat(\'home\')">← Quay lại</button><div class="article-view"><h1 class="article-title">'+esc(data.title)+'</h1>';if(data.summary)h+='<div class="article-summary">'+esc(data.summary)+'</div>';var seen={};data.body.forEach(function(b){if(b.type==='p')h+='<p class="article-p">'+b.text+'</p>';else if(b.type==='img'&&b.src&&!seen[b.src]){seen[b.src]=1;h+='<img class="article-img" src="'+esc(b.src)+'" onerror="this.style.display=\'none\'">';}else if(b.type==='heading')h+='<h2 class="article-h2">'+esc(b.text)+'</h2>';});h+='<div class="article-actions"><button class="primary" onclick="doRewriteArticle(this)">🤖 Rewrite AI đăng tường</button><button onclick="doShare(\''+esc(data.title)+'\',\''+esc(url)+'\',\''+esc(data.og_image||'')+'\')">📤</button><button onclick="window.open(\''+esc(url)+'\',\'_blank\')">🔗 Gốc</button></div><div class="article-ai-ask"><h3 style="font-size:14px;color:#5cb87a">🤖 Hỏi AI</h3><textarea id="article-ai-question" placeholder="Hỏi..."></textarea><button onclick="askArticleAI()">Hỏi</button><div id="article-ai-answer" class="article-ai-answer"></div></div></div>';el.innerHTML=h;window.scrollTo(0,0);return;}}catch(e){}
146
+ el.innerHTML='<button class="back-btn" onclick="switchCat(\'home\')">← Quay lại</button><div class="loading"><p>Không đọc được.</p><a href="'+esc(url)+'" target="_blank" style="color:#5cb87a">Mở gốc →</a></div>';
147
+ };
148
+ window.doRewriteArticle=async function(btn){var url=(window._currentArticle&&window._currentArticle.url)||'';if(!url){alert('Không có URL');return;}var ctx=document.querySelector('.article-view')?.innerText?.slice(0,14000)||'';btn.disabled=true;btn.textContent='Đang rewrite...';try{var r=await fetch('/api/rewrite_share',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url:url,context:ctx})});var j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');alert('Đã đăng Tường AI!');}catch(e){alert(e.message);}finally{btn.disabled=false;btn.textContent='🤖 Rewrite AI đăng tường';}};
149
+ window.askArticleAI=async function(){var q=document.getElementById('article-ai-question')?.value.trim();if(!q)return alert('Nhập câu hỏi');var a=document.getElementById('article-ai-answer');a.textContent='Đang hỏi...';var url=(window._currentArticle&&window._currentArticle.url)||'';var ctx=document.querySelector('.article-view')?.innerText?.slice(0,12000)||'';try{var r=await fetch('/api/article/ask',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url:url,question:q,context:ctx})});var j=await r.json();a.textContent=j.answer||'Không trả lời được';}catch(e){a.textContent='Lỗi: '+e.message}};
150
+
151
+ function renderSources(sources,append){
152
+ var list=document.getElementById('hashtag-src-list');if(!list)return;
153
+ var h='';
154
+ sources.forEach(function(s){
155
+ var idx=_htImgIdx++;
156
+ h+='<div class="hashtag-src-item" onclick="readArticle(\''+esc(s.url||'')+'\')">';
157
+ h+='<div class="hashtag-src-img" id="ht-img-'+idx+'"></div>';
158
+ h+='<div class="hashtag-src-text"><div class="hashtag-src-title">'+esc(s.title)+'</div><div class="hashtag-src-via">'+esc(s.via||'')+(s.pubDate?' · '+esc(s.pubDate.split(',')[0]||''):'')+'</div></div>';
159
+ h+='</div>';
160
+ // Lazy load image
161
+ setTimeout(function(){fetch('/api/article?url='+encodeURIComponent(s.url)).then(function(r){return r.json()}).then(function(d){if(d&&(d.og_image||d.img)){var el=document.getElementById('ht-img-'+idx);if(el)el.innerHTML='<img src="'+esc(d.og_image||d.img)+'" onerror="this.style.display=\'none\'" loading="lazy">';}}).catch(function(){});},idx*500);
162
+ });
163
+ if(append)list.insertAdjacentHTML('beforeend',h);else list.innerHTML=h;
164
+ }
165
+
166
+ window.showHashtagSources=async function(topic){
167
+ _htTopic=topic;_htPage=0;_htImgIdx=0;
168
+ var home=document.getElementById('view-home');if(!home)return;
169
+ document.getElementById('hashtag-sources-box')?.remove();
170
+ var box=document.createElement('div');box.id='hashtag-sources-box';box.className='hashtag-sources';
171
+ box.innerHTML='<h3>🔍 '+esc(topic)+'</h3><div class="hashtag-loading"><div class="hashtag-spinner"></div>Đang tìm bài viết mới nhất...</div>';
172
+ var compose=home.querySelector('.ai-compose');
173
+ if(compose)compose.after(box);else home.prepend(box);
174
+ box.scrollIntoView({behavior:'smooth',block:'start'});
175
+ try{
176
+ var r=await fetch('/api/hashtag/sources?topic='+encodeURIComponent(topic)+'&page=0');
177
+ var j=await r.json();var sources=j.sources||[];
178
+ if(!sources.length){box.innerHTML='<h3>🔍 '+esc(topic)+'</h3><div style="color:#888;font-size:12px;padding:8px">Không tìm được bài viết liên quan</div>';return;}
179
+ var h='<h3>🔍 '+esc(topic)+' <span style="font-size:10px;color:#888">('+j.total+' bài mới nhất từ Google News)</span></h3>';
180
+ h+='<div id="hashtag-src-list"></div>';
181
+ h+='<button class="hashtag-rewrite-btn" onclick="rewriteHashtagTopic(\''+esc(topic)+'\')">🤖 Rewrite AI tổng hợp & đăng tường</button>';
182
+ if(j.has_more)h+='<button class="hashtag-load-more" id="ht-load-more" onclick="loadMoreSources()">Tải thêm bài viết ▼</button>';
183
+ box.innerHTML=h;
184
+ renderSources(sources,false);
185
+ }catch(e){box.innerHTML='<h3>🔍 '+esc(topic)+'</h3><div style="color:#e74c3c;font-size:12px;padding:8px">Lỗi: '+esc(e.message)+'</div>';}
186
+ };
187
+
188
+ window.loadMoreSources=async function(){
189
+ _htPage++;var btn=document.getElementById('ht-load-more');
190
+ if(btn){btn.textContent='Đang tải...';btn.disabled=true;}
191
+ try{
192
+ var r=await fetch('/api/hashtag/sources?topic='+encodeURIComponent(_htTopic)+'&page='+_htPage);
193
+ var j=await r.json();var sources=j.sources||[];
194
+ renderSources(sources,true);
195
+ if(!j.has_more&&btn)btn.remove();
196
+ else if(btn){btn.textContent='Tải thêm bài viết ▼';btn.disabled=false;}
197
+ }catch(e){if(btn){btn.textContent='Lỗi, thử lại';btn.disabled=false;}}
198
+ };
199
+
200
+ window.rewriteHashtagTopic=async function(topic){var btn=event?.target;if(btn){btn.disabled=true;btn.textContent='Đang tổng hợp...';}try{var r=await fetch('/api/topic_post',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({topic:topic})});var j=await r.json();if(!r.ok||j.error)throw new Error(j.error||'Lỗi');if(btn)btn.textContent='✅ Đã đăng!';setTimeout(function(){document.getElementById('hashtag-sources-box')?.remove();},2000);}catch(e){if(btn){btn.disabled=false;btn.textContent='❌ '+e.message;}}};
201
+ window.createTopicPost=function(){var inp=document.getElementById('ai-topic-input');var topic=(inp&&inp.value||'').trim();if(!topic){alert('Nhập chủ đề');return;}showHashtagSources(topic);if(inp)inp.value='';};
202
+ window.createTopicPostFinal5=function(){var inp=document.getElementById('ai-topic-input-final5')||document.getElementById('ai-topic-input');var topic=(inp&&inp.value||'').trim();if(!topic){alert('Nhập chủ đề');return;}showHashtagSources(topic);if(inp)inp.value='';};
203
+ })();
204
+ </script>
205
+ '''
206
+
207
+ @app.get('/')
208
+ async def _index_run():
209
+ html=f5.f4.f3.f2.f1._load_index_html()
210
+ body=''
211
+ body+=getattr(rt.old,'PATCH_INJECT','')
212
+ body+=f5.f4.f3.f2.f1.FINAL_INJECT+f5.f4.f3.FINAL3_INJECT+f5.f4.FINAL4_INJECT+f5.FINAL5_INJECT
213
+ body+=getattr(f6,'FINAL6_INJECT','')
214
+ body+=getattr(f6,'FINAL6_FAST_HOME_INJECT','')
215
+ body+=getattr(f6,'FINAL6E_INJECT','')
216
+ body+=PATCH_INJECT
217
+ body+=UNIFIED_INJECT_FIXED
218
+ body+=HIGHLIGHT_FULL_OVERRIDE
219
+ body+=EXTRA_WALL_FIX
220
+ body+=FAST_HASHTAG_JS
221
+ return HTMLResponse(html.replace('</body>',body+'\n</body>') if '</body>' in html else html+body)