Update src/streamlit_app.py
Browse files- src/streamlit_app.py +81 -37
src/streamlit_app.py
CHANGED
|
@@ -3,23 +3,44 @@ import google.generativeai as genai
|
|
| 3 |
import requests
|
| 4 |
import os
|
| 5 |
|
|
|
|
| 6 |
st.set_page_config(page_title="AI 新知小助手", page_icon="📚", layout="wide")
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
# 從環境變數中取得 API Key
|
| 9 |
api_key = os.environ.get("GEMINI_API_KEY")
|
| 10 |
-
|
| 11 |
if not api_key:
|
| 12 |
-
st.error("請確認已經在 Space 的 Settings
|
| 13 |
st.stop()
|
| 14 |
|
| 15 |
genai.configure(api_key=api_key)
|
| 16 |
|
| 17 |
# 1. 基礎設定與連結
|
| 18 |
BASE_URL = "https://raw.githubusercontent.com/Deep-Learning-101/deep-learning-101.github.io/main/"
|
| 19 |
-
LOGO_URL = f"{BASE_URL}
|
| 20 |
HOME_URL = "https://deep-learning-101.github.io"
|
| 21 |
|
| 22 |
-
# 定義知識庫檔案與對應的社群連結
|
| 23 |
KNOWLEDGE_MAP = {
|
| 24 |
"大型語言模型 (LLM)": {
|
| 25 |
"raw_url": f"{BASE_URL}Large-Language-Model.md",
|
|
@@ -57,42 +78,47 @@ def fetch_all_knowledge():
|
|
| 57 |
st.warning(f"無法同步 {category} 的資料:{e}")
|
| 58 |
return combined_knowledge
|
| 59 |
|
|
|
|
| 60 |
if "knowledge" not in st.session_state:
|
| 61 |
st.session_state.knowledge = fetch_all_knowledge()
|
| 62 |
|
| 63 |
if "messages" not in st.session_state:
|
| 64 |
st.session_state.messages = []
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
# 3. 側邊欄設計
|
| 67 |
with st.sidebar:
|
| 68 |
-
|
| 69 |
-
st.markdown(
|
| 70 |
-
f"""
|
| 71 |
-
<a href="{HOME_URL}" target="_blank">
|
| 72 |
-
<img src="{LOGO_URL}" width="85%">
|
| 73 |
-
</a>
|
| 74 |
-
""",
|
| 75 |
-
unsafe_allow_html=True
|
| 76 |
-
)
|
| 77 |
-
|
| 78 |
st.title("⚙️ 知識庫狀態")
|
| 79 |
-
st.write("目前收錄領域與連結:")
|
| 80 |
-
|
| 81 |
-
# 迴圈產生各領域連結
|
| 82 |
for category, info in KNOWLEDGE_MAP.items():
|
| 83 |
with st.expander(category):
|
| 84 |
st.markdown(f"🔗 [瀏覽網頁]({info['page_url']})")
|
| 85 |
st.markdown(f"📂 [GitHub 原始碼]({info['repo_url']})")
|
| 86 |
-
|
| 87 |
st.markdown("---")
|
| 88 |
if st.button("🔄 手動更新知識庫"):
|
| 89 |
st.session_state.knowledge = fetch_all_knowledge()
|
| 90 |
st.success("資料已重新抓取!")
|
| 91 |
|
| 92 |
-
# 4. 主介面
|
| 93 |
st.title("📚 AI 演算法與論文社群助手")
|
| 94 |
st.caption("知識庫涵蓋 LLM、NLP、Speech、CV。歡迎直接提問!")
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
def get_gemini_response(user_input):
|
| 97 |
system_instruction = f"""
|
| 98 |
你是一位專業的 AI 技術分析專家。
|
|
@@ -101,30 +127,48 @@ def get_gemini_response(user_input):
|
|
| 101 |
{st.session_state.knowledge}
|
| 102 |
---
|
| 103 |
請嚴格基於上述提供的資訊來回答問題。
|
| 104 |
-
如果資訊中未收錄,請告知:「目前懶人包中尚未收錄此細節」。
|
| 105 |
"""
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
st.markdown(message["content"])
|
| 119 |
|
| 120 |
-
|
| 121 |
-
if prompt := st.chat_input("想瞭解哪方面的技術?"):
|
| 122 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
| 125 |
|
|
|
|
| 126 |
with st.chat_message("assistant"):
|
| 127 |
response_text = get_gemini_response(prompt)
|
| 128 |
st.markdown(response_text)
|
| 129 |
|
| 130 |
-
st.session_state.messages.append({"role": "assistant", "content": response_text})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import requests
|
| 4 |
import os
|
| 5 |
|
| 6 |
+
# 0. 頁面配置與 CSS 注入(隱藏側邊欄捲軸)
|
| 7 |
st.set_page_config(page_title="AI 新知小助手", page_icon="📚", layout="wide")
|
| 8 |
|
| 9 |
+
st.markdown(
|
| 10 |
+
"""
|
| 11 |
+
<style>
|
| 12 |
+
/* 隱藏側邊欄捲軸 */
|
| 13 |
+
[data-testid="stSidebar"] section::-webkit-scrollbar {
|
| 14 |
+
display: none;
|
| 15 |
+
}
|
| 16 |
+
[data-testid="stSidebar"] section {
|
| 17 |
+
-ms-overflow-style: none;
|
| 18 |
+
scrollbar-width: none;
|
| 19 |
+
}
|
| 20 |
+
/* 調整範例按鈕樣式 */
|
| 21 |
+
.stButton button {
|
| 22 |
+
width: auto;
|
| 23 |
+
padding: 5px 15px;
|
| 24 |
+
border-radius: 20px;
|
| 25 |
+
}
|
| 26 |
+
</style>
|
| 27 |
+
""",
|
| 28 |
+
unsafe_allow_html=True
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
# 從環境變數中取得 API Key
|
| 32 |
api_key = os.environ.get("GEMINI_API_KEY")
|
|
|
|
| 33 |
if not api_key:
|
| 34 |
+
st.error("請確認已經在 Space 的 Settings 設定了 GEMINI_API_KEY")
|
| 35 |
st.stop()
|
| 36 |
|
| 37 |
genai.configure(api_key=api_key)
|
| 38 |
|
| 39 |
# 1. 基礎設定與連結
|
| 40 |
BASE_URL = "https://raw.githubusercontent.com/Deep-Learning-101/deep-learning-101.github.io/main/"
|
| 41 |
+
LOGO_URL = f"{BASE_URL}DeepLearning101-LOGO.png"
|
| 42 |
HOME_URL = "https://deep-learning-101.github.io"
|
| 43 |
|
|
|
|
| 44 |
KNOWLEDGE_MAP = {
|
| 45 |
"大型語言模型 (LLM)": {
|
| 46 |
"raw_url": f"{BASE_URL}Large-Language-Model.md",
|
|
|
|
| 78 |
st.warning(f"無法同步 {category} 的資料:{e}")
|
| 79 |
return combined_knowledge
|
| 80 |
|
| 81 |
+
# 初始化 Session State
|
| 82 |
if "knowledge" not in st.session_state:
|
| 83 |
st.session_state.knowledge = fetch_all_knowledge()
|
| 84 |
|
| 85 |
if "messages" not in st.session_state:
|
| 86 |
st.session_state.messages = []
|
| 87 |
|
| 88 |
+
# 用於處理範例按鈕點擊的狀態
|
| 89 |
+
if "example_prompt" not in st.session_state:
|
| 90 |
+
st.session_state.example_prompt = None
|
| 91 |
+
|
| 92 |
# 3. 側邊欄設計
|
| 93 |
with st.sidebar:
|
| 94 |
+
st.markdown(f'<a href="{HOME_URL}" target="_blank"><img src="{LOGO_URL}" width="100%"></a>', unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
st.title("⚙️ 知識庫狀態")
|
|
|
|
|
|
|
|
|
|
| 96 |
for category, info in KNOWLEDGE_MAP.items():
|
| 97 |
with st.expander(category):
|
| 98 |
st.markdown(f"🔗 [瀏覽網頁]({info['page_url']})")
|
| 99 |
st.markdown(f"📂 [GitHub 原始碼]({info['repo_url']})")
|
|
|
|
| 100 |
st.markdown("---")
|
| 101 |
if st.button("🔄 手動更新知識庫"):
|
| 102 |
st.session_state.knowledge = fetch_all_knowledge()
|
| 103 |
st.success("資料已重新抓取!")
|
| 104 |
|
| 105 |
+
# 4. 主介面與範例問句
|
| 106 |
st.title("📚 AI 演算法與論文社群助手")
|
| 107 |
st.caption("知識庫涵蓋 LLM、NLP、Speech、CV。歡迎直接提問!")
|
| 108 |
|
| 109 |
+
# 顯示範例問句按鈕
|
| 110 |
+
example_cols = st.columns(3)
|
| 111 |
+
examples = [
|
| 112 |
+
"🤖 總結 LLM 的最新趨勢",
|
| 113 |
+
"🗣️ 語音處理有哪些新技術?",
|
| 114 |
+
"👁️ CV 領域目前的懶人包重點"
|
| 115 |
+
]
|
| 116 |
+
|
| 117 |
+
for col, ex in zip(example_cols, examples):
|
| 118 |
+
if col.button(ex):
|
| 119 |
+
st.session_state.example_prompt = ex
|
| 120 |
+
|
| 121 |
+
# 5. 模型回覆邏輯(含額度限制處理)
|
| 122 |
def get_gemini_response(user_input):
|
| 123 |
system_instruction = f"""
|
| 124 |
你是一位專業的 AI 技術分析專家。
|
|
|
|
| 127 |
{st.session_state.knowledge}
|
| 128 |
---
|
| 129 |
請嚴格基於上述提供的資訊來回答問題。
|
|
|
|
| 130 |
"""
|
| 131 |
+
try:
|
| 132 |
+
model = genai.GenerativeModel(
|
| 133 |
+
model_name="gemini-1.5-flash-latest",
|
| 134 |
+
system_instruction=system_instruction
|
| 135 |
+
)
|
| 136 |
+
chat = model.start_chat(history=[])
|
| 137 |
+
response = chat.send_message(user_input)
|
| 138 |
+
return response.text
|
| 139 |
+
except Exception as e:
|
| 140 |
+
# 捕捉 API 額度滿了 (429) 或其他錯誤
|
| 141 |
+
error_msg = str(e)
|
| 142 |
+
if "429" in error_msg or "quota" in error_msg.lower():
|
| 143 |
+
return "⚠️ **系統提示:API 使用額度已達上限**\n\n由於目前使用人數較多,Google AI Studio 的免費額度已暫時耗盡。請稍等幾分鐘後再試,或聯絡管理員更新 API Key。"
|
| 144 |
+
else:
|
| 145 |
+
return f"❌ **發生預期外錯誤**\n\n訊息:{error_msg}"
|
| 146 |
+
|
| 147 |
+
# 6. 對話邏輯
|
| 148 |
+
# 判斷是否有範例按鈕被點擊,或是使用者自行輸入
|
| 149 |
+
prompt = st.chat_input("想瞭解哪方面的技術?")
|
| 150 |
|
| 151 |
+
if st.session_state.example_prompt:
|
| 152 |
+
prompt = st.session_state.example_prompt
|
| 153 |
+
st.session_state.example_prompt = None # 用完即清空
|
|
|
|
| 154 |
|
| 155 |
+
if prompt:
|
|
|
|
| 156 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 157 |
+
|
| 158 |
+
# 顯示所有歷史訊息
|
| 159 |
+
for message in st.session_state.messages:
|
| 160 |
+
with st.chat_message(message["role"]):
|
| 161 |
+
st.markdown(message["content"])
|
| 162 |
|
| 163 |
+
# 產生新回覆
|
| 164 |
with st.chat_message("assistant"):
|
| 165 |
response_text = get_gemini_response(prompt)
|
| 166 |
st.markdown(response_text)
|
| 167 |
|
| 168 |
+
st.session_state.messages.append({"role": "assistant", "content": response_text})
|
| 169 |
+
st.rerun() # 強制重新整理以保持對話流暢
|
| 170 |
+
else:
|
| 171 |
+
# 僅在沒有新輸入時顯示歷史訊息
|
| 172 |
+
for message in st.session_state.messages:
|
| 173 |
+
with st.chat_message(message["role"]):
|
| 174 |
+
st.markdown(message["content"])
|