Atsatoru commited on
Commit
57b505f
·
verified ·
1 Parent(s): 2de9d22

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -52
app.py CHANGED
@@ -1362,14 +1362,12 @@ def fetch_live_government_news():
1362
  """Tự động kết nối và lấy dữ liệu tin tức mới nhất từ cổng thông tin"""
1363
  news_list = []
1364
  try:
1365
- # Cào dữ liệu thực tế từ chuyên mục hướng tới Chính phủ số / Dịch vụ công công nghệ mới
1366
  url = "https://baochinhphu.vn/tien-toi-chinh-phu-so.htm"
1367
  headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
1368
 
1369
  response = requests.get(url, headers=headers, verify=False, timeout=5)
1370
  if response.status_code == 200:
1371
  soup = BeautifulSoup(response.text, 'html.parser')
1372
- # Lấy ra 3 bài báo mới nhất dựa trên cấu trúc thẻ HTML của baochinhphu
1373
  stories = soup.find_all('div', class_='story', limit=3)
1374
 
1375
  for story in stories:
@@ -1389,7 +1387,6 @@ def fetch_live_government_news():
1389
  except Exception as e:
1390
  print(f"Lỗi kết nối đồng bộ tin tức trực tuyến: {e}")
1391
 
1392
- # Cơ chế dự phòng an toàn nếu mất kết nối mạng hoặc trang nguồn thay đổi cấu trúc thẻ HTML
1393
  if len(news_list) < 3:
1394
  news_list = [
1395
  {"title": "Đẩy mạnh số hóa 100% kết quả thủ tục hành chính công", "desc": "Kế hoạch hành động thúc đẩy toàn bộ các đơn vị ứng dụng trợ lý AI nhằm giảm thiểu tối đa thời gian chờ cấp trả giấy tờ trực tiếp cho người dân...", "link": "#"},
@@ -1416,14 +1413,14 @@ def update_news_interface():
1416
  return html_code
1417
 
1418
  # =====================================================================
1419
- # BACKEND FUNCTIONS (GIỮ NGUYÊN CẤU TRÚC LOGIC CỦA BẠN)
1420
  # =====================================================================
1421
  admin_procedures = list(DICHVUCONG_DATA.values())
1422
 
1423
  def get_procedures_list():
1424
  lines = ["| Mã | Tên thủ tục | Cơ quan |"]
1425
  lines.append("|---|---|---|")
1426
- for p in admin_procedures[:20]: # Limit to 20 for display
1427
  lines.append(f"| {p['code']} | {p['name']} | {p['coquan']} |")
1428
  return "\n".join(lines)
1429
 
@@ -1452,7 +1449,6 @@ def process_chat_pro(audio, text, history, persona="thuong"):
1452
  result = ai_process_pro(query, use_memory=True)
1453
  response = f"""{result['response']}\n\n--- \n _⏱️ Xử lý: {result['process_time']}s | 📄 Tài liệu: {result['docs_count']} | 🌡️ Temp: {result['temperature']}_"""
1454
 
1455
- # Cập nhật history theo định dạng Tuple [[user, bot]] cho bản Gradio cũ
1456
  history.append((query, response))
1457
 
1458
  audio_out = None
@@ -1489,21 +1485,18 @@ def change_persona(new_persona):
1489
  # CẤU HÌNH GIAO DIỆN & CUSTOM CSS
1490
  # =====================================================================
1491
  custom_css = """
1492
- /* Reset font & nền */
1493
  .gradio-container {
1494
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
1495
  background-color: #f8f9fa !important;
1496
  }
1497
- /* Ẩn footer mặc định */
1498
  footer {display: none !important;}
1499
 
1500
- /* Thanh Topbar chuyên nghiệp (Gradient Xanh Navy) */
1501
  .admin-topbar {
1502
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
1503
  padding: 20px 30px;
1504
  display: flex;
1505
  align-items: center;
1506
- margin: -20px -20px 20px -20px; /* Tràn viền */
1507
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
1508
  color: white;
1509
  }
@@ -1528,7 +1521,6 @@ footer {display: none !important;}
1528
  margin: 5px 0 0 0 !important;
1529
  font-weight: 300 !important;
1530
  }
1531
- /* Style thẻ tin tức cho Tab Trang chủ */
1532
  .news-card {
1533
  background: #ffffff;
1534
  padding: 14px;
@@ -1537,7 +1529,6 @@ footer {display: none !important;}
1537
  border-radius: 6px;
1538
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
1539
  }
1540
- /* Khung hướng dẫn bo góc chân trang */
1541
  .guide-box {
1542
  background: #ffffff;
1543
  padding: 15px 20px;
@@ -1546,7 +1537,6 @@ footer {display: none !important;}
1546
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
1547
  margin-top: 5px;
1548
  }
1549
- /* Tinh chỉnh Nút bấm */
1550
  button.primary {
1551
  background-color: #0056b3 !important;
1552
  color: white !important;
@@ -1559,14 +1549,12 @@ button.primary:hover {
1559
  background-color: #004494 !important;
1560
  box-shadow: 0 4px 8px rgba(0,86,179,0.3) !important;
1561
  }
1562
- /* Tùy chỉnh Khung Chat */
1563
  .main-chatbot {
1564
  border: 1px solid #dee2e6 !important;
1565
  border-radius: 8px !important;
1566
  background-color: #ffffff !important;
1567
  box-shadow: 0 2px 15px rgba(0,0,0,0.03) !important;
1568
  }
1569
- /* Tiêu đề Box */
1570
  .section-title {
1571
  color: #1e3c72;
1572
  font-weight: 600;
@@ -1575,10 +1563,8 @@ button.primary:hover {
1575
  padding-bottom: 5px;
1576
  }"""
1577
 
1578
- # Khởi tạo giao diện với Theme base màu xanh thanh lịch
1579
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), css=custom_css) as demo:
1580
 
1581
- # 1. TOPBAR CHUYÊN NGHIỆP (Gradient Xanh Navy)
1582
  gr.HTML("""
1583
  <div class="admin-topbar">
1584
  <div class="admin-icon">🏛️</div>
@@ -1592,16 +1578,13 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), cs
1592
  with gr.Tabs():
1593
 
1594
  # ------------------------------------------------------------------
1595
- # TAB 1: TRANG CHỦ (TIN TỨC Ở TRÊN NẰM NGANG - HƯỚNG DẪN Ở DƯỚI)
1596
  # ------------------------------------------------------------------
1597
  with gr.Tab("🏠 Trang chủ"):
1598
- # 1. Khối tin tức trực tuyến từ Chính Phủ: Sắp xếp nằm ngang toàn bộ trang web ngay sát dưới thanh taskbar
1599
  gr.HTML("<div class='section-title'>📰 BẢN TIN ĐIỆN TỬ DỊCH VỤ CÔNG QUỐC GIA (CẬP NHẬT TỰ ĐỘNG)</div>")
1600
  live_news_box = gr.HTML(value="<p style='font-size:13px; color:#666;'>🔄 Đang đồng bộ thông tin mới nhất từ Cổng Dịch vụ công Quốc gia...</p>")
1601
 
1602
- # 2. Khối hướng dẫn sử dụng: Di chuyển xuống dưới cùng chiếm toàn bộ không gian ngang
1603
  gr.HTML("<div class='section-title' style='margin-top: 15px;'>📖 HƯỚNG DẪN SỬ DỤNG HỆ THỐNG TRỢ LÝ ẢO</div>")
1604
-
1605
  with gr.Group(elem_classes="guide-box"):
1606
  gr.Markdown("""
1607
  Chào mừng bạn đến với **Hệ thống AI Hành chính công**. Hãy làm theo các hướng dẫn sau để khai thác tối đa tính năng:
@@ -1612,7 +1595,7 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), cs
1612
  """)
1613
 
1614
  # ------------------------------------------------------------------
1615
- # TAB 2: TRỢ LÝ AI (HỆ THỐNG CHATBOT)
1616
  # ------------------------------------------------------------------
1617
  with gr.Tab("💬 Trợ lý AI"):
1618
  with gr.Row():
@@ -1667,11 +1650,9 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), cs
1667
  btn_clear.click(clear_chat_pro, [], [chat, audio_out, msg_in])
1668
 
1669
  # ------------------------------------------------------------------
1670
- # TAB 3: ADMIN PANEL (BẢO TOÀN LOG IN & LOG OUT)
1671
  # ------------------------------------------------------------------
1672
  with gr.Tab("⚙️ Admin Panel"):
1673
-
1674
- # Khối giao diện đăng nhập (Login Form)
1675
  with gr.Row() as login_form:
1676
  input_user = gr.Textbox(
1677
  label="Tài khoản cán bộ",
@@ -1686,7 +1667,6 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), cs
1686
  )
1687
  btn_login = gr.Button("Đăng nhập 🔑", scale=1, variant="primary")
1688
 
1689
- # Khối nội dung Admin - Mặc định ẩn (visible=False)
1690
  admin_content = gr.Group(visible=False)
1691
 
1692
  with admin_content:
@@ -1711,16 +1691,15 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), cs
1711
  add_output = gr.Textbox(label="Kết quả xử lý")
1712
  procedures_list = gr.Markdown(value=get_procedures_list())
1713
 
1714
- # --- Logic xử lý Đăng nhập (Sửa lỗi ACCOUNT thành ADMIN_USERNAME tương thích tệp app.py gốc) ---
1715
  def check_admin_login(username, password):
1716
- if username == ADMIN_USERNAME and password == ADMIN_PASSWORD:
1717
  gr.Info("Đăng nhập hệ thống thành công!")
1718
  return gr.update(visible=False), gr.update(visible=True)
1719
  else:
1720
- gr.Warning("Tài khoản hoặc mật khẩu không chính xác. Vui lòng kiểm tra lại!")
1721
  return gr.update(visible=True), gr.update(visible=False)
1722
 
1723
- # --- Logic xử lý Đăng xuất ---
1724
  def admin_logout():
1725
  gr.Info("Đã đăng xuất khỏi tài khoản admin.")
1726
  return (
@@ -1730,35 +1709,38 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), cs
1730
  gr.update(value="")
1731
  )
1732
 
1733
- # Liên kết Sự kiện nút Đăng nhập
1734
- btn_login.click(
1735
- check_admin_login,
1736
- inputs=[input_user, input_pass],
1737
- outputs=[login_form, admin_content]
1738
- )
1739
-
1740
- # Liên kết Sự kiện nút Đăng xuất
1741
- btn_logout.click(
1742
- admin_logout,
1743
- inputs=[],
1744
- outputs=[login_form, admin_content, input_user, input_pass]
1745
- )
1746
-
1747
- # Sự kiện thêm thủ tục mới
1748
- btn_add.click(
1749
- admin_add,
1750
- [admin_code, admin_name, admin_docs, admin_coquan, admin_time, admin_lephi, admin_note, admin_steps],
1751
- [add_output, procedures_list]
1752
- )
 
 
 
 
1753
 
1754
- # Khởi động cơ chế tải dữ liệu thời gian thực khi khởi động trang web
1755
  demo.load(fn=update_news_interface, inputs=[], outputs=[live_news_box])
1756
 
1757
  # ============================================================
1758
  # PHẦN 12.7: LAUNCH APP PRO
1759
  # ============================================================
1760
  print('='*70)
1761
- print('🚀 KHỞI ĐỘNG ỨNG DỤNG AI PRO')
1762
  print('='*70)
1763
  print()
1764
 
 
1362
  """Tự động kết nối và lấy dữ liệu tin tức mới nhất từ cổng thông tin"""
1363
  news_list = []
1364
  try:
 
1365
  url = "https://baochinhphu.vn/tien-toi-chinh-phu-so.htm"
1366
  headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
1367
 
1368
  response = requests.get(url, headers=headers, verify=False, timeout=5)
1369
  if response.status_code == 200:
1370
  soup = BeautifulSoup(response.text, 'html.parser')
 
1371
  stories = soup.find_all('div', class_='story', limit=3)
1372
 
1373
  for story in stories:
 
1387
  except Exception as e:
1388
  print(f"Lỗi kết nối đồng bộ tin tức trực tuyến: {e}")
1389
 
 
1390
  if len(news_list) < 3:
1391
  news_list = [
1392
  {"title": "Đẩy mạnh số hóa 100% kết quả thủ tục hành chính công", "desc": "Kế hoạch hành động thúc đẩy toàn bộ các đơn vị ứng dụng trợ lý AI nhằm giảm thiểu tối đa thời gian chờ cấp trả giấy tờ trực tiếp cho người dân...", "link": "#"},
 
1413
  return html_code
1414
 
1415
  # =====================================================================
1416
+ # BACKEND FUNCTIONS (CỦA BẠN)
1417
  # =====================================================================
1418
  admin_procedures = list(DICHVUCONG_DATA.values())
1419
 
1420
  def get_procedures_list():
1421
  lines = ["| Mã | Tên thủ tục | Cơ quan |"]
1422
  lines.append("|---|---|---|")
1423
+ for p in admin_procedures[:20]:
1424
  lines.append(f"| {p['code']} | {p['name']} | {p['coquan']} |")
1425
  return "\n".join(lines)
1426
 
 
1449
  result = ai_process_pro(query, use_memory=True)
1450
  response = f"""{result['response']}\n\n--- \n _⏱️ Xử lý: {result['process_time']}s | 📄 Tài liệu: {result['docs_count']} | 🌡️ Temp: {result['temperature']}_"""
1451
 
 
1452
  history.append((query, response))
1453
 
1454
  audio_out = None
 
1485
  # CẤU HÌNH GIAO DIỆN & CUSTOM CSS
1486
  # =====================================================================
1487
  custom_css = """
 
1488
  .gradio-container {
1489
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
1490
  background-color: #f8f9fa !important;
1491
  }
 
1492
  footer {display: none !important;}
1493
 
 
1494
  .admin-topbar {
1495
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
1496
  padding: 20px 30px;
1497
  display: flex;
1498
  align-items: center;
1499
+ margin: -20px -20px 20px -20px;
1500
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
1501
  color: white;
1502
  }
 
1521
  margin: 5px 0 0 0 !important;
1522
  font-weight: 300 !important;
1523
  }
 
1524
  .news-card {
1525
  background: #ffffff;
1526
  padding: 14px;
 
1529
  border-radius: 6px;
1530
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
1531
  }
 
1532
  .guide-box {
1533
  background: #ffffff;
1534
  padding: 15px 20px;
 
1537
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
1538
  margin-top: 5px;
1539
  }
 
1540
  button.primary {
1541
  background-color: #0056b3 !important;
1542
  color: white !important;
 
1549
  background-color: #004494 !important;
1550
  box-shadow: 0 4px 8px rgba(0,86,179,0.3) !important;
1551
  }
 
1552
  .main-chatbot {
1553
  border: 1px solid #dee2e6 !important;
1554
  border-radius: 8px !important;
1555
  background-color: #ffffff !important;
1556
  box-shadow: 0 2px 15px rgba(0,0,0,0.03) !important;
1557
  }
 
1558
  .section-title {
1559
  color: #1e3c72;
1560
  font-weight: 600;
 
1563
  padding-bottom: 5px;
1564
  }"""
1565
 
 
1566
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", neutral_hue="slate"), css=custom_css) as demo:
1567
 
 
1568
  gr.HTML("""
1569
  <div class="admin-topbar">
1570
  <div class="admin-icon">🏛️</div>
 
1578
  with gr.Tabs():
1579
 
1580
  # ------------------------------------------------------------------
1581
+ # TAB 1: TRANG CHỦ
1582
  # ------------------------------------------------------------------
1583
  with gr.Tab("🏠 Trang chủ"):
 
1584
  gr.HTML("<div class='section-title'>📰 BẢN TIN ĐIỆN TỬ DỊCH VỤ CÔNG QUỐC GIA (CẬP NHẬT TỰ ĐỘNG)</div>")
1585
  live_news_box = gr.HTML(value="<p style='font-size:13px; color:#666;'>🔄 Đang đồng bộ thông tin mới nhất từ Cổng Dịch vụ công Quốc gia...</p>")
1586
 
 
1587
  gr.HTML("<div class='section-title' style='margin-top: 15px;'>📖 HƯỚNG DẪN SỬ DỤNG HỆ THỐNG TRỢ LÝ ẢO</div>")
 
1588
  with gr.Group(elem_classes="guide-box"):
1589
  gr.Markdown("""
1590
  Chào mừng bạn đến với **Hệ thống AI Hành chính công**. Hãy làm theo các hướng dẫn sau để khai thác tối đa tính năng:
 
1595
  """)
1596
 
1597
  # ------------------------------------------------------------------
1598
+ # TAB 2: TRỢ LÝ AI
1599
  # ------------------------------------------------------------------
1600
  with gr.Tab("💬 Trợ lý AI"):
1601
  with gr.Row():
 
1650
  btn_clear.click(clear_chat_pro, [], [chat, audio_out, msg_in])
1651
 
1652
  # ------------------------------------------------------------------
1653
+ # TAB 3: ADMIN PANEL (Sửa lỗi đồng bộ đăng nhập theo file gốc)
1654
  # ------------------------------------------------------------------
1655
  with gr.Tab("⚙️ Admin Panel"):
 
 
1656
  with gr.Row() as login_form:
1657
  input_user = gr.Textbox(
1658
  label="Tài khoản cán bộ",
 
1667
  )
1668
  btn_login = gr.Button("Đăng nhập 🔑", scale=1, variant="primary")
1669
 
 
1670
  admin_content = gr.Group(visible=False)
1671
 
1672
  with admin_content:
 
1691
  add_output = gr.Textbox(label="Kết quả xử lý")
1692
  procedures_list = gr.Markdown(value=get_procedures_list())
1693
 
1694
+ # Logic xử lý Đăng nhập chỉ dùng ADMIN_PASSWORD gốc của bạn
1695
  def check_admin_login(username, password):
1696
+ if password == ADMIN_PASSWORD:
1697
  gr.Info("Đăng nhập hệ thống thành công!")
1698
  return gr.update(visible=False), gr.update(visible=True)
1699
  else:
1700
+ gr.Warning("Mật khẩu không chính xác. Vui lòng kiểm tra lại!")
1701
  return gr.update(visible=True), gr.update(visible=False)
1702
 
 
1703
  def admin_logout():
1704
  gr.Info("Đã đăng xuất khỏi tài khoản admin.")
1705
  return (
 
1709
  gr.update(value="")
1710
  )
1711
 
1712
+ btn_login.click(check_admin_login, inputs=[input_user, input_pass], outputs=[login_form, admin_content])
1713
+ btn_logout.click(admin_logout, inputs=[], outputs=[login_form, admin_content, input_user, input_pass])
1714
+ btn_add.click(admin_add, [admin_code, admin_name, admin_docs, admin_coquan, admin_time, admin_lephi, admin_note, admin_steps], [add_output, procedures_list])
1715
+
1716
+ # ------------------------------------------------------------------
1717
+ # TAB 4: MEMORY MANAGER (Trả lại đầy đủ Tab gốc)
1718
+ # ------------------------------------------------------------------
1719
+ with gr.Tab("🧠 Memory Manager"):
1720
+ gr.Markdown("### 📊 Quản lý bộ nhớ hội thoại")
1721
+
1722
+ memory_info = gr.Textbox(label="Ngữ cảnh hiện tại", interactive=False, lines=3)
1723
+ memory_history = gr.Textbox(label="Lịch sử chat", interactive=False, lines=10)
1724
+
1725
+ with gr.Row():
1726
+ btn_refresh = gr.Button("🔄 Làm mới")
1727
+ btn_clear_mem = gr.Button("🗑️ Xóa memory", variant='stop')
1728
+
1729
+ def refresh_memory():
1730
+ ctx = conversation_memory.get_context_summary()
1731
+ hist = "\n".join([f"{m['role']}: {m['content'][:100]}..." for m in conversation_memory.history[-5:]])
1732
+ return ctx or "Không có ngữ cảnh", hist or "Không có lịch sử"
1733
+
1734
+ btn_refresh.click(refresh_memory, [], [memory_info, memory_history])
1735
+ btn_clear_mem.click(clear_chat_pro, [], [chat, audio_out, msg_in])
1736
 
 
1737
  demo.load(fn=update_news_interface, inputs=[], outputs=[live_news_box])
1738
 
1739
  # ============================================================
1740
  # PHẦN 12.7: LAUNCH APP PRO
1741
  # ============================================================
1742
  print('='*70)
1743
+ print('🚀 KHỔI ĐỘNG ỨNG DỤNG AI PRO')
1744
  print('='*70)
1745
  print()
1746