shield-chatbot / src /streamlit_app.py
DeepLearning101's picture
Update src/streamlit_app.py
92aeb66 verified
raw
history blame
4.69 kB
import streamlit as st
import google.generativeai as genai
import requests
import os
st.set_page_config(page_title="AI 新知小助手", page_icon="📚", layout="wide")
# 從環境變數中取得 API Key
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
st.error("請確認已經在 Space 的 Settings -> Variables and secrets 中設定了 GEMINI_API_KEY")
st.stop()
genai.configure(api_key=api_key)
# 1. 基礎設定與連結
BASE_URL = "https://raw.githubusercontent.com/Deep-Learning-101/deep-learning-101.github.io/main/"
LOGO_URL = f"{BASE_URL}images/DeepLearning101-LOGO.png"
HOME_URL = "https://deep-learning-101.github.io"
# 定義知識庫檔案與對應的社群連結
KNOWLEDGE_MAP = {
"大型語言模型 (LLM)": {
"raw_url": f"{BASE_URL}Large-Language-Model.md",
"page_url": "https://deep-learning-101.github.io/Large-Language-Model",
"repo_url": "https://github.com/Deep-Learning-101/Natural-Language-Processing-Paper/blob/main/Large-Language-Model.md"
},
"自然語言處理 (NLP)": {
"raw_url": f"{BASE_URL}Natural-Language-Processing.md",
"page_url": "https://deep-learning-101.github.io/Natural-Language-Processing",
"repo_url": "https://github.com/Deep-Learning-101/Natural-Language-Processing-Paper"
},
"語音處理 (Speech)": {
"raw_url": f"{BASE_URL}Speech-Processing.md",
"page_url": "https://deep-learning-101.github.io/Speech-Processing",
"repo_url": "https://github.com/Deep-Learning-101/Speech-Processing-Paper"
},
"電腦視覺 (CV)": {
"raw_url": f"{BASE_URL}Computer-Vision.md",
"page_url": "https://deep-learning-101.github.io/Computer-Vision",
"repo_url": "https://github.com/Deep-Learning-101/Computer-Vision-Paper"
}
}
# 2. 批量抓取內容
def fetch_all_knowledge():
combined_knowledge = ""
with st.spinner("正在同步 GitHub 最新資訊..."):
for category, info in KNOWLEDGE_MAP.items():
try:
response = requests.get(info["raw_url"])
response.raise_for_status()
combined_knowledge += f"\n\n## 【領域:{category}】\n"
combined_knowledge += response.text
except Exception as e:
st.warning(f"無法同步 {category} 的資料:{e}")
return combined_knowledge
if "knowledge" not in st.session_state:
st.session_state.knowledge = fetch_all_knowledge()
if "messages" not in st.session_state:
st.session_state.messages = []
# 3. 側邊欄設計
with st.sidebar:
# 放置可點擊的 Logo
st.markdown(
f"""
<a href="{HOME_URL}" target="_blank">
<img src="{LOGO_URL}" width="85%">
</a>
""",
unsafe_allow_html=True
)
st.title("⚙️ 知識庫狀態")
st.write("目前收錄領域與連結:")
# 迴圈產生各領域連結
for category, info in KNOWLEDGE_MAP.items():
with st.expander(category):
st.markdown(f"🔗 [瀏覽網頁]({info['page_url']})")
st.markdown(f"📂 [GitHub 原始碼]({info['repo_url']})")
st.markdown("---")
if st.button("🔄 手動更新知識庫"):
st.session_state.knowledge = fetch_all_knowledge()
st.success("資料已重新抓取!")
# 4. 主介面
st.title("📚 AI 演算法與論文社群助手")
st.caption("知識庫涵蓋 LLM、NLP、Speech、CV。歡迎直接提問!")
def get_gemini_response(user_input):
system_instruction = f"""
你是一位專業的 AI 技術分析專家。
以下是從 GitHub 同步的技術資訊:
---
{st.session_state.knowledge}
---
請嚴格基於上述提供的資訊來回答問題。
如果資訊中未收錄,請告知:「目前懶人包中尚未收錄此細節」。
"""
model = genai.GenerativeModel(
model_name="gemini-flash-latest",
system_instruction=system_instruction
)
chat = model.start_chat(history=[])
response = chat.send_message(user_input)
return response.text
# 顯示對話紀錄
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# 接收輸入
if prompt := st.chat_input("想瞭解哪方面的技術?"):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
response_text = get_gemini_response(prompt)
st.markdown(response_text)
st.session_state.messages.append({"role": "assistant", "content": response_text})