tiendung commited on
Commit
675b3d2
1 Parent(s): acc1395

first commit

Browse files
Files changed (6) hide show
  1. README.md +1 -1
  2. app.py +0 -4
  3. gen_clear_view.py +24 -0
  4. pages_helpers.py +572 -0
  5. pages_notebook.py +258 -0
  6. requirements.txt +7 -0
README.md CHANGED
@@ -5,7 +5,7 @@ colorFrom: purple
5
  colorTo: green
6
  sdk: streamlit
7
  sdk_version: 1.38.0
8
- app_file: app.py
9
  pinned: false
10
  short_description: Tóm tắt và chat với các nội dung từ các links được cung cấp
11
  ---
 
5
  colorTo: green
6
  sdk: streamlit
7
  sdk_version: 1.38.0
8
+ app_file: pages_notebook.py
9
  pinned: false
10
  short_description: Tóm tắt và chat với các nội dung từ các links được cung cấp
11
  ---
app.py DELETED
@@ -1,4 +0,0 @@
1
- import streamlit as st
2
-
3
- x = st.slider('Select a value')
4
- st.write(x, 'squared is', x * x)
 
 
 
 
 
gen_clear_view.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys, json
2
+ from pprint import pprint
3
+
4
+ import llm
5
+
6
+
7
+ try: filename = sys.argv[1]
8
+ except: filename = ".cache/https:/vietnamnet.vn/muc-nuoc-song-cau-o-thai-nguyen-giam-dan-nguoi-dan-tat-bat-don-dep-sau-lu-2321461.html"
9
+
10
+ clean_view_filename = filename + "__clean_view.txt"
11
+
12
+ # if not os.path.exists(clean_view_filename):
13
+ text_filename = filename + ".txt"
14
+
15
+ text = open(text_filename, "rt").read()
16
+
17
+ print(f"Chuẩn bị tạo nội dung cleanview {clean_view_filename}", flush = True)
18
+ clean_view = llm.gen_clean_view(text)
19
+
20
+ with open(clean_view_filename, "wt") as f:
21
+ f.write(clean_view)
22
+
23
+ print("\n- - - CLEAN VIEW - - -\n")
24
+ print(clean_view, flush = True)
pages_helpers.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import trafilatura
2
+ import requests
3
+ import lzma
4
+ import os
5
+ import re
6
+ import time
7
+ from datetime import datetime
8
+ import json
9
+ from pprint import pprint
10
+ import subprocess
11
+
12
+ import config
13
+
14
+ from utils import *
15
+
16
+ from text_utils import *
17
+
18
+ from llm import *
19
+
20
+ from mode_llm import llm_html_to_md, md_to_text, get_html_body_with_soup
21
+
22
+ from crawl4ai import WebCrawler # pip install "crawl4ai @ git+https://github.com/unclecode/crawl4ai.git"
23
+
24
+ # Create an instance of WebCrawler
25
+ crawler = WebCrawler()
26
+
27
+ # Warm up the crawler (load necessary models)
28
+ crawler.warmup()
29
+
30
+ ## Cách lấy cookies và headers sử dụng https://curlconverter.com
31
+ cookies = {
32
+ 'ASP.NET_SessionId': '42i3ivvgk14yd2tnxmddybvq',
33
+ 'Culture': 'vi',
34
+ 'Cookie_VB': 'close',
35
+ 'ruirophaply-covi19': '24',
36
+ 'SLG_G_WPT_TO': 'vi',
37
+ 'G_ENABLED_IDPS': 'google',
38
+ 'SLG_GWPT_Show_Hide_tmp': '1',
39
+ 'SLG_wptGlobTipTmp': '1',
40
+ '__zlcmid': '1NOmxyopHgawxjN',
41
+ '45C5EF': '96780c17-dee3-49b2-9bf7-6335c4348d4f',
42
+ 'vqc': '0',
43
+ }
44
+
45
+ headers = {
46
+ 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
47
+ 'accept-language': 'en-US,en;q=0.9',
48
+ 'cache-control': 'max-age=0',
49
+ 'priority': 'u=0, i',
50
+ 'sec-ch-ua': '"Opera GX";v="111", "Chromium";v="125", "Not.A/Brand";v="24"',
51
+ 'sec-ch-ua-mobile': '?0',
52
+ 'sec-ch-ua-platform': '"Windows"',
53
+ 'sec-fetch-dest': 'document',
54
+ 'sec-fetch-mode': 'navigate',
55
+ 'sec-fetch-site': 'none',
56
+ 'sec-fetch-user': '?1',
57
+ 'sec-gpc': '1',
58
+ 'upgrade-insecure-requests': '1',
59
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 OPR/111.0.0.0',
60
+ # 'User-Agent': "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Mobile Safari/537.36",
61
+ }
62
+
63
+
64
+ def norm_url_and_gen_filename(url):
65
+ url = url.strip() # loại bỏ ký tự trống ở đầu và cuối
66
+ if url[-1] == "/": url = url[:-1] # loại bỏ "/" ở cuối
67
+
68
+ # init filename và tạo sub folder nếu chưa có
69
+ filename = f'.cache/{url}'
70
+ return url, filename
71
+
72
+
73
+ def reset_content(url):
74
+ _, filename = norm_url_and_gen_filename(url)
75
+
76
+ text_filename = filename + ".txt"
77
+ json_filename = filename + ".json"
78
+ html_filename = filename + ".html"
79
+ xz_filename = filename + ".xz"
80
+
81
+ for filename in [
82
+ text_filename,
83
+ json_filename,
84
+ html_filename,
85
+ xz_filename,
86
+ ]:
87
+ cmd = f"rm -rf '{filename}'"; print(cmd)
88
+ subprocess.run(cmd, shell = True)
89
+
90
+
91
+ # from functools import lru_cache
92
+ # @lru_cache(maxsize=128)
93
+ def url_content(url, update_text=None):
94
+ url, filename = norm_url_and_gen_filename(url)
95
+ parts = filename.split("/")
96
+
97
+ for i in range(1, len(parts)):
98
+ path = "/".join(parts[:i])
99
+ # print(path) # DEBUG
100
+ os.makedirs(path, exist_ok=True)
101
+
102
+
103
+ text_filename = filename + ".txt"
104
+ json_filename = filename + ".json"
105
+ html_filename = filename + ".html"
106
+ xz_filename = filename + ".xz"
107
+
108
+
109
+ # Nếu được yêu cầu update nội dung text của url thì update
110
+ if update_text is not None:
111
+
112
+ print("\nUPDATE TEXT", filename)
113
+
114
+ text, noise_ratio, max_noise = normalize_text(update_text, get_noise_info = True)
115
+
116
+ # update meta, Lưu lại text và meta
117
+ meta = json.load(open(json_filename))
118
+
119
+ meta["updated_at"] = str(datetime.now())
120
+ meta["updates_count"] += 1
121
+
122
+ meta["noise_ratio"] = noise_ratio
123
+ meta["max_noise"] = max_noise
124
+
125
+ # Cắt ngắn text nếu đầu vào quá dài
126
+ text = cut_if_too_long(text, meta)
127
+
128
+ with open(json_filename, "wt") as f:
129
+ f.write(json.dumps(meta, ensure_ascii = False))
130
+
131
+ with open(text_filename, "wt") as f:
132
+ f.write(text)
133
+
134
+ # gọi gen_clear_view.py (chạy chậm) ở process riêng
135
+ get_clear_view(filename)
136
+
137
+ # Re-gen llm contents
138
+ get_llm_gen_contents(url, use_cache = False)
139
+
140
+ print(CYAN,end=""); print(meta); print(RESET,end="", flush=True)
141
+
142
+
143
+ # Nếu tồn tại text_filename thì trả về,
144
+ # đây có thể là nội dung text đã được chỉnh sửa nên ưu tiên trả về trước
145
+ if os.path.exists(text_filename):
146
+ print("\nGOT TEXT", filename, flush=True)
147
+
148
+ norm_text = open(text_filename, "rt").read()
149
+ return norm_text
150
+
151
+
152
+ html = None
153
+ # Thử đọc nội dung html đã được cache
154
+ if os.path.exists(xz_filename):
155
+ try:
156
+ html = lzma.open(xz_filename,"rt").read()
157
+ print("\nGOT HTML", filename, flush=True)
158
+ except:
159
+ pass
160
+
161
+
162
+
163
+ blacklist = """
164
+ Your connection is not private
165
+ -----BEGIN CERTIFICATE-----
166
+ """.strip().split("\n")
167
+
168
+
169
+ ## Thử các cách lấy HTML: requests vs crawl4ai vs reader
170
+ get_html_method = "requests"
171
+ if html is None:
172
+ # Thử lần 1 bằng requests
173
+ print("\nGET HTML", filename, flush=True)
174
+
175
+ try:
176
+ html = requests.get(url, cookies=cookies, headers=headers)
177
+ html = str(html.text)
178
+
179
+ # Lưu lại nội dung html vào xz_filename
180
+ with lzma.open(xz_filename, "wt") as f: f.write(html)
181
+
182
+ except Exception as e:
183
+ print(f"!!! REQUESTS Error {e} !!!")
184
+
185
+ if isinstance(html, str):
186
+ for x in blacklist:
187
+ if x in html:
188
+ print(f"--{x}--")
189
+ i = html.find(x)
190
+ print(f"{RED}!!! REQUESTS đọc lỗi {html[i-30:i+200]} !!!{RESET}")
191
+ html = None
192
+ break
193
+
194
+
195
+ meta = None
196
+ if html is None or len(html) < 500:
197
+ # Thử lần 2 bằng CRAWL4AI
198
+ print("GET HTML CRAWL4AI", filename, flush=True)
199
+ get_html_method = "crawl4ai"
200
+
201
+ try:
202
+ result = crawler.run(url=url)
203
+ html = result.html
204
+
205
+ # Lưu lại nội dung html vào xz_filename
206
+ with lzma.open(xz_filename, "wt") as f: f.write(html)
207
+
208
+ # {'title': 'Ngập úng và thiệt hại trên 202.000 ha lúa | baotintuc.vn', 'description': 'Thống kê từ Bộ Nông nghiệp và Phát triển nông thôn, tính đến sáng 13/9, có trên 202.000 ha lúa, gần 39.300 ha hoa màu bị ngập úng, thiệt hại do ảnh hưởng của bão số 3.', 'keywords': None, 'author': 'baotintuc.vn', 'og:type': 'article', 'og:url': 'https://baotintuc.vn/xa-hoi/ngap-ung-va-thiet-hai-tren-202000-ha-lua-20240913095621343.htm', 'og:image': 'https://cdnmedia.baotintuc.vn/Upload/EqV5H9rWgvy9oNikwkHLXA/files/13092024-bao-1.jpg', 'og:image:url': 'https://cdnmedia.baotintuc.vn/Upload/EqV5H9rWgvy9oNikwkHLXA/files/13092024-bao-1.jpg', 'og:image:secure_url': 'https://cdnmedia.baotintuc.vn/Upload/EqV5H9rWgvy9oNikwkHLXA/files/13092024-bao-1.jpg', 'og:image:width': '460', 'og:image:height': '345', 'og:title': 'Ngập úng và thiệt hại trên 202.000 ha lúa', 'og:description': 'Thống kê từ Bộ Nông nghiệp và Phát triển nông thôn, đến sáng 13/9, có trên 202.000 ha lúa, gần 39.300 ha hoa màu bị ngập úng, thiệt hại do ảnh hưởng của bão số 3.', 'twitter: card': 'summary_large_image', 'twitter: image': 'https://cdnmedia.baotintuc.vn/Upload/EqV5H9rWgvy9oNikwkHLXA/files/13092024-bao-1.jpg'}
209
+ meta = dict(result.metadata)
210
+
211
+ for key in result.metadata.keys():
212
+ if "og:" in key or "twitter:" in key:
213
+ meta.pop(key)
214
+
215
+ except Exception as e:
216
+ print(f"!!! CRAWL4AI Error {e} !!!")
217
+
218
+ if isinstance(html, str):
219
+ for x in blacklist:
220
+ if x in html:
221
+ i = html.find(x)
222
+ print(f"{RED}!!! CRAWL4AI đọc lỗi {html[i-30:i+200]} !!!{RESET}")
223
+ html = None
224
+ meta = {}
225
+ break
226
+
227
+
228
+ if html is None or len(html) < 500:
229
+ # Thử lần 3 bằng reader api
230
+ print("GET HTML READER", filename, flush=True)
231
+ get_html_method = "reader"
232
+
233
+ try:
234
+ reader_url = "https://r.jina.ai/" + url
235
+ # Use below header make https://jina.ai/reader return text not markdown by default
236
+ html = requests.get(reader_url, headers = { 'X-Return-Format': 'html', }).text
237
+
238
+ # Lưu lại nội dung html vào xz_filename
239
+ with lzma.open(xz_filename, "wt") as f: f.write(html)
240
+
241
+ except Exception as e:
242
+ print(f"!!! READER Error {e} !!!")
243
+
244
+
245
+ if isinstance(html, str):
246
+ for x in blacklist:
247
+ if x in html:
248
+ i = html.find(x)
249
+ print(f"{RED}!!! READER đọc lỗi {html[i-30:i+200]} !!!{RESET}")
250
+ html = None
251
+ break
252
+
253
+
254
+ ## Thử các cách extract text: trafilatura vs llm vs reader
255
+ extract_method = "trafilatura"
256
+ # https://trafilatura.readthedocs.io/en/latest/corefunctions.html#extract
257
+ try:
258
+ text = trafilatura.extract(html,
259
+ # favor_recall = True,
260
+ include_tables = True,
261
+ include_comments = False,
262
+ with_metadata = False,
263
+ )
264
+ except:
265
+ text = ""
266
+
267
+ if meta is None: # Có thể meta đã đc lấy ở crawl4ai
268
+ try:
269
+ meta = trafilatura.extract(html, only_with_metadata = True)
270
+ if meta and len(meta) > 0:
271
+ # print(meta); input() # DEBUG
272
+ meta = meta.split("---")[1]
273
+ splits = re.findall(r'\S+: [^\n]+', meta)
274
+ meta = { x.split(": ", 1)[0].strip() : x.split(": ", 1)[1].strip() for x in splits }
275
+ else:
276
+ meta = {}
277
+ except:
278
+ meta = {}
279
+
280
+
281
+ # Chuẩn hóa text
282
+ if text is None: text = ""
283
+ text, noise_ratio, max_noise = normalize_text(text, get_noise_info = True)
284
+ print(f">>> {RED}noise_ratio {pretty_num(noise_ratio)}, max_noise {max_noise}{RESET}")
285
+
286
+
287
+ MEANINGFUL = 500
288
+ MAX_NOISE_RATIO = 0.3
289
+
290
+ too_short = ( len(text) < MEANINGFUL )
291
+ too_noise = ( noise_ratio > MAX_NOISE_RATIO or max_noise > MEANINGFUL )
292
+
293
+ # ko lấy đc text hoặc text quá ngắn (cào trượt), hoặc text quá noise
294
+ if text is None or too_short or too_noise:
295
+ # Lấy text thông qua phương pháp khác
296
+ print("!!! Đoạn text dưới do trafilatura triết xuất có vấn đề?")
297
+ print("too short", too_short)
298
+ print("too noise", too_noise)
299
+ print("- - - "*6)
300
+ print(f"{YELLOW}{text}{RESET}")
301
+ print("- - - "*6)
302
+
303
+ print("!!! Dùng Jina Reader ...")
304
+ reader_url = "https://r.jina.ai/" + url
305
+ # Use below header make https://jina.ai/reader return text not markdown by default
306
+ reader_text = requests.get(reader_url, headers = { 'X-Return-Format': 'text', }).text
307
+ reader_text, reader_noise_ratio, reader_max_noise = normalize_text(reader_text, get_noise_info = True)
308
+
309
+ # Chuẩn hóa text
310
+ reader_text, reader_noise_ratio, reader_max_noise = normalize_text(reader_text, get_noise_info = True)
311
+
312
+ reader_too_noise = ( reader_noise_ratio > MAX_NOISE_RATIO or reader_max_noise > MEANINGFUL )
313
+
314
+ print(f">>> {RED}reader_noise_ratio {pretty_num(reader_noise_ratio)}, reader_max_noise {reader_max_noise}{RESET}")
315
+ print(f">>> {RED}reader_too_noise {reader_too_noise}{RESET}")
316
+
317
+ signal = int( len(text) * (1 - noise_ratio) ) + 1
318
+ reader_signal = int( len(reader_text) * (1 - reader_noise_ratio) ) + 1
319
+
320
+ samesame = ( abs(signal - reader_signal) / reader_signal ) < 0.2
321
+ print(f">>> {RED}samesame {samesame}, original signal {pretty_num(signal)}, reader_signal {pretty_num(reader_signal)}{RESET}")
322
+
323
+ # Nếu bản gốc quá ngắn nhưng bản reader quá noise thì thà chọn ngắn còn hơn
324
+ original_too_shot_but_reader_too_noise = (
325
+ too_short and (samesame or reader_noise_ratio >= 0.5 )
326
+ )
327
+
328
+ original_too_noise_but_reader_even_more_noise = (
329
+ too_noise and noise_ratio < reader_noise_ratio and max_noise < reader_max_noise
330
+ )
331
+
332
+ if original_too_shot_but_reader_too_noise:
333
+ print("!!! reader quá noise, chọn bản trafilatura too_short còn hơn.")
334
+
335
+ if original_too_noise_but_reader_even_more_noise:
336
+ print("!!! reader còn noise hơn bản trafilatura, bỏ qua.")
337
+
338
+
339
+ if not original_too_shot_but_reader_too_noise and \
340
+ not original_too_noise_but_reader_even_more_noise:
341
+
342
+ choose_original_text = False
343
+
344
+ if reader_too_noise: # vẫn còn noisy lắm, thử dùng readability.js
345
+
346
+ if html is not None and len(html) > 200:
347
+
348
+ html_filename = filename + ".html"
349
+ with open(html_filename, "wt") as f:
350
+ f.write(html)
351
+
352
+ abi_text = subprocess.run(
353
+ f"node node_readability.js '{html_filename}' '{url}'",
354
+ shell=True,
355
+ capture_output=True,
356
+ ).stdout.decode('utf-8')
357
+
358
+ abi_text, abi_noise_ratio, abi_max_noise = \
359
+ normalize_text(abi_text, get_noise_info = True)
360
+
361
+ if abi_max_noise < reader_max_noise:
362
+ print(GREEN, ">>>", abi_text, "<<<", RESET)
363
+
364
+ if len(abi_text) < len(reader_text) and len(text) < len(reader_text): # chuộng text ngắn
365
+ choose_original_text = True
366
+
367
+
368
+ if not choose_original_text:
369
+
370
+ extract_method = "reader"
371
+ text = reader_text
372
+ noise_ratio = reader_noise_ratio
373
+ max_noise = reader_max_noise
374
+
375
+
376
+ # update meta, Lưu lại text và meta
377
+ meta["url"] = url
378
+ meta["get_html_method"] = get_html_method
379
+ meta["extract_method"] = extract_method
380
+ meta["created_at"] = str(datetime.now())
381
+ meta["updates_count"] = 0
382
+ meta["noise_ratio"] = noise_ratio
383
+ meta["max_noise"] = max_noise
384
+ meta["text_origin_len"] = len(text)
385
+
386
+ if "hostname" in meta: meta.pop("hostname")
387
+ if "sitename" in meta: meta.pop("sitename")
388
+
389
+ # Thêm title và description vào text (nếu có)
390
+ norm_text = normalize_text(text)
391
+ text = add_title_desc_to_text(norm_text, meta)
392
+
393
+ # Cắt ngắn text nếu đầu vào quá dài
394
+ text = cut_if_too_long(text, meta)
395
+
396
+ print(CYAN,end=""); print(meta); print(RESET,end="")
397
+
398
+ with open(json_filename, "wt") as f:
399
+ f.write(json.dumps(meta, ensure_ascii = False))
400
+
401
+ with open(text_filename, "wt") as f:
402
+ f.write(text)
403
+
404
+ get_clear_view(filename)
405
+ get_llm_gen_contents(url, use_cache = False)
406
+
407
+ return text
408
+
409
+
410
+ def get_clear_view(filename):
411
+ # gọi gen_clear_view.py (chạy chậm) ở process riêng
412
+ subprocess.run(f"nohup python3 gen_clear_view.py '{filename}' &", shell = True)
413
+ import time; time.sleep(1) # chờ 1 giây
414
+
415
+
416
+ def cut_if_too_long(text, meta, max_words = config.text_max_words):
417
+ words = text.split()
418
+
419
+ if len(words) > max_words:
420
+
421
+ words = words[ : max_words]
422
+ threshold = len(" ".join(words))
423
+
424
+ meta["text_cutoff"] = True
425
+ meta["text_cutoff_len"] = threshold
426
+
427
+ return text[ : threshold ]
428
+
429
+ else:
430
+ return text
431
+
432
+
433
+ def add_title_desc_to_text(text, meta):
434
+ content = []
435
+ title = meta["title"] if "title" in meta else None
436
+ description = meta["description"] if "description" in meta else None
437
+
438
+ if title is not None and len(title) > 5:
439
+ content.append(f"**title**: {title}")
440
+
441
+ if description is not None and len(description) > 10:
442
+ content.append(f"**description**: {description}")
443
+
444
+ content.append(text)
445
+ return "\n\n".join(content)
446
+
447
+
448
+
449
+ def normalize_text(text, get_noise_info = False):
450
+ text = text.strip()
451
+ chunks = re.split(r'\s*(?:\n\s*)+', text, flags = re.MULTILINE)
452
+ text = "\n\n".join([ x for x in chunks if len(x) > 20 ])
453
+
454
+ if get_noise_info:
455
+ noise_len = 1
456
+ total_len = 1
457
+
458
+ max_noise = 0
459
+ continuous_noise = 0
460
+ for x in chunks:
461
+ n = len(x)
462
+ total_len += n
463
+
464
+ if n < 80:
465
+ noise_len += n
466
+ continuous_noise += n
467
+ if continuous_noise > max_noise:
468
+ max_noise = continuous_noise
469
+ else:
470
+ continuous_noise = 0
471
+
472
+ noise_ratio = noise_len / total_len
473
+ return text, noise_ratio, max_noise
474
+ else:
475
+ return text
476
+
477
+
478
+ def get_clean_view(url):
479
+ url, filename = norm_url_and_gen_filename(url)
480
+ clean_view_filename = filename + "__clean_view.txt"
481
+
482
+ if os.path.exists(clean_view_filename):
483
+ return open(clean_view_filename, "rt").read()
484
+ else:
485
+ return None
486
+
487
+
488
+ def get_meta(url):
489
+ url, filename = norm_url_and_gen_filename(url)
490
+ json_filename = filename + ".json"
491
+ return json.load(open(json_filename))
492
+
493
+
494
+ TAGS = "keyphrases figures summary".split()
495
+ ###
496
+ def get_llm_gen_contents(url, use_cache = True):
497
+ url, filename = norm_url_and_gen_filename(url)
498
+ json_filename = filename + ".json"
499
+ text_filename = filename + ".txt"
500
+
501
+ if os.path.exists(json_filename):
502
+ meta = json.load(open(json_filename, "rt"))
503
+
504
+ generated = ( "llm_generated" in meta )
505
+
506
+ if not use_cache or not generated:
507
+
508
+ text = open(text_filename, "rt").read()
509
+ marked_text, chunks = add_chunk_markers(text, para = True)
510
+
511
+ raw = extract_keyphrases_figures_summary(marked_text)
512
+ result = extract_xmls(raw, TAGS)
513
+
514
+ result["raw"] = raw
515
+ meta["llm_generated"] = result
516
+
517
+ with open(json_filename, "wt") as f:
518
+ f.write(json.dumps(meta, ensure_ascii = False))
519
+
520
+ return meta["llm_generated"]
521
+
522
+ else:
523
+ return {
524
+ "summary": "Tóm tắt nội dung ... văn bản nói về ...",
525
+ "keyphrases": ["keywords 1", "keywords 2", "keywords 3"]
526
+ }
527
+
528
+
529
+ default_urls_input = """
530
+ https://thuvienphapluat.vn/phap-luat/ho-so-dien-tu-thuc-hien-thu-tuc-hanh-chinh-la-gi-huong-dan-chuan-bi-va-nop-ho-so-dien-tu-khi-thuc-h-155754-140107.html
531
+ https://video.vnexpress.net/bon-ngay-chong-choi-lu-ngap-gan-3-m-cua-nguoi-dan-thai-nguyen-4791440.html
532
+ http://danvan.vn/Home/Tin-hoat-dong/Ban-dan-van/18706/Ban-Dan-van-Trung-uong-va-Hoi-Chu-thap-do-Viet-Nam-tham-tang-qua-nhan-dan-bi-anh-huong-bao-so-3-tai-Thai-Nguyen
533
+ https://baodauthau.vn/thai-nguyen-144-ty-dong-nang-cap-duong-cach-mang-thang-8-tp-song-cong-post164486.html
534
+ https://baothainguyen.vn/chinh-tri/202409/chu-tich-quoc-hoi-tran-thanh-man-lam-viec-voi-tinh-thai-nguyen-ve-cong-tackhac-phuc-hau-qua-bao-so-3-3f9253f/
535
+ https://baothainguyen.vn/giao-duc/202409/dam-bao-dieu-kien-de-hoc-sinh-tro-lai-truong-cham-nhat-ngay-16-9-9742985/
536
+ https://baothainguyen.vn/tai-nguyen-moi-truong/202409/khu-khuan-dien-rong-nhung-vung-bi-ngap-lut-tai-tp-thai-nguyen-585273d/
537
+ https://baothainguyen.vn/thoi-su-thai-nguyen/202409/dien-luc-tp-thai-nguyen-no-luccap-dien-tro-lai-cho-tren-2000-hotrong-ngay-12-9-da21a20/
538
+ https://baothainguyen.vn/xa-hoi/202409/tao-sinh-ke-giam-ngheo-vung-dong-bao-dan-toc-thieu-so-b8f041c/
539
+ https://baotintuc.vn/xa-hoi/ngap-ung-va-thiet-hai-tren-202000-ha-lua-20240913095621343.htm
540
+ https://daidoanket.vn/thai-nguyen-hai-nguoi-tu-vong-thiet-hai-hon-600-ty-dong-do-bao-yagi-10290104.html
541
+ https://dangcongsan.vn/xay-dung-dang/thai-nguyen-cong-bo-cac-quyet-dinh-ve-cong-tac-can-bo-677747.html
542
+ https://danviet.vn/62-y-bac-si-cua-binh-dinh-den-thai-nguyen-yen-bai-quyet-tam-cung-dong-bao-vuot-qua-kho-khan-20240913101402511.htm
543
+ https://laodong.vn/thoi-su/chu-tich-quoc-hoi-kiem-tra-cong-tac-khac-phuc-hau-qua-mua-lu-o-thai-nguyen-1393445.ldo
544
+ https://nhandan.vn/anh-chu-tich-quoc-hoi-tran-thanh-man-kiem-tra-cong-tac-khac-phuc-hau-qua-bao-so-3-tai-tinh-thai-nguyen-post830447.html
545
+ https://nld.com.vn/toi-7-gio-13-9-336-nguoi-chet-va-mat-tich-hon-130-ngan-nguoi-dan-phai-di-doi-do-bao-lu-196240913101124546.htm
546
+ https://phunuvietnam.vn/thai-nguyen-hoi-vien-phu-nu-chung-tay-khac-phuc-hau-qua-ngap-lut-20240912154801867.htm
547
+ https://phunuvietnam.vn/thai-nguyen-trien-khai-cong-tac-phong-chong-dich-sau-thien-tai-20240912174641866.htm
548
+ https://thainguyen.dcs.vn/hoat-dong-cua-cac-dang-bo/dang-bo-tp-thai-nguyen/hoi-nghi-ban-thuong-vu-thanh-uy-thai-nguyen-lan-thu-102-857.html
549
+ https://thainguyen.dms.gov.vn/tin-chi-tiet/-/chi-tiet/thai-nguyen-%C4%91am-bao-nguon-hang-hoa-phuc-vu-nhan-dan-89820-1404.html
550
+ https://thuonghieucongluan.com.vn/thai-nguyen-tiep-nhan-5-tan-gao-ho-tro-nhan-dan-bi-anh-huong-ngap-lut-a235642.html
551
+ https://tienphong.vn/nam-thanh-nien-o-thai-nguyen-bi-lu-cuon-khi-di-bat-ca-post1672693.tpo
552
+ https://tienphong.vn/ngan-hang-dau-tien-cong-bo-giam-lai-suat-cho-vay-sau-bao-so-3-post1672728.tpo
553
+ https://tuoitre.vn/chu-tich-quoc-hoi-tran-thanh-man-trao-30-ti-dong-ho-tro-khac-phuc-bao-lu-tai-thai-nguyen-20240912191724375.htm
554
+ https://tuoitre.vn/sau-lu-nguoi-dan-thai-nguyen-noi-chua-bao-gio-bun-ngap-nhieu-den-vay-202409121653144.htm
555
+ https://vietnamnet.vn/muc-nuoc-song-cau-o-thai-nguyen-giam-dan-nguoi-dan-tat-bat-don-dep-sau-lu-2321461.html
556
+ https://vtcnews.vn/trieu-nu-cuoi-huong-ve-thai-nguyen-sau-con-bao-ar895714.html
557
+ """.strip()
558
+
559
+ default_urls_input = """
560
+ https://vnexpress.net/sam-altman-ai-thong-minh-hon-con-nguoi-trong-vai-nghin-ngay-toi-4796649.html
561
+ https://vnexpress.net/may-tram-chay-ai-gia-tram-trieu-dong-tai-viet-nam-4796490.html
562
+ https://www.vngcloud.vn/blog/what-are-large-language-models
563
+ https://arxiv.org/html/2408.16737v1
564
+ https://arxiv.org/html/2409.15700v1
565
+ https://arxiv.org/html/2409.09916v1
566
+ https://arxiv.org/html/2409.06903v1
567
+ https://arxiv.org/html/2409.12558v1
568
+ https://arxiv.org/html/2409.10516v2
569
+ https://rlhflow.github.io/posts/2024-05-29-multi-objective-reward-modeling
570
+ https://arxiv.org/html/2405.07863v2
571
+ https://arxiv.org/html/2406.12845
572
+ """.strip()
pages_notebook.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import html
3
+ import uuid
4
+ import urllib
5
+
6
+ import streamlit as st
7
+ from pages.sticky_header import sticky_container
8
+
9
+ import sys; sys.path.append('../')
10
+ from pages_helpers import *
11
+ from text_utils import *
12
+
13
+ import config
14
+
15
+ # Kích hoạt chế độ toàn màn hình (full width)
16
+ st.set_page_config(layout="wide")
17
+
18
+
19
+ ###################################################################
20
+
21
+ # Define HTML and CSS for the tooltip
22
+ html_content = """
23
+ <style>
24
+ .tooltip {
25
+ position: relative;
26
+ display: inline-block;
27
+ cursor: pointer;
28
+ }
29
+
30
+ .tooltip .tooltiptext {
31
+ font-weight: normal;
32
+ visibility: hidden;
33
+ width: 320px;
34
+ background-color: #eadef9;
35
+ color: black;
36
+ text-align: left;
37
+ border-radius: 6px;
38
+ padding: 0.6em;
39
+ position: absolute;
40
+ z-index: 1;
41
+ top: 100%;
42
+ left: 50%;
43
+ margin-left: -60px;
44
+ opacity: 20%;
45
+ transition: opacity 0.3s;
46
+ }
47
+
48
+ .tooltip:hover .tooltiptext {
49
+ visibility: visible;
50
+ opacity: 1;
51
+ }
52
+ </style>
53
+ """
54
+ st.markdown(html_content, unsafe_allow_html=True)
55
+
56
+ def javascript(source: str) -> None:
57
+ div_id = uuid.uuid4()
58
+
59
+ st.markdown(f"""
60
+ <div style="display:none" id="{div_id}">
61
+ <iframe src="javascript: \
62
+ var script = document.createElement('script'); \
63
+ script.type = 'text/javascript'; \
64
+ script.text = {html.escape(repr(source))}; \
65
+ var div = window.parent.document.getElementById('{div_id}'); \
66
+ div.appendChild(script); \
67
+ div.parentElement.parentElement.parentElement.style.display = 'none'; \
68
+ "/>
69
+ </div>
70
+ """, unsafe_allow_html=True)
71
+
72
+
73
+ ###################################################################
74
+
75
+
76
+ if "urls_input" not in st.session_state:
77
+ st.session_state["urls_input"] = normalize_text(default_urls_input)
78
+
79
+ tab1, tab2 = st.tabs(["Danh sách các liên kết", "Chỉnh sửa danh sách các liên kết"])
80
+
81
+
82
+ with tab2:
83
+ edited_urls_input = st.text_area(
84
+ "Thêm hoặc bớt các liên kết",
85
+ value=st.session_state["urls_input"],
86
+ height=500,
87
+ key=f"edit_urls_input"
88
+ )
89
+
90
+ if st.button("Cập nhật thay đổi"):
91
+ st.session_state["urls_input"] = normalize_text(edited_urls_input)
92
+ st.session_state['selected_url'] = None
93
+ st.success("Đã lưu thay đổi!")
94
+ st.rerun()
95
+
96
+
97
+ with tab1:
98
+ # Giao diện Streamlit với 2 cột bằng nhau, chiếm trọn màn hình
99
+ col1, col2 = st.columns([3, 6])
100
+
101
+ urls = st.session_state["urls_input"].strip().split()
102
+
103
+ ##############
104
+ with col1:
105
+ ##############
106
+ # Hiển thị danh sách các URL và cho phép chọn
107
+ for idx, url in enumerate(urls):
108
+ url_preview = url[:50] + "..." # rút gọn
109
+ if st.button(url_preview, key = idx):
110
+ st.session_state['selected_url'] = url
111
+
112
+
113
+ ##############
114
+ with col2:
115
+ ##############
116
+ if 'selected_url' not in st.session_state or st.session_state["selected_url"] is None:
117
+ "Nhấn vào url để hiển thị nội dung"
118
+
119
+ else:
120
+ selected_url = st.session_state['selected_url']
121
+ fresh_text = url_content(selected_url)
122
+ _, chunks = add_chunk_markers(fresh_text, para = True)
123
+
124
+ # Hiển thị url
125
+ st.markdown(selected_url)#, help="tooltip")
126
+
127
+ # Hiển thị summary và nhận xét
128
+ text = url_content(selected_url) # tuy ko dùng nhưng phải lấy text trước thì mới có cái để summ
129
+ llm_generated = get_llm_gen_contents(selected_url)
130
+
131
+ if "summary" in llm_generated:
132
+ summ = llm_generated["summary"]
133
+
134
+ # Hiển thị phần tóm tắt văn bản
135
+ summ = re.sub(r'<cite>((?:\[\d+\])+)</cite>', r' \1', summ)
136
+ summ_sub = rf'<strong><a href="#" sourceid="chunk_\1" target="" class="cite tooltip">[\1]\
137
+ <span class="tooltiptext">__chunk_\1_text__</span></a></strong>'
138
+
139
+ summ = re.sub(r'\[(\d+)\]', summ_sub, summ)
140
+ for idx, chunk in enumerate(chunks):
141
+ chunk = re.sub(r'https?://', '', chunk, flags = re.IGNORECASE | re.MULTILINE)
142
+ summ = summ.replace(f"__chunk_{idx}_text__", f"{chunk}")
143
+
144
+ st.write(summ, unsafe_allow_html = True)
145
+
146
+
147
+ tab1, tab2, tab3, tab4, tab5 = st.tabs([
148
+ "Xem nội dung",
149
+ "Bản tinh gọn",
150
+ "Chỉnh sửa nội dung",
151
+ "Cào lại nội dung",
152
+ "Xóa nội dung",
153
+ ])
154
+
155
+
156
+ ######################
157
+ with tab1:
158
+ ######################
159
+ marked_chunks = [ f'<span id="chunk_{i}" class="source">{c}</span>' for i, c in enumerate(chunks) ]
160
+
161
+ content = "\n\n".join(marked_chunks)
162
+
163
+ st.write(content, unsafe_allow_html = True)
164
+
165
+ # Nhúng javascript sau cùng để hilite citing
166
+ # https://discuss.streamlit.io/t/injecting-js/22651/6
167
+ javascript("""
168
+ function removeHilite() {
169
+ document.querySelectorAll('.hilite').forEach(element => {
170
+ element.classList.remove('hilite');
171
+ element.setAttribute("style", "background: #FFFFFF;")
172
+ });
173
+ }
174
+
175
+ setTimeout(() => {
176
+
177
+ console.log("BẮT ĐẦU NHÚNG JS");
178
+ removeHilite();
179
+
180
+ document.querySelectorAll('.cite').forEach(element => {
181
+
182
+ console.log('Element:', element);
183
+ element.addEventListener('click', () => {
184
+
185
+ let chunkId = element.getAttribute("sourceid");
186
+ removeHilite();
187
+
188
+ let hiliteElem = document.getElementById(chunkId);
189
+ console.log('Element to hilite:', chunkId, hiliteElem);
190
+
191
+ hiliteElem.classList.add('hilite');
192
+ hiliteElem.setAttribute("style", "background: #eadef9;")
193
+
194
+ // Scroll into view
195
+ hiliteElem.scrollIntoView({ behavior: "smooth", block: "center" });
196
+ });
197
+ });
198
+
199
+ }, 200);
200
+ """.strip())
201
+
202
+
203
+ ######################
204
+ with tab2:
205
+ ######################
206
+ clean_view = get_clean_view(selected_url)
207
+ if clean_view is None:
208
+ st.write("Hệ thống đang tạo nội dung, vui lòng chờ ...")
209
+
210
+ if st.button("Reload"):
211
+ st.rerun()
212
+ else:
213
+ st.write(clean_view)
214
+
215
+ if st.button("Dùng bản tinh gọn làm nội dung"):
216
+ url_content(selected_url, update_text = clean_view)
217
+ st.success("Đã lưu thay đổi!")
218
+ st.rerun()
219
+
220
+
221
+ ######################
222
+ with tab3:
223
+ ######################
224
+ fresh_text = url_content(selected_url)
225
+
226
+ edited_text = st.text_area(
227
+ f"*Lưu ý: Văn bản không được dài quá {config.text_max_words} từ, nếu quá sẽ tự động cắt bỏ*",
228
+ value =fresh_text,
229
+ height = 500,
230
+ key = f"edit_{selected_url}"
231
+ )
232
+
233
+ if st.button("Lưu thay đổi"):
234
+ url_content(selected_url, update_text = edited_text)
235
+ st.success("Đã lưu thay đổi!")
236
+ st.rerun()
237
+
238
+
239
+ ######################
240
+ with tab4:
241
+ ######################
242
+ if st.button("Bạn chắc chắn muốn cào lại nội dung?"):
243
+ reset_content(selected_url)
244
+ st.rerun()
245
+
246
+
247
+ ######################
248
+ with tab5:
249
+ ######################
250
+ if st.button("Bạn chắc chắn muốn xóa nội dung?"):
251
+ urls_input = st.session_state["urls_input"]
252
+ urls_input = urls_input.replace(selected_url, "")
253
+
254
+ st.session_state["urls_input"] = normalize_text(urls_input)
255
+ st.session_state['selected_url'] = None
256
+
257
+ st.success("Đã xóa nội dung!")
258
+ st.rerun()
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ google-generativeai
2
+ together
3
+
4
+ streamlit
5
+ trafilatura
6
+ markdown
7
+ selenium