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