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
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ from urllib.parse import urljoin
5
+
6
+
7
+ def google_search(query):
8
+ """
9
+ Lấy tất cả các URL từ một trang HTML và lọc ra các URL có dạng
10
+ 'https://www.google.com/url?q=https://'.
11
+
12
+ Args:
13
+ url: URL của trang web.
14
+
15
+ Returns:
16
+ Danh sách các URL đã được lọc.
17
+ """
18
+ url = f"https://www.google.com/search?q={query}"
19
+ try:
20
+ response = requests.get(url)
21
+ response.raise_for_status() # Raise an exception for HTTP errors
22
+ soup = BeautifulSoup(response.content, "html.parser")
23
+ except requests.exceptions.RequestException as e:
24
+ print(f"Error during request: {e}")
25
+ return []
26
+
27
+ urls = []
28
+ # Tìm tất cả các thẻ 'a' (đường link)
29
+ for link in soup.find_all("a"):
30
+ href = link.get("href")
31
+ if href:
32
+ # Sử dụng urljoin để tạo URL tuyệt đối (nếu href là URL tương đối)
33
+ absolute_url = urljoin(url, href)
34
+ urls.append(absolute_url)
35
+
36
+ # Tìm tất cả các thẻ 'img' (đường link hình ảnh)
37
+ for img in soup.find_all("img"):
38
+ src = img.get("src")
39
+ if src:
40
+ absolute_url = urljoin(url, src)
41
+ urls.append(absolute_url)
42
+
43
+ # Lọc các URL có dạng 'https://www.google.com/url?'
44
+ pattern = r"^https://www\.google\.com/url\?q=h"
45
+ filtered_urls = [
46
+ url
47
+ for url in urls
48
+ if re.match(pattern, url) and len(re.findall(r"google", url, re.IGNORECASE)) < 2
49
+ ]
50
+ return filtered_urls
51
+
52
+
53
+ # --------------------------------------
54
+
55
+ # %%capture
56
+ # !pip install groq
57
+ # !pip install google.generativeai
58
+ # !pip install gradio
59
+
60
+ # ----------------------------------
61
+ from groq import Groq
62
+
63
+ client = Groq(api_key="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")
64
+
65
+
66
+ def create_query(history, question):
67
+ completion = client.chat.completions.create(
68
+ model="llama-3.3-70b-specdec",
69
+ messages=[
70
+ {
71
+ "role": "user",
72
+ "content": f'Đóng vai trò là nhà phân tích truy vấn. Dựa vào thông tin lịch sử câu hỏi người dùng và câu hỏi hiện tại, hãy đưa ra một chuỗi từ khóa hợp lý nhất cho câu hỏi hiện tại, để việc tìm kiếm web là lấy được thông tin chính xác và phù hợp.\n\nNếu câu hỏi từ người dùng không liên quan đến lịch sử hỏi, vui lòng không dựa vào lịch sử hỏi để phân tích truy vấn. Bạn cần suy luận để chuỗi từ khóa là hợp lý nhất. Chỉ đưa ra một kết quả chính xác nhất, không chứa cặp nháy kép và không giải thích gì thêm.\n\nLịch sử: "{history}"\nCâu hỏi từ người dùng: "{question}"',
73
+ }
74
+ ],
75
+ temperature=1,
76
+ max_tokens=32,
77
+ top_p=1,
78
+ stream=False,
79
+ stop=None,
80
+ )
81
+ return completion.choices[0].message.content
82
+
83
+
84
+ # ------------------------------------------
85
+
86
+ import urllib.parse
87
+ import os
88
+
89
+ os.environ["GEMINI_API_KEY"] = "AIzaSyAzFb_PROBmKy8mGwQvh4zDUJv1t_sK6_0"
90
+
91
+
92
+ def get_url(url):
93
+ parsed_url = urllib.parse.urlparse(url)
94
+ query_params = urllib.parse.parse_qs(parsed_url.query)
95
+ original_url = query_params["q"][0]
96
+ return original_url
97
+
98
+
99
+ # -------------------------------
100
+
101
+ import requests
102
+ from bs4 import BeautifulSoup
103
+ from requests.packages.urllib3.exceptions import InsecureRequestWarning
104
+
105
+ requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
106
+
107
+
108
+ def get_content(url, i):
109
+ """
110
+ Lấy nội dung text (chữ) từ một trang web, bỏ qua các thẻ HTML.
111
+
112
+ Args:
113
+ url: URL của trang web.
114
+
115
+ Returns:
116
+ Một chuỗi chứa nội dung text của trang web, hoặc None nếu có lỗi.
117
+ """
118
+ headers = {
119
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
120
+ }
121
+ try:
122
+ response = requests.get(url, headers=headers, verify=False, timeout=10)
123
+ response.raise_for_status() # Raise an exception for HTTP errors
124
+ soup = BeautifulSoup(response.content, "html.parser")
125
+
126
+ all_text = soup.get_text(separator="\n", strip=True)
127
+ # Phân tách text thành các đoạn nhỏ theo dòng
128
+ lines = all_text.splitlines()
129
+ # Loại bỏ các đoạn text có độ dài dưới 4
130
+ filtered_lines = [line for line in lines if len(line.split()) >= 1]
131
+ joined_text = " ".join(filtered_lines)
132
+ joined_text.replace("\t", " ")
133
+ joined_text = re.sub(r"\s+", " ", joined_text)
134
+ return f"Nguồn [{i+1}]: {url}\n Nội dung: {joined_text}\n\n"
135
+ except requests.exceptions.RequestException as e:
136
+ print(f"Error during request: {e}")
137
+ return None
138
+
139
+
140
+ # ------------------------------------------------------------
141
+ import re
142
+ import requests
143
+ from bs4 import BeautifulSoup
144
+ from urllib.parse import urljoin
145
+
146
+
147
+ def google_search(query):
148
+ """
149
+ Lấy tất cả các URL từ một trang HTML và lọc ra các URL có dạng
150
+ 'https://www.google.com/url?q=https://'.
151
+
152
+ Args:
153
+ url: URL của trang web.
154
+
155
+ Returns:
156
+ Danh sách các URL đã được lọc.
157
+ """
158
+ url = f"https://www.google.com/search?q={query}"
159
+ try:
160
+ response = requests.get(url)
161
+ response.raise_for_status() # Raise an exception for HTTP errors
162
+ soup = BeautifulSoup(response.content, "html.parser")
163
+ except requests.exceptions.RequestException as e:
164
+ print(f"Error during request: {e}")
165
+ return []
166
+
167
+ urls = []
168
+ # Tìm tất cả các thẻ 'a' (đường link)
169
+ for link in soup.find_all("a"):
170
+ href = link.get("href")
171
+ if href:
172
+ # Sử dụng urljoin để tạo URL tuyệt đối (nếu href là URL tương đối)
173
+ absolute_url = urljoin(url, href)
174
+ urls.append(absolute_url)
175
+
176
+ # Tìm tất cả các thẻ 'img' (đường link hình ảnh)
177
+ for img in soup.find_all("img"):
178
+ src = img.get("src")
179
+ if src:
180
+ absolute_url = urljoin(url, src)
181
+ urls.append(absolute_url)
182
+
183
+ # Lọc các URL có dạng 'https://www.google.com/url?'
184
+ pattern = r"^https://www\.google\.com/url\?q=h"
185
+ filtered_urls = [
186
+ url
187
+ for url in urls
188
+ if re.match(pattern, url) and len(re.findall(r"google", url, re.IGNORECASE)) < 2
189
+ ]
190
+ return filtered_urls
191
+
192
+
193
+ # ---------------------------------------
194
+
195
+ import os
196
+ import google.generativeai as genai
197
+
198
+ genai.configure(api_key=os.environ["GEMINI_API_KEY"])
199
+
200
+ # Create the model
201
+ generation_config = {
202
+ "temperature": 1,
203
+ "top_p": 0.95,
204
+ "top_k": 40,
205
+ "max_output_tokens": 2048,
206
+ "response_mime_type": "text/plain",
207
+ }
208
+
209
+ model_name = "gemini-2.0-flash-exp"
210
+ model = genai.GenerativeModel(
211
+ model_name=model_name,
212
+ generation_config=generation_config,
213
+ )
214
+
215
+ # --------------------------------------
216
+
217
+ from datetime import datetime
218
+ import pytz
219
+ import gradio as gr
220
+
221
+
222
+ def generative_x(query="Chỉ số không khí tại Cầu Giấy, Hà Nội hiện tại"):
223
+ result_google = google_search(query=query)
224
+ text = ""
225
+ for i in range(1):
226
+ x = get_content(result_google[i], i)
227
+ text += f"Nguồn [{i+1}]: {result_google[i]}\n Nội dung: {x}\n\n"
228
+ # extracted_text = extract_information(query, text, model, tokenizer, device)
229
+ # print(extracted_text)
230
+
231
+ question = f"""Bạn sẽ tóm tắt và đưa ra thông tin về chỉ số không khí tại Cầu Giấy, Hà Nội và các thông tin cảnh báo cũng như lời khuyên.
232
+ Cần ngắn gọn, xúc tích. Không cần trích dẫn nguồn.
233
+ Không được sinh bất cứ ô mã nguồn nào.
234
+ Đưa ra kết quả phải theo định dạng sau, có thể thêm màu sắc, icon, hiệu ứng Markdown, ... để câu trả lời được hiển thị sinh động hơn. Nhớ thêm các dấu xuống dòng hợp lý.
235
+
236
+ **Thông tin về chất lượng không khí tại Cầu Giấy**
237
+ ### Chỉ số đo đạc:
238
+ ### Cảnh báo:
239
+ ### Lời khuyên:
240
+
241
+ Bây giờ là {timeis()} tại Hà Nội.
242
+ Thông tin phụ trợ "{text}"
243
+
244
+ Câu hỏi: "{query}" """
245
+ response = model.generate_content(question, stream=True)
246
+ output_text = ""
247
+ for token in response:
248
+ output_text += token.text
249
+ return output_text
250
+
251
+
252
+ def timeview():
253
+ tz = pytz.timezone("Asia/Bangkok")
254
+ now = datetime.now(tz)
255
+ week_number = now.isocalendar().week
256
+ weekday = now.isoweekday()
257
+ weekday_names = [
258
+ "Thứ Hai",
259
+ "Thứ Ba",
260
+ "Thứ Tư",
261
+ "Thứ Năm",
262
+ "Thứ Sáu",
263
+ "Thứ Bảy",
264
+ "Chủ Nhật",
265
+ ]
266
+ weekday_name = weekday_names[weekday - 1]
267
+ date_string = now.strftime("%d tháng %m năm %Y")
268
+ time_string = now.strftime("%H:%M")
269
+
270
+ # Giữ nội dung HTML đơn giản để tránh nháy
271
+ output_string = f"""Tuần {week_number}
272
+ {weekday_name}, ngày {date_string}
273
+ {time_string} (GMT +7)"""
274
+ return output_string
275
+
276
+
277
+ def timeis():
278
+ tz = pytz.timezone("Asia/Bangkok")
279
+ now = datetime.now(tz)
280
+ dt = now.strftime("%d/%m/%Y, %H:%M:%S")
281
+ return dt
282
+
283
+
284
+ def timeupdate():
285
+ tz = pytz.timezone("Asia/Bangkok")
286
+ now = datetime.now(tz)
287
+ dt = now.strftime("%d/%m/%Y, %H:%M:%S")
288
+ return f"""<small><i>Cập nhật lần cuối: {dt}</i></small>"""
289
+
290
+
291
+ import gradio as gr
292
+
293
+ chat_session = model.start_chat()
294
+ search_history = [] # List để lưu trữ lịch sử truy vấn
295
+
296
+
297
+ def generative(user_query, history, use_special_features):
298
+ global search_history
299
+ # Lấy kết quả tìm kiếm và sinh câu trả lời
300
+ search_history = search_history[-3:]
301
+
302
+ # ----------- Internet ------------------
303
+ if use_special_features:
304
+ # Thực hiện tìm kiếm với truy v��n kết hợp
305
+ query = create_query(search_history, user_query)
306
+ search_history.append(user_query)
307
+ result_google = google_search(query=query)
308
+
309
+ from concurrent.futures import ThreadPoolExecutor, as_completed
310
+
311
+ with ThreadPoolExecutor(max_workers=5) as executor:
312
+
313
+ # Gửi các nhiệm vụ vào pool và thu thập kết quả
314
+ futures = [
315
+ executor.submit(get_content, result_google[i], i)
316
+ for i in range(min(5, len(result_google)))
317
+ ]
318
+
319
+ # Lấy kết quả từ các task
320
+ all_results = []
321
+
322
+ for future in as_completed(futures): # Duyệt qua các luồng đã hoàn thành
323
+ try:
324
+ # Thu thập kết quả
325
+ result = future.result()
326
+ all_results.append(result)
327
+ except Exception as e:
328
+ # Ghi lại lỗi nếu xảy ra
329
+ j = 1
330
+
331
+ result_string = "\n".join(all_results)
332
+
333
+ # for i in range(5):
334
+ # x = get_content(result_google[i])
335
+ # text += f"Nguồn [{i+1}]: {result_google[i]}\n Nội dung: {x}\n\n"
336
+
337
+ question = f"""Hãy nhớ rằng bạn là trợ lý ảo MobiBot của MobiFone.
338
+ Đây là một số lưu ý:
339
+ - Câu trả lời cần tự nhiên, không cứng nhắc
340
+ - Cần sử dụng toàn bộ nguồn thông tin được cung cấp để tránh sai sót, thiếu thông tin, thậm chí là thiên vị. Đưa ra một câu trả lời duy nhất, không lan man, chính xác và đầy đủ nhất.
341
+ - Trích dẫn nguồn. Chỉ đưa ra số hiệu nguồn, ví dụ [1], [2],..., thay vì ghi chi tiết đường dẫn.
342
+ - Ghi rõ các yếu tố thời điểm.
343
+ - Các câu hỏi yêu cầu suy luận thông tin để trả lời.
344
+ - Đây là một phiên trò chuyện nên hãy tận dụng lịch sử chat để trả lời phù hợp nhất.
345
+
346
+ Bây giờ là {timeis()} tại Hà Nội.
347
+ Thông tin phụ trợ \"{result_string}\"
348
+
349
+ Câu hỏi: \"{user_query}\"
350
+ """
351
+ # Gửi tin nhắn người dùng đến ChatSession
352
+ response = chat_session.send_message(question)
353
+ # Xử lý kết quả trả về (nếu cần)
354
+ assistant_answer = f"{query}\n\n {response.text}"
355
+
356
+ assistant_answer += "\n-----------\nNguồn:\n"
357
+ for i in range(min(5, len(result_google))):
358
+ if re.search(rf"\[{i}\]", assistant_answer):
359
+ assistant_answer += f"[{i+1}]: {get_url(result_google[i])}\n"
360
+
361
+ yield assistant_answer
362
+ # --------------------- No Internet ---------------------
363
+ else:
364
+ search_history.append(user_query)
365
+ question = f"""Hãy nhớ rằng bạn là trợ lý ảo MobiBot của MobiFone.
366
+ Đây là một số lưu ý:
367
+ - Câu trả lời cần tự nhiên, không cứng nhắc
368
+ - Đưa ra một câu trả lời duy nhất, không lan man, chính xác và đầy đủ nhất.
369
+ - Các câu hỏi yêu cầu suy luận thông tin để trả lời.
370
+ - Đây là một phiên trò chuyện nên hãy tận dụng lịch sử chat để trả lời phù hợp nhất.
371
+ Câu hỏi: \"{user_query}\"
372
+ """
373
+ # Gửi tin nhắn người dùng đến ChatSession
374
+ response = chat_session.send_message(question)
375
+ # Xử lý kết quả trả về (nếu cần)
376
+ assistant_answer = response.text
377
+ yield assistant_answer
378
+
379
+
380
+ css = """
381
+ #chatbot {
382
+ flex-grow: 1 !important;
383
+ overflow: auto !important;
384
+ }
385
+ #col { height: calc(100vh - 112px - 16px) !important; }
386
+ .centered-text {
387
+ text-align: center;
388
+ font-weight: bold;
389
+ }
390
+ .gradient-text {
391
+ background-image: linear-gradient(to right, #283593, #673ab7, #d32f2f); /* Xanh indigo, tím, đỏ */
392
+ -webkit-background-clip: text;
393
+ color: transparent;
394
+ font-weight: bold;
395
+ text-align: center;
396
+ }
397
+ #my_textbox {
398
+ background-image: linear-gradient(to right, #f00, #00f); /* Chuyển màu từ đỏ sang xanh */
399
+ color: #333333;
400
+ border: 2px solid #4CAF50;
401
+ border-radius: 5px;
402
+ padding: 10px;
403
+ font-size: 16px;
404
+ }
405
+ .custom-textbox {
406
+ box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
407
+ }
408
+ #info-container { /* Style cho container thông tin */
409
+ border: 3px solid #ccc;
410
+ padding: 10px;
411
+ border-radius: 5px;
412
+ overflow-y: auto; /* Cho phép cuộn nếu nội dung quá dài */
413
+ max-height: 400px; /* Giới hạn chiều cao tối đa (tùy chỉnh theo ý muốn) */
414
+ }
415
+
416
+ """
417
+ initial_info = generative_x()
418
+ initial_time_view = timeupdate()
419
+
420
+ # Tạo giao diện chatbot với gr.ChatInterface
421
+ # demo = gr.ChatInterface(fn=generative, chatbot=gr.Chatbot(label="Chat với hệ thống"))
422
+ with gr.Blocks(css=css) as demo:
423
+
424
+ with gr.Row():
425
+ with gr.Column(scale=3, elem_id="col"):
426
+ gr.Markdown(
427
+ """<div style="font-size: 26px; font-weight: bold; line-height: 1.2; margin: 1;">
428
+ Demini <span style="background: linear-gradient(to right, #f00, #00f); -webkit-background-clip: text; color: transparent;">Free</span>
429
+ </div>
430
+ <div style="font-size: 16px; line-height: 1.2; margin: 5;">
431
+ 2.0 Flash Experimental with Google Search
432
+ </div>"""
433
+ )
434
+ # Khối thông tin xây dựng
435
+ build_text = gr.Textbox(
436
+ value="Bản dựng kết hợp giữa API của Gemini 2.0 và các công cụ cào website. MỚI: Đã có thể ghi nhớ cuộc trò chuyện trước đó. MỚI: Đã tăng tốc tìm kiếm lên 5 lần. GHI CHÚ: Gemini 2.0 Flash có thể cho kết quả chậm hơn dự kiến (khoảng 60-90 giây). Vui lòng kiên nhẫn. ",
437
+ label=None,
438
+ elem_id="my_textbox",
439
+ elem_classes="custom_textbox",
440
+ )
441
+
442
+ #######
443
+ # Khối thời gian hiện tại
444
+ clock_output = gr.Textbox(label="Thời gian hiện tại")
445
+ timer_1 = gr.Timer(1)
446
+ # Sử dụng timer.tick() để cập nhật clock_output mỗi giây
447
+ timer_1.tick(fn=timeview, inputs=None, outputs=clock_output)
448
+
449
+ # with gr.Column(elem_id="info-container"): # Tạo một container cho thông tin
450
+ # timetable = gr.Markdown(initial_info)
451
+ # time_output = gr.Markdown(initial_time_view)
452
+ # refresh_button = gr.Button("🔄 Làm mới")
453
+ # refresh_button.click(fn=generative_x, inputs=None, outputs=timetable)
454
+ # refresh_button.click(fn=timeupdate, inputs=None, outputs=time_output)
455
+ #######
456
+
457
+ with gr.Column(scale=7, elem_id="col"):
458
+ use_special_features = gr.Checkbox(
459
+ label="THỬ NGHIỆM: Sử dụng chức năng tìm kiếm web (Chú ý: Tính năng này mất thêm 10-15 giây để phân tích)",
460
+ value=False,
461
+ )
462
+ chat = gr.ChatInterface(
463
+ fn=generative,
464
+ additional_inputs=[use_special_features],
465
+ chatbot=gr.Chatbot(elem_id="chatbot", render=False),
466
+ )
467
+ gr.Markdown(
468
+ "Câu trả lời sinh bởi mô hình Gemini 2.0 Flash. Có thể có lỗi sai, điều này không thể tránh khỏi. QUAN TRỌNG: Cần xác thực các thông tin được đưa ra.",
469
+ elem_classes="centered-text",
470
+ )
471
+
472
+ demo.queue()
473
+ demo.launch(share=True)