bep40 commited on
Commit
b05f45b
·
verified ·
1 Parent(s): d29e138

Fix: Restore correct app_v2_entry.py with og:image from slides, og:description from text, URL-based canonical

Browse files
Files changed (1) hide show
  1. app_v2_entry.py +1 -1820
app_v2_entry.py CHANGED
@@ -636,1826 +636,7 @@ async def _sh_slug(slug: str, request: Request, url: str = '', title: str = '',
636
  </head><body></body></html>''')
637
 
638
  @app.get('/s')
639
- async """VNEWS v2 Entry Point - with fast bongda proxy + rewrite endpoints + multilingual TTS"""
640
- import sys, os
641
- from main import app, HEADERS, BONGDA_HEADERS, fetch_bongda_api, HL_LEAGUES
642
-
643
- try:
644
- import ai_ext
645
- except Exception as e:
646
- print(f"[WARN] ai_ext import failed: {e}")
647
-
648
- try:
649
- import ai_patch
650
- except Exception as e:
651
- print(f"[WARN] ai_patch import failed: {e}")
652
-
653
- from fastapi.responses import HTMLResponse, JSONResponse, FileResponse, Response
654
- from fastapi.staticfiles import StaticFiles
655
- from starlette.routing import Mount
656
- from fastapi import Query, Request, UploadFile, File, Form
657
- import requests as req
658
- from bs4 import BeautifulSoup
659
- import re, html as html_lib, json, threading, time, uuid
660
- from concurrent.futures import ThreadPoolExecutor, as_completed
661
- from urllib.parse import quote
662
- import asyncio
663
-
664
- HL_LEAGUES['friendly'] = {"path": "giai-khac/friendly", "name": "Giao hữu", "emoji": "🤝"}
665
-
666
- STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')
667
- SPACE = "https://bep40-vnews.hf.space" # SEO URL base for share links
668
- app.router.routes=[r for r in app.router.routes if not(getattr(r,'path',None)=='/' and hasattr(r,'methods') and 'GET' in getattr(r,'methods',set()))]
669
- app.routes[:]=[r for r in app.routes if not isinstance(r, Mount)]
670
- app.router.routes=[r for r in app.router.routes if not isinstance(r, Mount)]
671
-
672
- def _clean(s): return re.sub(r"\s+"," ",html_lib.unescape(str(s or""))).strip()
673
-
674
- # Cache for match details (5 min TTL)
675
- _match_cache = {}
676
-
677
- # === FAST BONGDA PROXY ENDPOINT ===
678
- def _get_match_detail(event_id, slug=None):
679
- headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "Accept": "text/html", "Referer": "https://bongda.com.vn/"}
680
- if slug:
681
- url = f"https://bongda.com.vn/tran-dau/{event_id}/centre/{slug}"
682
- else:
683
- url = f"https://bongda.com.vn/tran-dau/{event_id}"
684
- resp = req.get(url, headers=headers, timeout=15, allow_redirects=True)
685
- if resp.status_code != 200:
686
- return None
687
- soup = BeautifulSoup(resp.text, 'html.parser')
688
- result = {"event_id": event_id, "found": False, "sections": []}
689
- info = {}
690
- tel = soup.select_one('.teams')
691
- if tel:
692
- he = tel.select_one('.team.home')
693
- if he:
694
- p_tags = [p for p in he.select('p') if not p.get('class') or 'logo' not in p.get('class', [])]
695
- if p_tags: info['home_team'] = _clean(p_tags[0].get_text())
696
- lo = he.select_one('img')
697
- if lo: info['home_logo'] = lo.get('src', '')
698
- ae = tel.select_one('.team.away')
699
- if ae:
700
- p_tags = ae.select('p')
701
- team_ps = [p for p in p_tags if not p.get('class') or 'logo' not in p.get('class', [])]
702
- if team_ps: info['away_team'] = _clean(team_ps[-1].get_text())
703
- lo = ae.select_one('img')
704
- if lo: info['away_logo'] = lo.get('src', '')
705
- sc = tel.select_one('.score')
706
- if sc:
707
- parts = [_clean(p.get_text()) for p in sc.select('p')]
708
- if len(parts) >= 2: info['score'] = f"{parts[0]} - {parts[1]}"
709
- lb = sc.select_one('.label')
710
- if lb: info['status_label'] = _clean(lb.get_text())
711
- if info.get('home_team') and info.get('away_team'):
712
- result['info'] = info
713
- result['found'] = True
714
- result['sections'].append('info')
715
- events = []
716
- for ev in soup.select('.events .period .event'):
717
- ev_cls = ' '.join(ev.get('class', []))
718
- ev_data = {'team': 'home' if 'home' in ev_cls else 'away', 'period': '', 'type': 'unknown', 'time': '', 'players': ''}
719
- parent = ev.parent
720
- if parent:
721
- h2 = parent.find('h2')
722
- if h2: ev_data['period'] = _clean(h2.get_text())
723
- if ev.select_one('[class*="goal"]'): ev_data['type'] = 'goal'
724
- elif ev.select_one('[class*="redcard"]'): ev_data['type'] = 'redcard'
725
- elif ev.select_one('[class*="yellowcard"]'): ev_data['type'] = 'yellowcard'
726
- elif ev.select_one('[class*="substitution"]'): ev_data['type'] = 'substitution'
727
- players_el = ev.select_one('.players')
728
- if players_el:
729
- pl_text = _clean(players_el.get_text(' ', strip=True))
730
- m = re.match(r"(\d+)'(.*)", pl_text)
731
- if m:
732
- ev_data['time'] = f"{m.group(1)}'"
733
- ev_data['players'] = m.group(2)
734
- else:
735
- ev_data['players'] = pl_text
736
- events.append(ev_data)
737
- if events:
738
- result['events'] = events
739
- result['sections'].append('events')
740
- pred = soup.select_one('.prediction-card')
741
- if pred:
742
- team_info = pred.select_one('.team-info')
743
- if team_info:
744
- teams = team_info.select('.team')
745
- pred_data = {}
746
- if len(teams) >= 2:
747
- pred_data['home_name'] = _clean(teams[0].select_one('.team-name').get_text()) if teams[0].select_one('.team-name') else ''
748
- pred_data['away_name'] = _clean(teams[1].select_one('.team-name').get_text()) if teams[1].select_one('.team-name') else ''
749
- divider = team_info.select_one('.divider')
750
- if divider: pred_data['result'] = _clean(divider.get_text())
751
- vc = pred.select_one('.vote-count')
752
- if vc: pred_data['vote_count'] = _clean(vc.get_text())
753
- result['prediction'] = pred_data
754
- recent = []
755
- ml = soup.select_one('.matches-list')
756
- if ml:
757
- for item in ml.select('.match-detail, .match-item, li'):
758
- de = item.select_one('.date, .time')
759
- le = item.select_one('.league')
760
- he_item = item.select_one('.home, .team-home')
761
- ae_item = item.select_one('.away, .team-away')
762
- se = item.select_one('.score, .result')
763
- if he_item or ae_item:
764
- recent.append({'date': _clean(de.get_text()) if de else '', 'league': _clean(le.get_text()) if le else '', 'home': _clean(he_item.get_text()) if he_item else '', 'away': _clean(ae_item.get_text()) if ae_item else '', 'score': _clean(se.get_text()) if se else 'vs'})
765
- if recent:
766
- result['recent_matches'] = recent
767
- result['sections'].append('recent')
768
- try:
769
- api_h = {"User-Agent": "Mozilla/5.0", "Accept": "application/json", "X-Requested-With": "XMLHttpRequest", "Referer": "https://bongda.com.vn/"}
770
- ar = req.get(f"https://bongda.com.vn/api/fixtures/h2h-stats?event_id={event_id}", headers=api_h, timeout=10)
771
- if ar.status_code == 200:
772
- ad = ar.json()
773
- if ad.get('status') == 'success' and ad.get('html'):
774
- asp = BeautifulSoup(ad['html'], 'html.parser')
775
- ast = {}
776
- for row in asp.select('li, tr'):
777
- cells = row.select('td, span, p')
778
- if len(cells) >= 3:
779
- lb = _clean(cells[0].get_text())
780
- if lb: ast[lb] = {'home': _clean(cells[1].get_text()), 'away': _clean(cells[2].get_text())}
781
- if ast:
782
- result['h2h_stats_parsed'] = ast
783
- result['sections'].append('h2h_stats')
784
- except: pass
785
- return result
786
-
787
- @app.get('/api/proxy/bongda')
788
- def proxy_bongda(event_id: int = Query(default=None), slug: str = Query(default=None)):
789
- if event_id is None:
790
- return JSONResponse({'error': 'event_id required'}, status_code=400)
791
- cache_key = f"{event_id}_{slug}"
792
- now = time.time()
793
- cached = _match_cache.get(cache_key)
794
- if cached and now - cached.get('_ts', 0) < 300:
795
- return JSONResponse(cached)
796
- try:
797
- result = _get_match_detail(event_id, slug)
798
- if result:
799
- result['_ts'] = now
800
- _match_cache[cache_key] = result
801
- return JSONResponse(result)
802
- except Exception as e:
803
- err = {"event_id": event_id, "found": False, "error": str(e), "_ts": now}
804
- _match_cache[cache_key] = err
805
- return JSONResponse(err)
806
- return JSONResponse({"event_id": event_id, "found": False})
807
-
808
- @app.get('/api/match/{event_id}/detail')
809
- def api_match_detail(event_id: int, url: str = Query(default=None)):
810
- slug = None
811
- if url:
812
- m = re.match(r'.+/tran-dau/\d+/(?:centre|preview)/(.+)', url)
813
- if m:
814
- slug = m.group(1)
815
- cache_key = f"{event_id}_{slug or ''}"
816
- now = time.time()
817
- cached = _match_cache.get(cache_key)
818
- if cached and now - cached.get('_ts', 0) < 300:
819
- return JSONResponse(cached)
820
- try:
821
- if not slug:
822
- try:
823
- home_r = req.get("https://bongda.com.vn/", headers={"User-Agent": "Mozilla/5.0"}, timeout=10)
824
- if home_r.status_code == 200:
825
- home_soup = BeautifulSoup(home_r.text, 'html.parser')
826
- for a in home_soup.select(f'a[href*="/tran-dau/{event_id}/"]'):
827
- href = a.get('href', '')
828
- m = re.match(r'/tran-dau/\d+/(?:centre|preview)/(.+)', href)
829
- if m:
830
- slug = m.group(1)
831
- cache_key = f"{event_id}_{slug}"
832
- break
833
- except: pass
834
- result = _get_match_detail(event_id, slug)
835
- if result:
836
- result['_ts'] = now
837
- _match_cache[cache_key] = result
838
- return JSONResponse(result)
839
- except Exception as e:
840
- err = {"event_id": event_id, "found": False, "error": str(e), "_ts": now}
841
- _match_cache[cache_key] = err
842
- return JSONResponse(err)
843
- return JSONResponse({"event_id": event_id, "found": False})
844
-
845
- _STOP=set('và của các những một được trong với cho tại sau trước khi không người việt nam hôm nay mới nhất nóng tin tức cập nhật theo từ đến là có thì này đã để'.split())
846
-
847
- def _has_kw(topic,title):
848
- tl=topic.lower();tt=(title or'').lower()
849
- if tl in tt:return True
850
- words=[w for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',tl) if len(w)>2 and w not in _STOP]
851
- if not words:return True
852
- return any(w in tt for w in words)
853
-
854
- def _s_vnexpress(topic,limit=8):
855
- items=[]
856
- try:
857
- r=req.get(f"https://timkiem.vnexpress.net/?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml')
858
- for art in soup.select('article.item-news')[:limit]:
859
- a=art.select_one('h2 a, h3 a')
860
- if a and a.get('href'):
861
- t=_clean(a.get('title','') or a.get_text(strip=True))
862
- if _has_kw(topic,t):items.append({'title':t,'url':a['href'],'via':'VnExpress'})
863
- except:pass
864
- return items
865
-
866
- def _s_dantri(topic,limit=8):
867
- items=[]
868
- try:
869
- r=req.get(f"https://dantri.com.vn/tim-kiem/{quote(topic)}.htm",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml')
870
- for a in soup.select('h3 a[href], .article-title a[href]')[:limit*2]:
871
- t=_clean(a.get_text(strip=True));href=a.get('href','')
872
- if t and len(t)>15 and _has_kw(topic,t):
873
- if not href.startswith('http'):href='https://dantri.com.vn'+href
874
- items.append({'title':t,'url':href,'via':'Dân Trí'})
875
- if len(items)>=limit:break
876
- except:pass
877
- return items
878
-
879
- def _s_vietnamnet(topic,limit=6):
880
- items=[]
881
- try:
882
- r=req.get(f"https://vietnamnet.vn/tim-kiem?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml')
883
- for a in soup.select('h3 a[href], .vnn-title a')[:limit*2]:
884
- t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','')
885
- if t and len(t)>15 and _has_kw(topic,t):
886
- if not href.startswith('http'):href='https://vietnamnet.vn'+href
887
- items.append({'title':t,'url':href,'via':'VietNamNet'})
888
- if len(items)>=limit:break
889
- except:pass
890
- return items
891
-
892
- def _s_bongda(topic,limit=5):
893
- items=[]
894
- try:
895
- r=req.get(f"https://bongda.com.vn/tim-kiem.html?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=8);soup=BeautifulSoup(r.text,'lxml')
896
- for a in soup.select('h3 a[href], .title a[href]')[:limit*2]:
897
- t=_clean(a.get_text(strip=True));href=a.get('href','')
898
- if t and len(t)>15 and _has_kw(topic,t):
899
- if not href.startswith('http'):href='https://bongda.com.vn'+href
900
- items.append({'title':t,'url':href,'via':'Bóng Đá'})
901
- if len(items)>=limit:break
902
- except:pass
903
- return items
904
-
905
- def _s_genk(topic,limit=5):
906
- items=[]
907
- try:
908
- r=req.get(f"https://genk.vn/tim-kiem?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=8);soup=BeautifulSoup(r.text,'lxml')
909
- for a in soup.select('a[href$=".chn"]')[:limit*3]:
910
- t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','')
911
- if t and len(t)>15 and _has_kw(topic,t):
912
- if href.startswith('/'):href='https://genk.vn'+href
913
- items.append({'title':t,'url':href,'via':'GenK'})
914
- if len(items)>=limit:break
915
- except:pass
916
- return items
917
-
918
- def _s_thanhnien(topic,limit=6):
919
- items=[]
920
- try:
921
- r=req.get(f"https://thanhnien.vn/tim-kiem?q={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml')
922
- for a in soup.select('h3 a[href], .box-title a')[:limit*2]:
923
- t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','')
924
- if t and len(t)>15 and _has_kw(topic,t):
925
- if not href.startswith('http'):href='https://thanhnien.vn'+href
926
- items.append({'title':t,'url':href,'via':'Thanh Niên'})
927
- if len(items)>=limit:break
928
- except:pass
929
- return items
930
-
931
- def _s_tuoitre(topic,limit=6):
932
- items=[]
933
- try:
934
- r=req.get(f"https://tuoitre.vn/tim-kiem.htm?keywords={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=10);soup=BeautifulSoup(r.text,'lxml')
935
- for a in soup.select('h3 a[href], .box-title-text a')[:limit*2]:
936
- t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','')
937
- if t and len(t)>15 and _has_kw(topic,t):
938
- if not href.startswith('http'):href='https://tuoitre.vn'+href
939
- items.append({'title':t,'url':href,'via':'Tuổi Trẻ'})
940
- if len(items)>=limit:break
941
- except:pass
942
- return items
943
-
944
- def _s_thethaovanhoa(topic,limit=5):
945
- items=[]
946
- try:
947
- r=req.get(f"https://thethaovanhoa.vn/tim-kiem.htm?keyword={quote(topic)}",headers={'User-Agent':'Mozilla/5.0'},timeout=8);soup=BeautifulSoup(r.text,'lxml')
948
- for a in soup.select('h3 a[href], .title a[href]')[:limit*2]:
949
- t=_clean(a.get('title','') or a.get_text(strip=True));href=a.get('href','')
950
- if t and len(t)>15 and _has_kw(topic,t):
951
- if not href.startswith('http'):href='https://thethaovanhoa.vn'+href
952
- items.append({'title':t,'url':href,'via':'TT&VH'})
953
- if len(items)>=limit:break
954
- except:pass
955
- return items
956
-
957
- def _search_all(topic,limit=36):
958
- results={}
959
- with ThreadPoolExecutor(8) as ex:
960
- futs={ex.submit(_s_vnexpress,topic,8):'vne',ex.submit(_s_dantri,topic,8):'dt',ex.submit(_s_vietnamnet,topic,6):'vnn',ex.submit(_s_bongda,topic,5):'bd',ex.submit(_s_genk,topic,5):'gk',ex.submit(_s_thanhnien,topic,6):'tn',ex.submit(_s_tuoitre,topic,6):'tt',ex.submit(_s_thethaovanhoa,topic,5):'tvh'}
961
- for f in as_completed(futs,timeout=14):
962
- try:results[futs[f]]=f.result()
963
- except:results[futs[f]]=[]
964
- srcs=list(results.values());out=[];seen=set()
965
- for i in range(max((len(s) for s in srcs),default=0)):
966
- for s in srcs:
967
- if i<len(s) and s[i].get('url') and s[i]['url'] not in seen:seen.add(s[i]['url']);out.append(s[i])
968
- return out[:limit]
969
-
970
- for _path in ['/api/article', '/api/hot_topics', '/api/categories', '/api/storage_status']:
971
- app.router.routes=[r for r in app.router.routes if not(getattr(r,'path',None)==_path and 'GET' in getattr(r,'methods',set()))]
972
-
973
- _article_cache = {}
974
- _article_cache_ttl = 1800
975
-
976
- _art_session = None
977
- _art_lock = threading.Lock()
978
- def _get_art_session():
979
- global _art_session
980
- if _art_session is None:
981
- with _art_lock:
982
- if _art_session is None:
983
- _art_session = req.Session()
984
- _art_session.headers.update({
985
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
986
- "Accept-Language": "vi-VN,vi;q=0.9,en;q=0.8",
987
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
988
- })
989
- return _art_session
990
-
991
- def _scrape_article_fast(url):
992
- from urllib.parse import urlparse
993
- domain = urlparse(url).netloc
994
- sess = _get_art_session()
995
- uas = [
996
- {"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"},
997
- {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"},
998
- ]
999
- for ua in uas:
1000
- try:
1001
- r = sess.get(url, headers=ua, timeout=6, allow_redirects=True)
1002
- if not r or r.status_code != 200:
1003
- continue
1004
- r.encoding = 'utf-8'
1005
- soup = BeautifulSoup(r.text, 'lxml')
1006
- for tag in soup.find_all(['script','style','nav','footer','aside','form','noscript','iframe','.ads','.ad','.banner-ads','.fb-comments','.fb-root','.social-share','.related-news','.tag','.breadcrumb']):
1007
- tag.decompose()
1008
- title = summary = og_img = ""
1009
- ogt = soup.find('meta', property='og:title')
1010
- if ogt: title = ogt.get('content', '')
1011
- ogd = soup.find('meta', property='og:description') or soup.find('meta', attrs={'name': 'description'})
1012
- if ogd: summary = ogd.get('content', '')[:500]
1013
- ogi = soup.find('meta', property='og:image')
1014
- if ogi:
1015
- og_img = ogi.get('content', '')
1016
- if og_img.startswith('//'): og_img = 'https:' + og_img
1017
- h1 = soup.find('h1')
1018
- if not title and h1: title = h1.get_text(strip=True)[:200]
1019
- body = []
1020
- selectors = [
1021
- '.fck_detail', '.sidebar-1',
1022
- '.singular-content', '.dt__content', '.article-content', '.content-detail', '#divNewsContent',
1023
- '.content-detail', '.main-content-detail', '.box-content',
1024
- '.knc-content', '.article-body', '.detail-body',
1025
- '.article-detail', '.detail-content',
1026
- 'article', 'main', '.cms-body', '.article__body', '.post-content',
1027
- '.entry-content', '#content', '.article-text', '.story-body',
1028
- ]
1029
- for sel in selectors:
1030
- el = soup.select_one(sel)
1031
- if el and len(el.find_all('p')) >= 2:
1032
- seen_imgs = set()
1033
- for child in el.find_all(['p','h2','h3','figure','img'], recursive=True):
1034
- if child.name == 'p':
1035
- t = child.get_text(strip=True)
1036
- if t and len(t) > 15:
1037
- body.append({'type': 'p', 'text': t})
1038
- elif child.name in ('h2','h3'):
1039
- t = child.get_text(strip=True)
1040
- if t:
1041
- body.append({'type': 'heading', 'text': t})
1042
- elif child.name in ('figure','img'):
1043
- im = child if child.name == 'img' else child.find('img')
1044
- if im:
1045
- src = im.get('data-src') or im.get('src') or im.get('data-lazy') or ''
1046
- if src and 'base64' not in src and src not in seen_imgs:
1047
- seen_imgs.add(src)
1048
- if src.startswith('//'): src = 'https:' + src
1049
- body.append({'type': 'img', 'src': src})
1050
- if child.name == 'figure':
1051
- cap = child.find('figcaption')
1052
- if cap:
1053
- ct = cap.get_text(strip=True)
1054
- if ct: body.append({'type': 'p', 'text': ct})
1055
- if len(body) >= 2:
1056
- return {'title': _clean(title), 'summary': _clean(summary), 'og_image': og_img,
1057
- 'body': body[:50], 'source': domain, 'url': url}
1058
- if title and (summary or og_img):
1059
- fallback = []
1060
- if og_img: fallback.append({'type': 'img', 'src': og_img})
1061
- if summary: fallback.append({'type': 'p', 'text': summary})
1062
- if fallback:
1063
- return {'title': _clean(title), 'summary': _clean(summary), 'og_image': og_img,
1064
- 'body': fallback, 'source': domain, 'url': url, 'fallback': True}
1065
- if title:
1066
- return {'title': _clean(title), 'summary': '', 'og_image': '',
1067
- 'body': [{'type': 'p', 'text': 'Nội dung đang được tải...'}],
1068
- 'source': domain, 'url': url, 'fallback': True}
1069
- break
1070
- except Exception:
1071
- continue
1072
- return None
1073
-
1074
- @app.get('/api/article')
1075
- def api_article_v2(url: str = Query(...)):
1076
- from urllib.parse import unquote
1077
- safe_url = unquote(url)
1078
- try:
1079
- now = time.time()
1080
- cached = _article_cache.get(safe_url)
1081
- if cached and now - cached['t'] < _article_cache_ttl:
1082
- resp = JSONResponse(cached['d'])
1083
- resp.headers["Cache-Control"] = "public, max-age=1800"
1084
- return resp
1085
- data = _scrape_article_fast(safe_url)
1086
- if data and data.get('body'):
1087
- _article_cache[safe_url] = {'d': data, 't': now}
1088
- resp = JSONResponse(data)
1089
- resp.headers["Cache-Control"] = "public, max-age=1800"
1090
- return resp
1091
- result = {'error': 'Không đọc được', 'url': safe_url}
1092
- resp = JSONResponse(result)
1093
- resp.headers["Cache-Control"] = "public, max-age=60"
1094
- return resp
1095
- except Exception as e:
1096
- return JSONResponse({'error': f'Server error: {str(e)[:100]}', 'url': safe_url}, status_code=200)
1097
-
1098
- _hot_cache={'t':0,'d':[]}
1099
- def _get_hot_topics():
1100
- now=time.time()
1101
- if _hot_cache['d'] and now-_hot_cache['t']<600:return _hot_cache['d']
1102
- freq={};display={}
1103
- feeds=['https://vnexpress.net/rss/tin-moi-nhat.rss','https://dantri.com.vn/rss/home.rss','https://vietnamnet.vn/rss/tin-moi-nhat.rss','https://thanhnien.vn/rss/home.rss','https://tuoitre.vn/rss/tin-moi-nhat.rss','https://genk.vn/rss','https://vnexpress.net/rss/the-thao.rss','https://thethaovanhoa.vn/rss/tin-nong.rss']
1104
- for feed_url in feeds:
1105
- try:
1106
- r=req.get(feed_url,headers={'User-Agent':'Mozilla/5.0'},timeout=6);r.encoding='utf-8';soup=BeautifulSoup(r.text,'xml')
1107
- for item in soup.find_all('item')[:12]:
1108
- title=_clean(item.find('title').get_text() if item.find('title') else '')
1109
- if not title:continue
1110
- title=re.sub(r'\s*[-|].*$','',title);words=[w for w in re.findall(r'[A-Za-zÀ-ỹ0-9]+',title) if len(w)>2 and w.lower() not in _STOP]
1111
- if len(words)<2:continue
1112
- for n in(3,4,2):
1113
- for i in range(max(0,len(words)-n+1)):
1114
- phrase=' '.join(words[i:i+n])
1115
- if 8<=len(phrase)<=45:key=phrase.lower();freq[key]=freq.get(key,0)+1;display[key]=phrase
1116
- except:continue
1117
- ranked=sorted(freq.items(),key=lambda x:x[1],reverse=True);topics=[];seen=set()
1118
- for key,count in ranked:
1119
- is_dup=any(len(set(e.split())&set(key.split()))/max(len(set(e.split())),len(set(key.split())),1)>0.6 for e in seen)
1120
- if is_dup:continue
1121
- seen.add(key);topics.append({'label':'#'+re.sub(r'\s+','',display[key].title()),'topic':display[key],'count':count})
1122
- if len(topics)>=20:break
1123
- for kw in['World Cup 2026','Kinh tế Việt Nam','Bóng đá châu Âu','Công nghệ AI','Giá vàng','Thời tiết']:
1124
- if len(topics)>=24:break
1125
- if not any(kw.lower() in s for s in seen):topics.append({'label':'#'+re.sub(r'\s+','',kw.title()),'topic':kw,'count':0})
1126
- _hot_cache.update({'t':now,'d':topics[:24]});return topics[:24]
1127
-
1128
- @app.get('/api/hot_topics')
1129
- def api_hot_topics():
1130
- resp = JSONResponse({'topics':_get_hot_topics()})
1131
- resp.headers["Cache-Control"] = "public, max-age=120"
1132
- return resp
1133
- @app.get('/')
1134
- async def serve_index():
1135
- p=os.path.join(STATIC_DIR,'index_v2.html')
1136
- if os.path.exists(p):return FileResponse(p,media_type='text/html')
1137
- return HTMLResponse('<h1>VNEWS</h1>')
1138
- @app.get('/api/hashtag/sources')
1139
- def _ht(topic:str=Query(...),page:int=Query(default=0)):
1140
- items=_search_all(topic,36);per_page=8;start=page*per_page;end=start+per_page
1141
- return JSONResponse({'sources':items[start:end],'topic':topic,'page':page,'has_more':end<len(items),'total':len(items)})
1142
- @app.get('/api/categories')
1143
- def _cat():return JSONResponse([])
1144
- @app.get('/api/storage_status')
1145
- def _st():return JSONResponse({'persistent':os.path.isdir('/data') and os.access('/data',os.W_OK)})
1146
- # ===== SHARE HELPERS - Updated 1783740350: render content pages for shared links =====
1147
- def _render_slides_page(post, safe_title, safe_img, safe_url):
1148
- slides = post.get('slides', [])
1149
- # Get image from post.img or first slide's image
1150
- if not safe_img and slides and slides[0].get('image'):
1151
- safe_img = slides[0].get('image', '')
1152
- # Use text for description if available
1153
- description = _clean((post.get('text') or '')[:200]) or "Tin tức tóm tắt, AI rewrite, World Cup 2026"
1154
-
1155
- # Build canonical URL preserving original query format if url was provided
1156
- if safe_url and safe_url != '/':
1157
- canonical_url = f"{SPACE}/s?url={quote(safe_url)}&title={quote(safe_title[:100])}"
1158
- else:
1159
- canonical_url = f"{SPACE}/s?post_id={post.get('id') or ''}"
1160
-
1161
- h = f'''<!DOCTYPE html>
1162
- <html lang="vi">
1163
- <head>
1164
- <meta charset="utf-8">
1165
- <meta name="viewport" content="width=device-width,initial-scale=1">
1166
- <title>{_clean(safe_title)}</title>
1167
- <meta property="og:title" content="{_clean(safe_title)}">
1168
- <meta property="og:image" content="{_clean(safe_img)}">
1169
- <meta property="og:description" content="{description}">
1170
- <meta property="og:url" content="{canonical_url}">
1171
- <link rel="canonical" href="{canonical_url}">
1172
- <style>
1173
- *{{box-sizing:border-box;margin:0;padding:0}}body{{background:#111;color:#eee;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;padding:12px}}
1174
- .slide-card{{background:#1a1a1a;border:1px solid #2a2a2a;border-radius:12px;padding:16px;margin-bottom:12px;max-width:600px;margin-left:auto;margin-right:auto}}
1175
- .slide-num{{color:#5cb87a;font-size:12px;font-weight:700;margin-bottom:6px}}
1176
- .slide-img{{width:100%;max-height:300px;object-fit:cover;border-radius:8px;margin-bottom:8px}}
1177
- .slide-text{{color:#ddd;font-size:14px;line-height:1.6;margin:0}}
1178
- </style>
1179
- </head>
1180
- <body>'''
1181
- for s in slides:
1182
- img_src = s.get('image', '')
1183
- if img_src and ('cdnphoto.dantri' in img_src or 'refooty' in img_src or 'vnexpress' in img_src or 'vcdn' in img_src):
1184
- img_tag = f'<img src="/api/proxy/img?url={quote(img_src, safe="")}" class="slide-img" loading="lazy" onerror="this.style.display=\'none\'">'
1185
- else:
1186
- img_tag = f'<img src="{_clean(img_src)}" class="slide-img" loading="lazy" onerror="this.style.display=\'none\'">' if img_src else ''
1187
- h += f'<div class="slide-card"><div class="slide-num">Slide {s.get("index",1)}/{len(slides)}</div>{img_tag}<p class="slide-text">{_clean(s.get("text",""))}</p></div>'
1188
- h += '</body></html>'
1189
- return HTMLResponse(h)
1190
-
1191
- def _render_video_page(post, safe_title, safe_img, safe_url):
1192
- video_url = post.get('video', '')
1193
- # Use text for description if available
1194
- description = _clean((post.get('text') or '')[:200]) or "Tin tức tóm tắt, AI rewrite, World Cup 2026"
1195
-
1196
- # Build canonical URL preserving original query format if url was provided
1197
- if safe_url and safe_url != '/':
1198
- canonical_url = f"{SPACE}/s?url={quote(safe_url)}&title={quote(safe_title[:100])}"
1199
- else:
1200
- canonical_url = f"{SPACE}/s?post_id={post.get('id') or ''}"
1201
-
1202
- h = f'''<!DOCTYPE html>
1203
- <html lang="vi">
1204
- <head>
1205
- <meta charset="utf-8">
1206
- <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
1207
- <title>{_clean(safe_title)}</title>
1208
- <meta property="og:title" content="{_clean(safe_title)}">
1209
- <meta property="og:image" content="{_clean(safe_img)}">
1210
- <meta property="og:description" content="{description}">
1211
- <meta property="og:url" content="{canonical_url}">
1212
- <link rel="canonical" href="{canonical_url}">
1213
- <meta name="twitter:card" content="player">
1214
- <meta name="twitter:player" content="{video_url}">
1215
- <style>
1216
- *{{box-sizing:border-box;margin:0;padding:0}}body{{background:#111;color:#eee;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;padding:0;overflow:hidden}}
1217
- .video-container{{width:100vw;height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;background:#000}}
1218
- video{{width:100%;height:100%;max-height:100vh;object-fit:contain;background:#000}}
1219
- .title-bar{{position:fixed;bottom:0;left:0;right:0;background:linear-gradient(transparent,rgba(0,0,0,.8));padding:40px 16px 16px;text-align:center}}
1220
- .title-text{{color:#fff;font-size:13px;line-height:1.4;max-width:600px;margin:0 auto}}
1221
- </style>
1222
- </head>
1223
- <body>
1224
- <div class="video-container">
1225
- <video src="{_clean(video_url)}" controls autoplay playsinline loop></video>
1226
- <div class="title-bar"><div class="title-text">{_clean(safe_title)}</div></div>
1227
- </div>
1228
- </body></html>'''
1229
- return HTMLResponse(h)
1230
-
1231
- @app.get('/s/{slug}')
1232
- async def _sh_slug(slug: str, request: Request, url: str = '', title: str = '', img: str = ''):
1233
- """SEO-friendly share endpoint with slug in URL path.
1234
- Shows slide content when slug matches a wall post ID, otherwise redirects.
1235
- """
1236
- safe_title = _clean(title) if title else 'VNEWS - Tin tức'
1237
- safe_img = _clean(img) if img else ''
1238
- safe_url = _clean(url) if url else '/'
1239
-
1240
- # Try to find post by slug (post ID)
1241
- post = None
1242
- try:
1243
- if slug and len(slug) > 5: # Likely a post ID
1244
- posts = _load_wall_posts()
1245
- for p in posts:
1246
- if p.get('id') == slug:
1247
- post = p
1248
- safe_title = p.get('title', safe_title) or safe_title
1249
- safe_img = p.get('img', safe_img) or safe_img
1250
- safe_url = p.get('url', safe_url) or safe_url
1251
- break
1252
- except:
1253
- pass
1254
-
1255
- if post and post.get('slides'):
1256
- return _render_slides_page(post, safe_title, safe_img, safe_url)
1257
-
1258
- if post and post.get('video'):
1259
- return _render_video_page(post, safe_title, safe_img, safe_url)
1260
-
1261
- # Otherwise redirect
1262
- return HTMLResponse(f'''<!DOCTYPE html>
1263
- <html lang="vi">
1264
- <head>
1265
- <meta charset="utf-8">
1266
- <meta name="viewport" content="width=device-width,initial-scale=1">
1267
- <title>{_clean(safe_title)}</title>
1268
- <meta property="og:title" content="{_clean(safe_title)}">
1269
- <meta property="og:image" content="{_clean(safe_img)}">
1270
- <meta property="og:description" content="Tin tức tóm tắt, AI rewrite, World Cup 2026">
1271
- <meta property="og:url" content="{SPACE}/s/{slug}">
1272
- <link rel="canonical" href="{SPACE}/s/{slug}">
1273
- <meta http-equiv="refresh" content="0;url={safe_url}">
1274
- </head><body></body></html>''')
1275
-
1276
- @app.get('/s')
1277
- async def _sh(url:str='',title:str='',img:str='',post_id:str=''):
1278
- safe_title = _clean(title) if title else 'VNEWS - Tin tức'
1279
- safe_img = _clean(img) if img else ''
1280
- safe_url = _clean(url) if url else '/'
1281
-
1282
- # Try to find wall post by post_id or URL
1283
- post = None
1284
- try:
1285
- posts = _load_wall_posts()
1286
- for p in posts:
1287
- if post_id and p.get('id') == post_id:
1288
- post = p
1289
- safe_title = p.get('title', safe_title) or safe_title
1290
- safe_img = p.get('img', safe_img) or safe_img
1291
- safe_url = p.get('url', safe_url) or safe_url
1292
- break
1293
- if url and p.get('url') == url:
1294
- post = p
1295
- safe_title = p.get('title', safe_title) or safe_title
1296
- safe_img = p.get('img', safe_img) or safe_img
1297
- safe_url = p.get('url', safe_url) or safe_url
1298
- break
1299
- except:
1300
- pass
1301
-
1302
- if post and post.get('slides'):
1303
- return _render_slides_page(post, safe_title, safe_img, safe_url)
1304
-
1305
- if post and post.get('video'):
1306
- return _render_video_page(post, safe_title, safe_img, safe_url)
1307
-
1308
- # Fallback: redirect to original URL
1309
- return HTMLResponse(f'''<!DOCTYPE html>
1310
- <html lang="vi">
1311
- <head>
1312
- <meta charset="utf-8">
1313
- <meta name="viewport" content="width=device-width,initial-scale=1">
1314
- <title>{safe_title}</title>
1315
- <meta property="og:title" content="{safe_title}">
1316
- <meta property="og:image" content="{safe_img}">
1317
- <meta property="og:description" content="Tin tức tóm tắt, AI rewrite, World Cup 2026">
1318
- <meta property="og:url" content="{SPACE}/s?url={quote(safe_url)}">
1319
- <link rel="canonical" href="{SPACE}/s?url={quote(safe_url)}">
1320
- <meta http-equiv="refresh" content="0;url={safe_url}">
1321
- </head><body></body></html>''')
1322
-
1323
- from wc2026_scraper import scrape_summary,scrape_fixtures,scrape_standings,scrape_stats,scrape_wc_news,scrape_road_to_wc,get_wc2026_all,scrape_history,scrape_h2h,scrape_lineups,scrape_match_detail
1324
-
1325
- _xlb_cache = {}
1326
- _xlb_lock = threading.Lock()
1327
-
1328
- def _xlb_scrape(path):
1329
- url = f"https://xemlaibongda.top/{path}"
1330
- r = req.get(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}, timeout=15, allow_redirects=True)
1331
- if r.status_code != 200:
1332
- return []
1333
- soup = BeautifulSoup(r.text, 'lxml')
1334
- vids = []
1335
- seen = set()
1336
- for a in soup.select('a[href*="/video/"]'):
1337
- href = a.get('href', '')
1338
- if not href or href in seen:
1339
- continue
1340
- seen.add(href)
1341
- if not href.startswith('http'):
1342
- href = 'https://xemlaibongda.top' + href
1343
- img = a.select_one('img')
1344
- p = a.parent
1345
- for _ in range(4):
1346
- if img:
1347
- break
1348
- if p:
1349
- img = p.select_one('img')
1350
- p = p.parent
1351
- img_src = ''
1352
- if img:
1353
- img_src = img.get('data-src','') or img.get('src','') or img.get('data-lazy','') or img.get('data-original','')
1354
- if img_src.startswith('//'):
1355
- img_src = 'https:' + img_src
1356
- elif img_src.startswith('/'):
1357
- img_src = 'https://xemlaibongda.top' + img_src
1358
- title = ''
1359
- for sel in ['.title', 'h3', 'h2', '.name', '.post-title', '.entry-title', '.video-title']:
1360
- t = a.select_one(sel)
1361
- if t:
1362
- title = _clean(t.get_text())
1363
- break
1364
- if not title:
1365
- title = _clean(a.get('title',''))
1366
- if not title:
1367
- img_alt = a.select_one('img')
1368
- if img_alt:
1369
- title = _clean(img_alt.get('alt',''))
1370
- if not title:
1371
- parent = a.parent
1372
- if parent:
1373
- pt = _clean(parent.get_text(' ',strip=True))
1374
- if 5 < len(pt) < 120:
1375
- title = pt
1376
- if not title or len(title) < 3:
1377
- continue
1378
- vids.append({"link": href, "img": img_src, "title": title})
1379
- if len(vids) >= 30:
1380
- break
1381
- return vids
1382
-
1383
- @app.get('/api/proxy/xlb')
1384
- def proxy_xlb(path: str = Query(default="")):
1385
- now = time.time()
1386
- cache_key = f"xlb:{path}"
1387
- with _xlb_lock:
1388
- cached = _xlb_cache.get(cache_key)
1389
- if cached and now - cached['t'] < 120:
1390
- return JSONResponse(cached['d'])
1391
- try:
1392
- vids = _xlb_scrape(path)
1393
- result = {"videos": vids, "count": len(vids)}
1394
- with _xlb_lock:
1395
- _xlb_cache[cache_key] = {'t': now, 'd': result}
1396
- return JSONResponse(result)
1397
- except Exception as e:
1398
- return JSONResponse({"videos": [], "count": 0, "error": str(e)}, status_code=500)
1399
-
1400
- @app.get('/api/wc2026')
1401
- def _w():return JSONResponse(get_wc2026_all())
1402
- @app.get('/api/wc2026/fixtures')
1403
- def _wf():return JSONResponse(scrape_fixtures())
1404
- @app.get('/api/wc2026/standings')
1405
- def _ws():return JSONResponse(scrape_standings())
1406
- @app.get('/api/wc2026/stats')
1407
- def _wst():return JSONResponse(scrape_stats())
1408
- @app.get('/api/wc2026/history')
1409
- def _whi():return JSONResponse(scrape_history())
1410
- @app.get('/api/wc2026/news')
1411
- def _wn():return JSONResponse(scrape_wc_news())
1412
- @app.get('/api/wc2026/road')
1413
- def _wr():return JSONResponse(scrape_road_to_wc())
1414
- @app.get('/api/wc2026/h2h/{eid}')
1415
- def _wh2(eid:int):return JSONResponse(scrape_h2h(eid))
1416
- @app.get('/api/wc2026/lineups/{eid}')
1417
- def _wl(eid:int):return JSONResponse(scrape_lineups(eid))
1418
- @app.get('/api/wc2026/match/{eid}')
1419
- def _wm(eid:int):return JSONResponse(scrape_match_detail(eid))
1420
-
1421
- DATA_DIR='/data' if os.path.isdir('/data') else os.path.join(os.path.dirname(os.path.abspath(__file__)),'data')
1422
- os.makedirs(DATA_DIR,exist_ok=True)
1423
- IF=os.path.join(DATA_DIR,'interactions_v2.json')
1424
- CF=os.path.join(DATA_DIR,'comments_v2.json')
1425
- WALL_FILE=os.path.join(DATA_DIR,'wall_posts.json')
1426
- WALL_VIDEO_DIR=os.path.join(DATA_DIR,'wall_videos')
1427
- os.makedirs(WALL_VIDEO_DIR,exist_ok=True)
1428
-
1429
- _il=threading.Lock();_cl=threading.Lock();_wl_lock=threading.Lock()
1430
- def _lj(p):
1431
- try:
1432
- if os.path.exists(p):return json.load(open(p,'r',encoding='utf-8'))
1433
- except:pass
1434
- return{}
1435
- def _sj(p,d):
1436
- try:open(p+'.tmp','w',encoding='utf-8').write(json.dumps(d,ensure_ascii=False));os.replace(p+'.tmp',p)
1437
- except:pass
1438
-
1439
- @app.post('/api/v2/interact')
1440
- async def _int(request:Request):
1441
- b=await request.json();v=str(b.get('id','')).strip();t=str(b.get('type','')).strip()
1442
- if not v or t not in('view','like'):return JSONResponse({'error':'x'},status_code=400)
1443
- with _il:db=_lj(IF);db.setdefault(v,{'views':0,'likes':0,'comments':0});db[v][t+'s']+=1;_sj(IF,db);return JSONResponse(db[v])
1444
-
1445
- @app.get('/api/v2/interactions')
1446
- def _gi(id:str=Query(...)):
1447
- with _il:return JSONResponse(_lj(IF).get(id.strip(),{'views':0,'likes':0,'comments':0}))
1448
-
1449
- @app.get('/api/v2/comments')
1450
- def _gc(id:str=Query(...)):
1451
- with _cl:return JSONResponse({'comments':_lj(CF).get(id.strip(),[])})
1452
-
1453
- @app.post('/api/v2/comment')
1454
- async def _pc(request:Request):
1455
- b=await request.json();v=str(b.get('id','')).strip();tx=str(b.get('text','')).strip()[:500]
1456
- if not v or not tx:return JSONResponse({'error':'x'},status_code=400)
1457
- c={'text':tx,'time':time.strftime('%H:%M %d/%m',time.localtime()),'ts':int(time.time())}
1458
- with _cl:db=_lj(CF);db.setdefault(v,[]);db[v].append(c);db[v]=db[v][-200:];_sj(CF,db);cms=db[v]
1459
- with _il:idb=_lj(IF);idb.setdefault(v,{'views':0,'likes':0,'comments':0});idb[v]['comments']=len(cms);_sj(IF,idb)
1460
- return JSONResponse({'comments':cms})
1461
-
1462
- def _load_wall_posts():
1463
- with _wl_lock:
1464
- return _lj(WALL_FILE)
1465
-
1466
- def _save_wall_posts(posts):
1467
- with _wl_lock:
1468
- _sj(WALL_FILE, posts)
1469
-
1470
- @app.get('/api/wall')
1471
- def api_wall():
1472
- posts = _load_wall_posts()
1473
- if not posts:
1474
- return JSONResponse({"posts": []})
1475
- return JSONResponse({"posts": posts})
1476
-
1477
- @app.post('/api/wall')
1478
- async def api_wall_post(request: Request):
1479
- content_type = request.headers.get('content-type', '')
1480
- if 'multipart/form-data' in content_type:
1481
- try:
1482
- form = await request.form()
1483
- except Exception as e:
1484
- return JSONResponse({"error": f"Form parse error: {str(e)}"}, status_code=400)
1485
- title = form.get('title', 'Video mới') or 'Video mới'
1486
- text = form.get('text', '') or ''
1487
- source = form.get('source', 'vtv_recorder') or 'vtv_recorder'
1488
- video_file = form.get('video')
1489
- post_id = str(uuid.uuid4())[:12]
1490
- video_url = None
1491
- if video_file and hasattr(video_file, 'filename') and video_file.filename:
1492
- fname = video_file.filename.lower()
1493
- if fname.endswith('.mp4'):
1494
- ext = '.mp4'
1495
- elif fname.endswith('.webm'):
1496
- ext = '.webm'
1497
- else:
1498
- ext = '.webm'
1499
- video_filename = f"wall_{post_id}{ext}"
1500
- video_path = os.path.join(WALL_VIDEO_DIR, video_filename)
1501
- try:
1502
- content = await video_file.read()
1503
- if not content:
1504
- return JSONResponse({"error": "Empty video file"}, status_code=400)
1505
- with open(video_path, 'wb') as f:
1506
- f.write(content)
1507
- file_size_mb = len(content) / 1024 / 1024
1508
- if file_size_mb > 50:
1509
- os.remove(video_path)
1510
- return JSONResponse({"error": f"Video quá lớn ({file_size_mb:.1f}MB). Tối đa 50MB."}, status_code=400)
1511
- video_url = f"/api/wall/video/{video_filename}"
1512
- except Exception as e:
1513
- return JSONResponse({"error": f"Lỗi lưu video: {str(e)}"}, status_code=500)
1514
- post = {
1515
- "id": post_id,
1516
- "title": title[:200],
1517
- "text": text[:2000],
1518
- "source": source,
1519
- "video": video_url,
1520
- "img": None,
1521
- "images": [],
1522
- "created": int(time.time()),
1523
- "created_str": time.strftime('%H:%M %d/%m/%Y', time.localtime()),
1524
- }
1525
- posts = _load_wall_posts()
1526
- if not isinstance(posts, list):
1527
- posts = []
1528
- posts.insert(0, post)
1529
- posts = posts[:200]
1530
- _save_wall_posts(posts)
1531
- return JSONResponse({"post": post, "ok": True})
1532
- try:
1533
- body = await request.json()
1534
- except:
1535
- body = {}
1536
- title = body.get('title', 'Bài mới') or 'Bài mới'
1537
- text = body.get('text', '') or ''
1538
- img = body.get('img', None)
1539
- source = body.get('source', 'user') or 'user'
1540
- post_id = str(uuid.uuid4())[:12]
1541
- post = {
1542
- "id": post_id,
1543
- "title": title[:200],
1544
- "text": text[:2000],
1545
- "source": source,
1546
- "video": None,
1547
- "img": img,
1548
- "images": [],
1549
- "created": int(time.time()),
1550
- "created_str": time.strftime('%H:%M %d/%m/%Y', time.localtime()),
1551
- }
1552
- posts = _load_wall_posts()
1553
- if not isinstance(posts, list):
1554
- posts = []
1555
- posts.insert(0, post)
1556
- posts = posts[:200]
1557
- _save_wall_posts(posts)
1558
- return JSONResponse({"post": post, "ok": True})
1559
-
1560
- @app.get('/api/wall/video/{filename}')
1561
- def api_wall_video(filename: str):
1562
- if '..' in filename or '/' in filename:
1563
- return Response(status_code=403)
1564
- video_path = os.path.join(WALL_VIDEO_DIR, filename)
1565
- if not os.path.exists(video_path):
1566
- return Response(status_code=404)
1567
- ext = os.path.splitext(filename)[1].lower()
1568
- media_type = 'video/mp4' if ext == '.mp4' else 'video/webm'
1569
- return FileResponse(video_path, media_type=media_type)
1570
-
1571
- @app.delete('/api/wall/{post_id}')
1572
- def api_wall_delete(post_id: str):
1573
- posts = _load_wall_posts()
1574
- if not isinstance(posts, list):
1575
- return JSONResponse({"error": "No posts"}, status_code=404)
1576
- for i, p in enumerate(posts):
1577
- if p.get('id') == post_id:
1578
- if p.get('video'):
1579
- video_name = p['video'].split('/')[-1]
1580
- video_path = os.path.join(WALL_VIDEO_DIR, video_name)
1581
- if os.path.exists(video_path):
1582
- os.remove(video_path)
1583
- posts.pop(i)
1584
- _save_wall_posts(posts)
1585
- return JSONResponse({"ok": True})
1586
- return JSONResponse({"error": "Post not found"}, status_code=404)
1587
-
1588
- # ===== LANGUAGE & EMOTION DETECTION =====
1589
- import random as _random2
1590
- from urllib.parse import quote as _quote2
1591
-
1592
- _UA_RW = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'Accept-Language': 'vi-VN,vi;q=0.9'}
1593
-
1594
- # Unique character markers for language detection
1595
- _UNIQUE_CHARS = {
1596
- 'vietnamese': set('đăâêôơưàảãạáằẳẵặắầẩẫậấèẻẽẹéềễểệếìỉĩịíòỏõọóồổỗộốờởỡợớùủũụúừửữựứỳỷỹỵý'),
1597
- 'spanish': set('ñáéíóúü¿¡'),
1598
- 'portuguese': set('ãõçáéíóúâêôà'),
1599
- }
1600
-
1601
- _STOPWORDS = {
1602
- 'english': {'the', 'is', 'at', 'which', 'on', 'a', 'an', 'and', 'or', 'but', 'in', 'with', 'to', 'for', 'of', 'not', 'no', 'can', 'had', 'have', 'has', 'was', 'were', 'are', 'be', 'been', 'this', 'that', 'it', 'he', 'she', 'they', 'his', 'her', 'my', 'your', 'our', 'we', 'you', 'i'},
1603
- 'vietnamese': {'là', 'của', 'và', 'có', 'được', 'cho', 'không', 'với', 'này', 'đó', 'từ', 'trong', 'đã', 'sẽ', 'một', 'các', 'những', 'về', 'tại', 'người', 'năm', 'đến', 'ra', 'lại', 'như', 'khi', 'để', 'rất', 'cũng', 'mà', 'nếu', 'sau', 'trên', 'theo', 'vì', 'do', 'nên', 'thì', 'mình', 'tôi', 'bạn', 'anh', 'chị', 'em'},
1604
- 'portuguese': {'de', 'um', 'que', 'e', 'do', 'da', 'em', 'para', 'com', 'não', 'uma', 'os', 'no', 'se', 'na', 'por', 'mais', 'as', 'dos', 'como', 'mas', 'ao', 'ele', 'das', 'tem', 'seu', 'sua', 'ou', 'quando', 'muito', 'nos', 'já', 'eu', 'também', 'só', 'pelo', 'pela', 'até', 'isso', 'ela', 'entre', 'depois', 'sem', 'mesmo', 'aos', 'são', 'está', 'ter', 'ser', 'foi', 'era', 'há', 'estão', 'você', 'nós', 'eles', 'elas'},
1605
- 'spanish': {'de', 'que', 'el', 'en', 'y', 'a', 'los', 'del', 'se', 'las', 'por', 'un', 'para', 'con', 'no', 'una', 'su', 'al', 'es', 'lo', 'como', 'más', 'pero', 'sus', 'le', 'ya', 'o', 'fue', 'este', 'ha', 'si', 'porque', 'esta', 'son', 'entre', 'está', 'cuando', 'muy', 'sin', 'sobre', 'ser', 'también', 'me', 'hasta', 'hay', 'donde', 'han', 'quien', 'están', 'desde', 'todo', 'nos', 'durante', 'todos', 'uno', 'les', 'ni', 'contra', 'otros', 'fueron', 'ese', 'eso', 'ante', 'ellos', 'yo', 'tú', 'él', 'ella', 'nosotros', 'usted', 'ustedes'},
1606
- }
1607
-
1608
- def detect_language(text):
1609
- """Detect language from text content using stopword + character analysis."""
1610
- if not text:
1611
- return 'vietnamese'
1612
- text_lower = text.lower()
1613
- text_chars = set(text_lower)
1614
-
1615
- # Strong signal: Vietnamese unique characters
1616
- vn_chars = len(text_chars & _UNIQUE_CHARS['vietnamese'])
1617
- if vn_chars >= 2:
1618
- return 'vietnamese'
1619
-
1620
- # Spanish unique chars (ñ, ¿, ¡)
1621
- es_chars = len(text_chars & _UNIQUE_CHARS['spanish'])
1622
- pt_chars = len(text_chars & _UNIQUE_CHARS['portuguese'])
1623
-
1624
- # Stopword scoring
1625
- words = set(re.findall(r'\b\w+\b', text_lower))
1626
- scores = {}
1627
- for lang, stops in _STOPWORDS.items():
1628
- scores[lang] = len(words & stops) / max(len(stops), 1)
1629
-
1630
- # Disambiguate Portuguese vs Spanish
1631
- pt_markers = {'não', 'pelo', 'pela', 'isso', 'há', 'estão', 'num', 'numa', 'tenho', 'posso', 'você', 'nós', 'eles', 'elas', 'também', 'muito', 'já', 'só', 'até', 'entre', 'depois', 'sem', 'mesmo', 'aos', 'serão'}
1632
- es_markers = {'pero', 'está', 'están', 'porque', 'también', 'hasta', 'donde', 'quien', 'fue', 'son', 'fueron', 'ese', 'eso', 'ante', 'ellos', 'ella', 'nosotros', 'usted', 'ustedes', 'tú', 'él', 'desde', 'todo', 'durante', 'todos', 'uno', 'les', 'ni', 'contra', 'otros', 'fueron'}
1633
-
1634
- pt_overlap = len(words & pt_markers)
1635
- es_overlap = len(words & es_markers)
1636
-
1637
- if scores.get('portuguese', 0) > 0 and pt_overlap > es_overlap:
1638
- return 'portuguese'
1639
- if scores.get('spanish', 0) > 0 and es_overlap > pt_overlap:
1640
- return 'spanish'
1641
- if scores.get('english', 0) > 0.15:
1642
- return 'english'
1643
-
1644
- best = max(scores, key=scores.get)
1645
- return best if scores[best] > 0.05 else 'vietnamese'
1646
-
1647
- # Emotion keyword-based detection
1648
- _EMOTION_KEYWORDS = {
1649
- 'happy': {
1650
- 'en': ['happy', 'joy', 'wonderful', 'great', 'amazing', 'fantastic', 'love', 'excellent', 'beautiful', 'glad', 'delighted', 'pleased', 'cheerful', 'celebrate', 'victory', 'win', 'success'],
1651
- 'pt': ['feliz', 'alegria', 'maravilhoso', 'ótimo', 'incrível', 'fantástico', 'amor', 'excelente', 'lindo', 'contente', 'encantado', 'vitória', 'sucesso'],
1652
- 'es': ['feliz', 'alegria', 'maravilloso', 'genial', 'increíble', 'fantástico', 'amor', 'excelente', 'hermoso', 'contento', 'encantado', 'victoria', 'éxito'],
1653
- 'vi': ['vui', 'hạnh phúc', 'tuyệt vời', 'tuyệt', 'ý nghĩa', 'đẹp', 'thích', 'yêu', 'vui vẻ', 'hân hoan', 'phấn khích', 'chiến thắng', 'thành công'],
1654
- },
1655
- 'sad': {
1656
- 'en': ['sad', 'unhappy', 'terrible', 'awful', 'horrible', 'miserable', 'depressed', 'grief', 'sorrow', 'tragic', 'unfortunate', 'painful', 'death', 'die', 'kill'],
1657
- 'pt': ['triste', 'infeliz', 'terrível', 'horrível', 'miserável', 'deprimido', 'dor', 'trágico', 'infelizmente', 'penoso', 'morte', 'morrer'],
1658
- 'es': ['triste', 'infeliz', 'terrible', 'horrible', 'miserable', 'deprimido', 'dolor', 'trágico', 'desafortunado', 'penoso', 'muerte', 'morir'],
1659
- 'vi': ['buồn', 'không vui', 'tồi tệ', 'kinh khủng', 'đau khổ', 'đau buồn', 'bi thương', 'khốn nạn', 'đau đớn', 'thảm họa', 'chết', 'mất'],
1660
- },
1661
- 'excited': {
1662
- 'en': ['excited', 'thrilling', 'amazing', 'wow', 'incredible', 'unbelievable', 'awesome', 'exhilarating', 'electrifying', 'breathtaking', 'breakthrough', 'record'],
1663
- 'pt': ['animado', 'emocionante', 'incrível', 'impressionante', 'sensacional', 'eletrizante', 'empolgante', 'recorde'],
1664
- 'es': ['emocionante', 'increíble', 'impresionante', 'sensacional', 'electrizante', 'emocionado', 'entusiasmado', 'récord'],
1665
- 'vi': ['hào hứng', 'phấn khích', 'thú vị', 'tuyệt cú mèo', 'đỉnh cao', 'ngoạn mục', 'sục sôi', 'kỷ lục', 'đột phá'],
1666
- },
1667
- 'humorous': {
1668
- 'en': ['funny', 'hilarious', 'joke', 'laugh', 'comedy', 'humor', 'amusing', 'witty', 'sarcastic', 'ironic', 'ridiculous', 'absurd', 'lol', 'haha'],
1669
- 'pt': ['engraçado', 'hilário', 'piada', 'rir', 'comédia', 'humor', 'divertido', 'irônico', 'ridículo', 'absurdo', 'kkk'],
1670
- 'es': ['gracioso', 'hilarante', 'broma', 'risa', 'comedia', 'humor', 'divertido', 'irónico', 'ridículo', 'absurdo', 'jaja'],
1671
- 'vi': ['hài hước', 'buồn cười', 'đùa', 'cười', 'hài', 'vui nhộn', 'hóm hỉnh', 'mỉa mai', 'lố bịch', 'vô lý', 'haha'],
1672
- },
1673
- 'serious': {
1674
- 'en': ['serious', 'critical', 'important', 'urgent', 'severe', 'grave', 'significant', 'crucial', 'vital', 'essential', 'alarming', 'concerning', 'crisis', 'war', 'conflict'],
1675
- 'pt': ['sério', 'crítico', 'importante', 'urgente', 'grave', 'significativo', 'crucial', 'vital', 'essencial', 'preocupante', 'crise', 'guerra', 'conflito'],
1676
- 'es': ['serio', 'crítico', 'importante', 'urgente', 'grave', 'significativo', 'crucial', 'vital', 'esencial', 'preocupante', 'crisis', 'guerra', 'conflicto'],
1677
- 'vi': ['nghiêm trọng', 'quan trọng', 'khẩn cấp', 'nghiêm túc', 'đáng kể', 'thiết yếu', 'cần thiết', 'báo động', 'lo ngại', 'khủng hoảng', 'chiến tranh', 'xung đột'],
1678
- },
1679
- }
1680
-
1681
- def detect_emotion(text, language='vietnamese'):
1682
- """Detect emotion from text using keyword matching."""
1683
- if not text:
1684
- return 'neutral'
1685
- text_lower = text.lower()
1686
-
1687
- scores = {}
1688
- for emotion, lang_keywords in _EMOTION_KEYWORDS.items():
1689
- keywords = lang_keywords.get(language, lang_keywords.get('en', []))
1690
- score = sum(1 for kw in keywords if kw in text_lower)
1691
- scores[emotion] = score
1692
-
1693
- if max(scores.values()) == 0:
1694
- return 'neutral'
1695
-
1696
- return max(scores, key=scores.get)
1697
-
1698
- def detect_language_and_emotion(title, text):
1699
- """Detect both language and emotion from article content."""
1700
- combined = f"{title} {text}"
1701
- lang = detect_language(combined)
1702
- emotion = detect_emotion(combined, lang)
1703
- return lang, emotion
1704
-
1705
- # Voice selection based on language and emotion (using MultilingualNeural voices)
1706
- VOICE_BY_LANG_EMOTION = {
1707
- 'vietnamese': {
1708
- 'happy': ('vi-VN-HoaiMyNeural', 'vui'),
1709
- 'sad': ('vi-VN-NamMinhNeural', 'buồn'),
1710
- 'excited': ('vi-VN-HoaiMyNeural', 'hào hứng'),
1711
- 'humorous': ('vi-VN-HoaiMyNeural', 'vui'),
1712
- 'serious': ('vi-VN-NamMinhNeural', 'nghiêm túc'),
1713
- 'neutral': ('vi-VN-HoaiMyNeural', 'trung_tinh'),
1714
- },
1715
- 'portuguese': {
1716
- 'happy': ('pt-BR-ThalitaMultilingualNeural', 'feliz'),
1717
- 'sad': ('pt-BR-ThalitaMultilingualNeural', 'triste'),
1718
- 'excited': ('pt-BR-ThalitaMultilingualNeural', 'animado'),
1719
- 'humorous': ('pt-BR-ThalitaMultilingualNeural', 'engraçado'),
1720
- 'serious': ('pt-BR-ThalitaMultilingualNeural', 'sério'),
1721
- 'neutral': ('pt-BR-ThalitaMultilingualNeural', 'neutro'),
1722
- },
1723
- 'english': {
1724
- 'happy': ('en-US-AndrewMultilingualNeural', 'happy'),
1725
- 'sad': ('en-AU-WilliamMultilingualNeural', 'sad'),
1726
- 'excited': ('en-US-AndrewMultilingualNeural', 'excited'),
1727
- 'humorous': ('en-US-AndrewMultilingualNeural', 'funny'),
1728
- 'serious': ('en-AU-WilliamMultilingualNeural', 'serious'),
1729
- 'neutral': ('en-US-AndrewMultilingualNeural', 'neutral'),
1730
- },
1731
- 'french': {
1732
- 'happy': ('fr-FR-VivienneMultilingualNeural', 'heureux'),
1733
- 'sad': ('fr-FR-RemyMultilingualNeural', 'triste'),
1734
- 'excited': ('fr-FR-VivienneMultilingualNeural', 'excité'),
1735
- 'humorous': ('fr-FR-VivienneMultilingualNeural', 'drôle'),
1736
- 'serious': ('fr-FR-RemyMultilingualNeural', 'sérieux'),
1737
- 'neutral': ('fr-FR-VivienneMultilingualNeural', 'neutre'),
1738
- },
1739
- 'german': {
1740
- 'happy': ('de-DE-SeraphinaMultilingualNeural', 'glücklich'),
1741
- 'sad': ('de-DE-FlorianMultilingualNeural', 'traurig'),
1742
- 'excited': ('de-DE-SeraphinaMultilingualNeural', 'aufgeregt'),
1743
- 'humorous': ('de-DE-SeraphinaMultilingualNeural', 'lustig'),
1744
- 'serious': ('de-DE-FlorianMultilingualNeural', 'ernst'),
1745
- 'neutral': ('de-DE-SeraphinaMultilingualNeural', 'neutral'),
1746
- },
1747
- 'korean': {
1748
- 'happy': ('ko-KR-HyunsuMultilingualNeural', '행복'),
1749
- 'sad': ('ko-KR-HyunsuMultilingualNeural', '슬픔'),
1750
- 'excited': ('ko-KR-HyunsuMultilingualNeural', '흥분'),
1751
- 'humorous': ('ko-KR-HyunsuMultilingualNeural', '유쾌'),
1752
- 'serious': ('ko-KR-HyunsuMultilingualNeural', '진지'),
1753
- 'neutral': ('ko-KR-HyunsuMultilingualNeural', '중립'),
1754
- },
1755
- 'italian': {
1756
- 'happy': ('it-IT-GiuseppeMultilingualNeural', 'felice'),
1757
- 'sad': ('it-IT-GiuseppeMultilingualNeural', 'triste'),
1758
- 'excited': ('it-IT-GiuseppeMultilingualNeural', 'emozionato'),
1759
- 'humorous': ('it-IT-GiuseppeMultilingualNeural', 'divertente'),
1760
- 'serious': ('it-IT-GiuseppeMultilingualNeural', 'serio'),
1761
- 'neutral': ('it-IT-GiuseppeMultilingualNeural', 'neutro'),
1762
- },
1763
- }
1764
-
1765
- # All valid voice IDs (new MultilingualNeural format)
1766
- VALID_VOICES = {
1767
- 'vi-VN-HoaiMyNeural', 'vi-VN-NamMinhNeural',
1768
- 'en-US-AndrewMultilingualNeural', 'en-AU-WilliamMultilingualNeural',
1769
- 'pt-BR-ThalitaMultilingualNeural',
1770
- 'fr-FR-VivienneMultilingualNeural', 'fr-FR-RemyMultilingualNeural',
1771
- 'de-DE-SeraphinaMultilingualNeural', 'de-DE-FlorianMultilingualNeural',
1772
- 'ko-KR-HyunsuMultilingualNeural',
1773
- 'it-IT-GiuseppeMultilingualNeural',
1774
- }
1775
-
1776
- def get_voice_for_content(title, text, preferred_voice=None):
1777
- """Get appropriate voice based on content language and emotion."""
1778
- # Accept the new MultilingualNeural voices directly
1779
- if preferred_voice and preferred_voice in VALID_VOICES:
1780
- return preferred_voice
1781
-
1782
- # Also accept old shorthand voice IDs and map them to new format
1783
- old_voice_map = {
1784
- 'hoaimy': 'vi-VN-HoaiMyNeural',
1785
- 'namminh': 'vi-VN-NamMinhNeural',
1786
- 'andrew': 'en-US-AndrewMultilingualNeural',
1787
- 'jenny': 'en-US-AndrewMultilingualNeural',
1788
- 'thalita': 'pt-BR-ThalitaMultilingualNeural',
1789
- 'pt_thalita': 'pt-BR-ThalitaMultilingualNeural',
1790
- 'pt_francisco': 'pt-BR-ThalitaMultilingualNeural',
1791
- 'ela': 'en-US-AndrewMultilingualNeural',
1792
- 'es_carlos': 'en-US-AndrewMultilingualNeural',
1793
- 'denise': 'fr-FR-VivienneMultilingualNeural',
1794
- 'katja': 'de-DE-SeraphinaMultilingualNeural',
1795
- 'nanami': 'en-US-AndrewMultilingualNeural',
1796
- 'sunhee': 'ko-KR-HyunsuMultilingualNeural',
1797
- 'xiaochen': 'en-US-AndrewMultilingualNeural',
1798
- }
1799
- if preferred_voice and preferred_voice in old_voice_map:
1800
- return old_voice_map[preferred_voice]
1801
-
1802
- lang, emotion = detect_language_and_emotion(title, text)
1803
- lang_map = VOICE_BY_LANG_EMOTION.get(lang, VOICE_BY_LANG_EMOTION['vietnamese'])
1804
- voice, _ = lang_map.get(emotion, lang_map['neutral'])
1805
- return voice
1806
-
1807
-
1808
- def _is_relevant_image(img_url, title, text):
1809
- """Check if an image is relevant to the article content."""
1810
- if not img_url:
1811
- return False
1812
- skip_patterns = ['pixel', 'analytics', 'tracking', '1x1.gif', 'spacer.gif',
1813
- 'logo', 'icon', 'avatar', 'emoji', 'smiley', 'sprite',
1814
- 'advertisement', 'ad-banner', 'sponsored', 'banner-ads']
1815
- img_lower = img_url.lower()
1816
- for p in skip_patterns:
1817
- if p in img_lower:
1818
- return False
1819
- if not any(img_lower.endswith(ext) for ext in ['.jpg', '.jpeg', '.png', '.webp', '.gif']):
1820
- return False
1821
- return True
1822
-
1823
-
1824
- def _filter_relevant_images(images, title, text, max_images=8):
1825
- """Filter and rank images by relevance to article content."""
1826
- if not images:
1827
- return []
1828
- seen = set()
1829
- relevant = []
1830
- for img in images:
1831
- if img in seen:
1832
- continue
1833
- seen.add(img)
1834
- if _is_relevant_image(img, title, text):
1835
- relevant.append(img)
1836
- return relevant[:max_images]
1837
-
1838
-
1839
- def _scrape_article_for_rewrite(url):
1840
- """Scrape article: extract title, paragraphs, RELEVANT images, OG image."""
1841
- try:
1842
- r = req.get(url, headers=_UA_RW, timeout=15, allow_redirects=True)
1843
- r.encoding = 'utf-8'
1844
- soup = BeautifulSoup(r.text, 'lxml')
1845
- for tag in soup.find_all(['script', 'style', 'nav', 'footer', 'aside', 'form']):
1846
- tag.decompose()
1847
- h1 = soup.find('h1')
1848
- ogt = soup.find('meta', property='og:title')
1849
- title = (h1.get_text(strip=True) if h1 else '') or (ogt.get('content', '') if ogt else '')
1850
- ogi = soup.find('meta', property='og:image')
1851
- og_img = ogi.get('content', '') if ogi else ''
1852
- if og_img and og_img.startswith('//'):
1853
- og_img = 'https:' + og_img
1854
- block = None
1855
- for sel in ['article', '.singular-content', '.detail-content', '.fck_detail', '.content-detail', '.knc-content', 'main', '.cms-body', '.article__body']:
1856
- el = soup.select_one(sel)
1857
- if el and len(el.find_all('p')) >= 2:
1858
- block = el
1859
- break
1860
- if not block:
1861
- block = soup.body or soup
1862
- paragraphs = []
1863
- all_images = []
1864
- seen_imgs = set()
1865
- if og_img and og_img not in seen_imgs:
1866
- all_images.append(og_img)
1867
- seen_imgs.add(og_img)
1868
- for el in block.find_all(['p', 'h2', 'h3', 'figure', 'img'], recursive=True):
1869
- if el.name == 'p':
1870
- t = _clean(el.get_text(strip=True))
1871
- if t and len(t) > 40:
1872
- paragraphs.append(t)
1873
- elif el.name in ('figure', 'img'):
1874
- im = el if el.name == 'img' else el.find('img')
1875
- if im:
1876
- src = im.get('data-src') or im.get('src') or im.get('data-original') or ''
1877
- if src and 'base64' not in src:
1878
- if src.startswith('//'):
1879
- src = 'https:' + src
1880
- if src not in seen_imgs:
1881
- all_images.append(src)
1882
- seen_imgs.add(src)
1883
- # Filter to relevant images only
1884
- relevant_images = _filter_relevant_images(all_images, title, ' '.join(paragraphs[:5]))
1885
- return {'title': _clean(title), 'paragraphs': paragraphs, 'images': relevant_images, 'og_img': og_img}
1886
- except Exception:
1887
- return None
1888
-
1889
-
1890
- def _extract_key_points_rw(paragraphs, max_points=5):
1891
- r"""Extract key points from paragraphs - extracts ALL sentences, not just first one.
1892
-
1893
- Fixes: Original regex `^(.+?[.!?])\s` only captured first sentence per paragraph.
1894
- Now splits on all sentence boundaries and takes valid sentences until max_points.
1895
- """
1896
- points = []
1897
-
1898
- for p in paragraphs:
1899
- if len(points) >= max_points:
1900
- break
1901
-
1902
- p = _clean(p)
1903
- if not p:
1904
- continue
1905
-
1906
- # Split paragraph into sentences using Vietnamese + English punctuation
1907
- sentences = re.split(r'(?<=[.!?])\s+(?=[A-ZÀ-Ỹ0-9])', p)
1908
- sentences = [s.strip() for s in sentences if s.strip()]
1909
-
1910
- for sentence in sentences:
1911
- if len(points) >= max_points:
1912
- break
1913
-
1914
- # Clean sentence - remove extra whitespace
1915
- sentence = _clean(sentence)
1916
-
1917
- if len(sentence) < 30:
1918
- continue
1919
-
1920
- # Check for duplicates
1921
- if any(sentence[:60] in existing for existing in points):
1922
- continue
1923
-
1924
- # Ensure sentence ends with punctuation
1925
- if not sentence.endswith(('.', '!', '?')):
1926
- sentence = sentence + '.'
1927
-
1928
- points.append(sentence)
1929
-
1930
- # If no valid sentences found, take chunks from raw text
1931
- if not points:
1932
- raw = '\n'.join(paragraphs)
1933
- for i in range(0, min(len(raw), max_points * 300), 280):
1934
- chunk = _clean(raw[i:i+280])
1935
- if len(chunk) >= 30 and chunk not in points:
1936
- points.append(chunk + ('.' if not chunk.endswith('.') else ''))
1937
- if len(points) >= max_points:
1938
- break
1939
-
1940
- return points
1941
-
1942
-
1943
- @app.post("/api/rewrite_slide")
1944
- async def api_rewrite_slide(request: Request):
1945
- """Fast rewrite as SLIDES - no AI needed, instant response."""
1946
- body = await request.json()
1947
- url = _clean(body.get("url", ""))
1948
- context = body.get("context", "")
1949
- preferred_voice = body.get("voice", "") # Accept custom voice selection
1950
- if not url and not context:
1951
- return JSONResponse({"error": "Cần URL hoặc nội dung"}, status_code=400)
1952
- data = None
1953
- if url and url.startswith("http"):
1954
- data = _scrape_article_for_rewrite(url)
1955
- if not data and context:
1956
- paragraphs = [_clean(p) for p in context.split('\n') if len(_clean(p)) > 40]
1957
- data = {'title': paragraphs[0][:80] if paragraphs else 'Bài viết', 'paragraphs': paragraphs, 'images': [], 'og_img': ''}
1958
- if not data or not data.get('paragraphs'):
1959
- return JSONResponse({"error": "Không đọc được bài viết"}, status_code=422)
1960
- points = _extract_key_points_rw(data['paragraphs'], max_points=12)
1961
- if not points:
1962
- return JSONResponse({"error": "Không tìm được ý chính"}, status_code=422)
1963
- images = data.get('images', [])
1964
- slides = []
1965
- for i, point in enumerate(points):
1966
- img = images[i] if i < len(images) else (images[-1] if images else '')
1967
- if img and 'cdnphoto.dantri' in img:
1968
- img = '/api/proxy/img?url=' + _quote2(img, safe='')
1969
- slides.append({'text': point, 'image': img, 'index': i + 1})
1970
- summary_text = '\n\n'.join([f"• {s['text']}" for s in slides])
1971
-
1972
- # Auto-detect language and emotion
1973
- lang, emotion = detect_language_and_emotion(data['title'], summary_text)
1974
- # Use preferred voice if provided, otherwise auto-detect
1975
- voice = preferred_voice if preferred_voice else get_voice_for_content(data['title'], summary_text)
1976
-
1977
- post = {
1978
- "id": str(int(time.time() * 1000)) + str(_random2.randint(100, 999)),
1979
- "title": data['title'],
1980
- "text": summary_text,
1981
- "img": images[0] if images else '',
1982
- "url": url,
1983
- "kind": "slide_summary",
1984
- "slides": slides,
1985
- "images": images[:10],
1986
- "video": "",
1987
- "voice": voice,
1988
- "emotion": emotion,
1989
- "language": lang,
1990
- "ts": int(time.time())
1991
- }
1992
- posts = _load_wall_posts()
1993
- posts.insert(0, post)
1994
- _save_wall_posts(posts)
1995
- return JSONResponse({"post": post, "slides": slides})
1996
-
1997
-
1998
- @app.post("/api/rewrite_share")
1999
- async def api_rewrite_share(request: Request):
2000
- """Rewrite article and post to Tường AI with SLIDES + AI text."""
2001
- body = await request.json()
2002
- url = _clean(body.get("url", ""))
2003
- ctx = _clean(body.get("context", ""))
2004
- preferred_voice = body.get("voice", "") # Accept custom voice selection
2005
- if not url and not ctx:
2006
- return JSONResponse({"error": "Cần URL hoặc nội dung"}, status_code=400)
2007
- data = None
2008
- if url and url.startswith("http"):
2009
- data = _scrape_article_for_rewrite(url)
2010
- if not data and ctx:
2011
- paragraphs = [_clean(p) for p in ctx.split('\n') if len(_clean(p)) > 40]
2012
- data = {'title': paragraphs[0][:80] if paragraphs else 'Bài viết', 'paragraphs': paragraphs, 'images': [], 'og_img': ''}
2013
- if not data or not data.get('paragraphs'):
2014
- return JSONResponse({"error": "Không đọc được bài viết"}, status_code=422)
2015
- raw_text = '\n'.join(data['paragraphs'])
2016
- if len(raw_text) < 50:
2017
- raw_text = ctx[:14000]
2018
- if len(raw_text) < 50:
2019
- return JSONResponse({"error": "Bài viết quá ngắn"}, status_code=422)
2020
- domain = ''
2021
- try:
2022
- from urllib.parse import urlparse
2023
- domain = urlparse(url).netloc.replace('www.', '')
2024
- except:
2025
- pass
2026
-
2027
- # Generate AI summary text
2028
- ai_text = None
2029
- try:
2030
- import ai_ext
2031
- if hasattr(ai_ext, 'qwen_generate'):
2032
- prompt = f'Tóm tắt đăng Tường AI:\nTiêu đề: {data["title"]}\n{raw_text[:14000]}\n\n4-6 ý chính. Cuối ghi nguồn.'
2033
- ai_text = await ai_ext.qwen_generate(prompt, max_tokens=1000)
2034
- except Exception:
2035
- pass
2036
- if not ai_text or len(ai_text) < 80:
2037
- key_pts = _extract_key_points_rw(data['paragraphs'], max_points=12)
2038
- if key_pts:
2039
- ai_text = '\n\n'.join([f"• {p}" for p in key_pts])
2040
- else:
2041
- ai_text = f"Tóm tắt: {data['title']}\n\n{raw_text[:1200]}\n\nNguồn: {domain}"
2042
-
2043
- # Build slides from key points (FIX: include slides in rewrite_share too!)
2044
- points = _extract_key_points_rw(data['paragraphs'], max_points=12)
2045
- images = data.get('images', [])
2046
- slides = []
2047
- for i, point in enumerate(points):
2048
- img = images[i] if i < len(images) else (images[-1] if images else '')
2049
- if img and 'cdnphoto.dantri' in img:
2050
- img = '/api/proxy/img?url=' + _quote2(img, safe='')
2051
- slides.append({'text': point, 'image': img, 'index': i + 1})
2052
-
2053
- # Auto-detect language and emotion
2054
- lang, emotion = detect_language_and_emotion(data['title'], ai_text)
2055
- # Use preferred voice if provided, otherwise auto-detect
2056
- voice = preferred_voice if preferred_voice else get_voice_for_content(data['title'], ai_text)
2057
-
2058
- post = {
2059
- "id": str(int(time.time() * 1000)) + str(_random2.randint(100, 999)),
2060
- "title": data['title'],
2061
- "text": ai_text,
2062
- "img": images[0] if images else '',
2063
- "url": url,
2064
- "kind": "rewrite",
2065
- "slides": slides,
2066
- "images": images[:10],
2067
- "video": "",
2068
- "voice": voice,
2069
- "emotion": emotion,
2070
- "language": lang,
2071
- "ts": int(time.time())
2072
- }
2073
- posts = _load_wall_posts()
2074
- posts.insert(0, post)
2075
- _save_wall_posts(posts)
2076
- return JSONResponse({"post": post, "slides": slides})
2077
-
2078
-
2079
- @app.post("/api/url_wall")
2080
- async def api_url_wall(request: Request):
2081
- """Submit URL to add to Tường AI."""
2082
- body = await request.json()
2083
- url = _clean(body.get("url", ""))
2084
- if not url or not url.startswith('http'):
2085
- return JSONResponse({"error": "URL không hợp lệ"}, status_code=400)
2086
- # Reuse rewrite_share logic
2087
- req._body = json.dumps({"url": url}).encode()
2088
- return await api_rewrite_share(request)
2089
-
2090
-
2091
- def _bg():
2092
- time.sleep(15)
2093
- while True:
2094
- try:get_wc2026_all()
2095
- except:pass
2096
- time.sleep(90)
2097
- threading.Thread(target=_bg,daemon=True).start()
2098
-
2099
- # ===== AUTO SCHEDULER: rewrite AI + short at 7/13/19 VN time =====
2100
- _AUTO_SCHEDULE_TIMES = [(7, '07:00'), (13, '13:00'), (19, '19:00')]
2101
- _AUTO_LOG = os.path.join(DATA_DIR, 'auto_rewrite_log.json')
2102
-
2103
- def _load_auto_log():
2104
- try:
2105
- if os.path.exists(_AUTO_LOG):
2106
- with open(_AUTO_LOG, 'r') as f:
2107
- return json.load(f)
2108
- except: pass
2109
- return {}
2110
-
2111
- def _save_auto_log(log):
2112
- try:
2113
- tmp = _AUTO_LOG + '.tmp'
2114
- with open(tmp, 'w') as f:
2115
- json.dump(log, f)
2116
- os.replace(tmp, _AUTO_LOG)
2117
- except: pass
2118
-
2119
- async def _auto_fetch_short(post_id):
2120
- """Try to auto-generate a short for a post."""
2121
- try:
2122
- import httpx
2123
- async with httpx.AsyncClient(timeout=180) as cl:
2124
- r = await cl.post(
2125
- f"http://localhost:7860/api/ai/short/{post_id}",
2126
- json={"voice":"vi-VN-HoaiMyNeural","emotion":"neutral","speed":1.2},
2127
- headers={"Content-Type":"application/json"}
2128
- )
2129
- if r.status_code < 300:
2130
- sj = r.json()
2131
- if sj.get('video'):
2132
- posts = _load_wall_posts()
2133
- for p in posts:
2134
- if p.get('id') == post_id:
2135
- p['video'] = sj['video']
2136
- break
2137
- _save_wall_posts(posts)
2138
- return True
2139
- except: pass
2140
- return False
2141
-
2142
- async def _auto_rewrite_one(topic, slot_label, used_urls=None, post_index=0):
2143
- """Rewrite one topic: find articles, summarize, post to wall, trigger short.
2144
- used_urls: shared set to avoid duplicate articles across topics.
2145
- post_index: 0-based index to create multiple posts per topic (0,1,2 = up to 3 posts)."""
2146
- from urllib.parse import quote as _q
2147
- # Get MORE items to support 1-3 posts per topic
2148
- items = _search_all(topic, limit=12)
2149
- # Skip URLs already used by another topic
2150
- if used_urls is not None:
2151
- filtered = [it for it in items if it.get('url') not in used_urls]
2152
- if filtered:
2153
- items = filtered
2154
- if not items or post_index >= len(items):
2155
- return False
2156
-
2157
- # Get article at post_index (0,1,2 for multiple posts)
2158
- item = items[post_index] # post_index allows multiple articles per topic
2159
- url = item.get('url', '')
2160
- title = item.get('title', topic)
2161
- if url and used_urls is not None:
2162
- used_urls.add(url)
2163
- if not url.startswith('http'):
2164
- return False
2165
-
2166
- data = _scrape_article_for_rewrite(url)
2167
- if not data or not data.get('paragraphs'):
2168
- return False
2169
-
2170
- raw_text = '\n'.join(data['paragraphs'])
2171
- ai_text = None
2172
-
2173
- # Try AI generation
2174
- try:
2175
- import ai_ext
2176
- prompt = f"Tóm tắt tin tức (tự động {slot_label}):\nTiêu đề: {data['title']}\n{raw_text[:10000]}\n\n4-6 ý chính dạng bullet. Cuối ghi nguồn."
2177
- ai_text = await ai_ext.qwen_generate(prompt, max_tokens=1000)
2178
- except: pass
2179
-
2180
- if not ai_text or len(ai_text) < 80:
2181
- pts = data['paragraphs'][:6]
2182
- ai_text = '\n\n'.join([f"• {p[:300]}" for p in pts])
2183
- via = item.get('via', '') or urlparse(url).netloc.replace('www.', '')
2184
- ai_text += f"\n\nNguồn tham khảo: {via}"
2185
-
2186
- # Build slides
2187
- images = data.get('images', [])
2188
- pts = data['paragraphs'][:10]
2189
- slides = []
2190
- for i, p in enumerate(pts[:8]):
2191
- img = images[i] if i < len(images) else (images[-1] if images else data.get('og_img', ''))
2192
- slides.append({'text': p[:300], 'image': img, 'index': i + 1})
2193
-
2194
- post_id = str(int(time.time() * 1000)) + str(_random2.randint(100, 999))
2195
- post = {
2196
- "id": post_id, "title": data.get('title', title)[:200],
2197
- "text": ai_text, "img": images[0] if images else data.get('og_img', ''),
2198
- "url": url, "kind": "auto_rewrite", "slides": slides,
2199
- "images": images[:10], "video": "",
2200
- "voice": "vi-VN-HoaiMyNeural", "emotion": "neutral",
2201
- "language": "vietnamese", "ts": int(time.time()),
2202
- "auto_scheduled": True, "slot": slot_label,
2203
- }
2204
-
2205
- posts = _load_wall_posts()
2206
- posts.insert(0, post)
2207
- _save_wall_posts(posts)
2208
-
2209
- # Trigger short generation async
2210
- threading.Thread(target=lambda: asyncio.run(_auto_fetch_short(post_id)), daemon=True).start()
2211
- return True
2212
-
2213
- async def _do_scheduled_run(slot_label):
2214
- """Main scheduled run: 1-3 posts from 3 different HOT topics (3-9 total), no duplicates."""
2215
- print(f"[auto] Starting scheduled rewrite for {slot_label}")
2216
-
2217
- # Get top hot topics, skip duplicates
2218
- all_topics = _get_hot_topics()
2219
- seen_topics = set()
2220
- unique_topics = []
2221
- for t in all_topics:
2222
- kw = t.get('topic', '').lower().strip()
2223
- if kw and len(kw) > 5 and kw not in seen_topics:
2224
- is_dup = False
2225
- for s in seen_topics:
2226
- # Check if one topic is substring of another
2227
- if kw in s or s in kw:
2228
- is_dup = True
2229
- break
2230
- if not is_dup:
2231
- seen_topics.add(kw)
2232
- unique_topics.append(t)
2233
- if len(unique_topics) >= 3:
2234
- break
2235
-
2236
- job_topics = [t['topic'] for t in unique_topics[:3] if t.get('topic')]
2237
- if not job_topics:
2238
- print(f"[auto] No hot topics found, skipping")
2239
- return
2240
-
2241
- print(f"[auto] Running 3 topics: {job_topics}")
2242
-
2243
- # Track used URLs to avoid cross-topic duplicates
2244
- _used_urls = set()
2245
- results = []
2246
-
2247
- # Process each topic, create 1-3 posts per topic
2248
- for jt in job_topics:
2249
- for post_idx in range(3): # Try up to 3 posts per topic
2250
- try:
2251
- ok = await asyncio.wait_for(_auto_rewrite_one(jt, slot_label, _used_urls, post_idx), timeout=120)
2252
- if ok:
2253
- results.append((jt, post_idx, True))
2254
- print(f"[auto] Created post {post_idx+1} for '{jt}'")
2255
- else:
2256
- # No more articles for this topic
2257
- break
2258
- except Exception as e:
2259
- print(f"[auto] Error on '{jt}' post {post_idx}: {e}")
2260
- results.append((jt, post_idx, False))
2261
- await asyncio.sleep(1) # Small delay between posts
2262
-
2263
- # Ensure at least 3 posts total (fallback if needed)
2264
- successful_posts = sum(1 for _, _, ok in results if ok)
2265
- print(f"[auto] Done {slot_label}: {successful_posts} posts created")
2266
-
2267
- # Log
2268
- from datetime import datetime, timezone, timedelta
2269
- VN_TZ_SCHED = timezone(timedelta(hours=7))
2270
- today_str = datetime.now(VN_TZ_SCHED).strftime('%Y-%m-%d')
2271
- log = _load_auto_log()
2272
- if today_str not in log: log[today_str] = {}
2273
- log[today_str][slot_label] = {
2274
- 'time': datetime.now(VN_TZ_SCHED).strftime('%H:%M:%S'),
2275
- 'count': successful_posts,
2276
- 'total': len(job_topics),
2277
- }
2278
- _save_auto_log(log)
2279
-
2280
- def _scheduler_loop():
2281
- """Check every 60s; trigger at 7:00, 13:00, 19:00 VN time.
2282
- On startup, check for any missed slots today and run them immediately."""
2283
- time.sleep(35)
2284
- from datetime import datetime, timezone, timedelta
2285
- VN_TZ_SCHED = timezone(timedelta(hours=7))
2286
-
2287
- _last_run_date = ""
2288
- _last_run_slots = set()
2289
-
2290
- # On startup: check log for missed slots today
2291
- try:
2292
- start_now = datetime.now(VN_TZ_SCHED)
2293
- today_str = start_now.strftime('%Y-%m-%d')
2294
- current_hour = start_now.hour
2295
- current_minute = start_now.minute
2296
- log = _load_auto_log()
2297
- today_log = log.get(today_str, {})
2298
- for h, label in _AUTO_SCHEDULE_TIMES:
2299
- # Run if slot is past (either strictly earlier hour, or same hour but window has passed)
2300
- should_run = False
2301
- if h < current_hour:
2302
- should_run = True
2303
- elif h == current_hour and current_minute > 10:
2304
- should_run = True
2305
- if should_run and label not in today_log:
2306
- print(f"[auto] Detected missed slot {label} (h={h} < now={current_hour}:{current_minute}), running catch-up now")
2307
- _run_scheduled_sync(label)
2308
- _last_run_slots.add(label)
2309
- except Exception as e:
2310
- print(f"[auto] Catch-up check error: {e}")
2311
-
2312
- while True:
2313
- try:
2314
- now = datetime.now(VN_TZ_SCHED)
2315
- today = now.strftime('%Y-%m-%d')
2316
- hour = now.hour
2317
- minute = now.minute
2318
-
2319
- if today != _last_run_date:
2320
- _last_run_date = today
2321
- _last_run_slots = set()
2322
-
2323
- slot = None
2324
- for h, label in _AUTO_SCHEDULE_TIMES:
2325
- if hour == h and 0 <= minute < 5:
2326
- slot = label
2327
- break
2328
-
2329
- if slot and slot not in _last_run_slots:
2330
- _last_run_slots.add(slot)
2331
- _run_scheduled_sync(slot)
2332
- except Exception as e:
2333
- print(f"[auto] Loop error: {e}")
2334
-
2335
- time.sleep(60)
2336
-
2337
- threading.Thread(target=_scheduler_loop, daemon=True, name='auto-rewrite-scheduler').start()
2338
-
2339
- @app.get('/api/debug/auto_schedule')
2340
- async def debug_auto_schedule(slot: str = '07:00'):
2341
- """Manually trigger auto scheduler for debugging."""
2342
- try:
2343
- # Check if we can access the data directory
2344
- log = _load_auto_log()
2345
- topics = _get_hot_topics()[:3]
2346
- job_topics = [t['topic'] for t in topics if t.get('topic')]
2347
- return JSONResponse({
2348
- "slot": slot,
2349
- "log": log,
2350
- "hot_topics": job_topics,
2351
- "wall_posts_count": len(_load_wall_posts()),
2352
- "data_dir_writable": os.access(DATA_DIR, os.W_OK) if os.path.isdir(DATA_DIR) else False,
2353
- "data_dir_exists": os.path.isdir(DATA_DIR),
2354
- })
2355
- except Exception as e:
2356
- return JSONResponse({"error": str(e)}, status_code=500)
2357
-
2358
- def _run_scheduled_sync(slot):
2359
- """Run _do_scheduled_run in a separate event loop (for background thread)."""
2360
- loop = asyncio.new_event_loop()
2361
- asyncio.set_event_loop(loop)
2362
- try:
2363
- loop.run_until_complete(_do_scheduled_run(slot))
2364
- except Exception as e:
2365
- print(f"[auto] Background run error: {e}")
2366
- finally:
2367
- loop.close()
2368
-
2369
- @app.get('/api/debug/trigger_auto')
2370
- async def debug_trigger_auto(slot: str = '19:00'):
2371
- """Trigger _do_scheduled_run in background thread (non-blocking)."""
2372
- threading.Thread(target=_run_scheduled_sync, args=(slot,), daemon=True).start()
2373
- return JSONResponse({"status": "started", "slot": slot})
2374
-
2375
- # ===== SHORTS RSS PROXY ENDPOINT =====
2376
- @app.get("/api/shorts/rss")
2377
- def shorts_rss():
2378
- """Get shorts from YouTube RSS feeds server-side"""
2379
- import xml.etree.ElementTree as ET
2380
- import html as html_lib2
2381
- import re as re2
2382
-
2383
- YOUTUBE_CHANNELS = {
2384
- "baodantri7941": "UC_x5TKhOgd6GhYvv5z4I3jg",
2385
- "baosuckhoedoisongboyte": "UCBsY5fXTQLkF_JnH9kLkL4g",
2386
- }
2387
-
2388
- shorts = []
2389
- seen = set()
2390
-
2391
- for handle, channel_id in YOUTUBE_CHANNELS.items():
2392
- try:
2393
- rss_url = f"https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}"
2394
- r = req.get(rss_url, headers=HEADERS, timeout=15)
2395
- if r.status_code != 200:
2396
- continue
2397
-
2398
- root = ET.fromstring(r.text)
2399
- ns = {
2400
- 'atom': 'http://www.w3.org/2005/Atom',
2401
- 'yt': 'http://www.youtube.com/xml/schemas/2015',
2402
- 'media': 'http://search.yahoo.com/mrss/'
2403
- }
2404
-
2405
- for entry in root.findall('atom:entry', ns)[:30]:
2406
- title_el = entry.find('atom:title', ns)
2407
- title = html_lib2.unescape(title_el.text) if title_el is not None and title_el.text else ''
2408
-
2409
- link_el = entry.find('atom:link', ns)
2410
- link = link_el.get('href', '') if link_el is not None else ''
2411
-
2412
- vid_el = entry.find('yt:videoId', ns)
2413
- vid = vid_el.text if vid_el is not None else ''
2414
-
2415
- if not vid or vid in seen:
2416
- continue
2417
-
2418
- # Check if it's a short
2419
- is_short = '#shorts' in title.lower() or '#short' in title.lower() or '/shorts/' in link
2420
-
2421
- if not is_short:
2422
- desc_el = entry.find('media:description', ns)
2423
- if desc_el is not None and desc_el.text:
2424
- if '#shorts' in desc_el.text.lower():
2425
- is_short = True
2426
-
2427
- if not is_short:
2428
- continue
2429
-
2430
- seen.add(vid)
2431
-
2432
- # Get thumbnail
2433
- thumb = f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg"
2434
- media_group = entry.find('media:group', ns)
2435
- if media_group is not None:
2436
- thumb_el = media_group.find('media:thumbnail', ns)
2437
- if thumb_el is not None:
2438
- thumb = thumb_el.get('url', thumb)
2439
-
2440
- shorts.append({
2441
- 'id': vid,
2442
- 'title': title.replace('#shorts', '').replace('#short', '').strip()[:120],
2443
- 'img': thumb,
2444
- 'link': f'https://www.youtube.com/shorts/{vid}',
2445
- 'channel': handle,
2446
- 'source': 'yt'
2447
- })
2448
-
2449
- if len(shorts) >= 40:
2450
- break
2451
-
2452
- except Exception as e:
2453
- print(f"RSS error for {handle}: {e}")
2454
- continue
2455
-
2456
- return {"shorts": shorts, "count": len(shorts)}
2457
-
2458
- app.mount('/static',StaticFiles(directory=STATIC_DIR),name='vnews_static')'',title:str='',img:str='',post_id:str=''):
2459
  safe_title = _clean(title) if title else 'VNEWS - Tin tức'
2460
  safe_img = _clean(img) if img else ''
2461
  safe_url = _clean(url) if url else '/'
 
636
  </head><body></body></html>''')
637
 
638
  @app.get('/s')
639
+ async def _sh(url:str='',title:str='',img:str='',post_id:str=''):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
640
  safe_title = _clean(title) if title else 'VNEWS - Tin tức'
641
  safe_img = _clean(img) if img else ''
642
  safe_url = _clean(url) if url else '/'