DeepLearning101 commited on
Commit
4044773
·
verified ·
1 Parent(s): 7b568c7

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +93 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,95 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import google.generativeai as genai
3
+ import requests
4
 
5
+ st.set_page_config(page_title="AI 新知小助手", page_icon="📚", layout="wide")
6
+
7
+ if "GEMINI_API_KEY" not in st.secrets:
8
+ st.error("請在 Secrets 中設定 GEMINI_API_KEY")
9
+ st.stop()
10
+
11
+ genai.configure(api_key=st.secrets["GEMINI_API_KEY"])
12
+
13
+ # 1. 定義你要鎖定的 GitHub 檔案清單
14
+ # 請把 YOUR_ACCOUNT/YOUR_REPO 換成你真實的 GitHub 資訊
15
+ BASE_URL = "https://raw.githubusercontent.com/Deep-Learning-101/deep-learning-101.github.io/main/"
16
+ TARGET_FILES = {
17
+ "大型語言模型 (LLM)": f"{BASE_URL}Large-Language-Model.md",
18
+ "自然語言處理 (NLP)": f"{BASE_URL}Natural-Language-Processing.md",
19
+ "語音處理 (Speech)": f"{BASE_URL}Speech-Processing.md",
20
+ "電腦視覺 (CV)": f"{BASE_URL}Computer-Vision.md"
21
+ }
22
+
23
+ # 2. 批量抓取並格式化內容
24
+ def fetch_all_knowledge():
25
+ combined_knowledge = ""
26
+ with st.spinner("正在從 GitHub 同步 4 大領域最新資訊..."):
27
+ for category, url in TARGET_FILES.items():
28
+ try:
29
+ response = requests.get(url)
30
+ response.raise_for_status()
31
+ # 在每個檔案內容前加上明確的標題,幫助 AI 分類記憶
32
+ combined_knowledge += f"\n\n## 【領域:{category}】\n"
33
+ combined_knowledge += response.text
34
+ except Exception as e:
35
+ st.warning(f"無法同步 {category} 的資料:{e}")
36
+ return combined_knowledge
37
+
38
+ # 初始化 Session State
39
+ if "knowledge" not in st.session_state:
40
+ st.session_state.knowledge = fetch_all_knowledge()
41
+
42
+ if "messages" not in st.session_state:
43
+ st.session_state.messages = []
44
+
45
+ # 側邊欄設計
46
+ with st.sidebar:
47
+ st.title("⚙️ 知識庫狀態")
48
+ st.write("目前收錄以下領域:")
49
+ for category in TARGET_FILES.keys():
50
+ st.markdown(f"- {category}")
51
+
52
+ st.markdown("---")
53
+ if st.button("🔄 手動更新知識庫"):
54
+ st.session_state.knowledge = fetch_all_knowledge()
55
+ st.success("所有領域資料已重新抓取!")
56
+
57
+ # 主介面
58
+ st.title("📚 AI 演算法與論文社群助手")
59
+ st.caption("知識庫涵蓋 LLM、NLP、Speech、CV。歡迎直接提問!")
60
+
61
+ def get_gemini_response(user_input):
62
+ system_instruction = f"""
63
+ 你是一位專業的 AI 技術分析專家。
64
+ 以下是我從 GitHub 同步的四個領域 (LLM, NLP, Speech, CV) 的最新技術簡介與重點:
65
+ ---
66
+ {st.session_state.knowledge}
67
+ ---
68
+ 請嚴格基於上述提供的資訊來回答使用者的問題。
69
+ 如果使用者詢問了上述資訊中沒有涵蓋的細節,請明確告知:「目前這份懶人包中尚未收錄關於此問題的詳細資訊」。
70
+ """
71
+ model = genai.GenerativeModel(
72
+ model_name="gemini-1.5-pro",
73
+ system_instruction=system_instruction
74
+ )
75
+
76
+ chat = model.start_chat(history=[])
77
+ response = chat.send_message(user_input)
78
+ return response.text
79
+
80
+ # 顯示對話紀錄
81
+ for message in st.session_state.messages:
82
+ with st.chat_message(message["role"]):
83
+ st.markdown(message["content"])
84
+
85
+ # 接收輸入
86
+ if prompt := st.chat_input("例如:請幫我比較一下 CV 跟 NLP 目前常用的技術?"):
87
+ st.session_state.messages.append({"role": "user", "content": prompt})
88
+ with st.chat_message("user"):
89
+ st.markdown(prompt)
90
+
91
+ with st.chat_message("assistant"):
92
+ response_text = get_gemini_response(prompt)
93
+ st.markdown(response_text)
94
+
95
+ st.session_state.messages.append({"role": "assistant", "content": response_text})