seb129225 commited on
Commit
55765db
·
verified ·
1 Parent(s): 094dfe2

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +282 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,284 @@
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 pandas as pd
3
+ import folium
4
+ from streamlit_folium import st_folium
5
+ import os
6
+ import requests
7
+ import io
8
+ from openai import OpenAI
9
+ import json
10
+
11
+
12
+ # --- 0. 配置与初始化 ---
13
+ st.set_page_config(
14
+ page_title="李白生平GIS与RAG整合",
15
+ page_icon="🐉",
16
+ layout="wide"
17
+ )
18
+
19
+ # 初始化OpenAI客户端
20
+ client = OpenAI(
21
+ api_key=os.getenv("DEEPSEEK_API_KEY", "sk-72997944466a4af2bcd52a068895f8cf"),
22
+ base_url="https://api.deepseek.com"
23
+ )
24
+
25
+ # ----------------------------------------------------
26
+ # 全局变量定义
27
+ # ----------------------------------------------------
28
+ GITHUB_XLSX_URL = "https://raw.githubusercontent.com/seblee424/5571_data/main/李白人生重要节点与代表作地理位置.xlsx"
29
+ location_col = '地点(古称/今称)'
30
+ summary_col = '诗作/事件摘要'
31
+
32
+
33
+ # --- 1. RAG 补充函数:抓取CBDB李白人物资料 ---
34
+ @st.cache_data(ttl=3600)
35
+ def get_cbdb_data(name="李白"):
36
+ url = f"https://cbdb.fas.harvard.edu/cbdbapi/person.php?name={name}&o=json"
37
+ headers = {"User-Agent": "Mozilla/5.0 (Streamlit App)"}
38
+ try:
39
+ response = requests.get(url, headers=headers, timeout=10)
40
+ if response.status_code == 200:
41
+ return response.json()
42
+ else:
43
+ return None
44
+ except Exception:
45
+ return None
46
+
47
+
48
+ # --- 2. 地理坐标匹配表 ---
49
+ LOCATION_COORDS = {
50
+ "碎叶城": {"lat": 42.8447, "lon": 75.1648, "match_keys": ["碎叶城"]},
51
+ "峨眉山": {"lat": 29.5807, "lon": 103.3592, "match_keys": ["峨眉山"]},
52
+ "蜀中": {"lat": 31.7828, "lon": 104.7570, "match_keys": ["蜀中", "江油"]},
53
+ "荆门/南津关": {"lat": 30.5667, "lon": 111.4500, "match_keys": ["荆门", "南津关"]},
54
+ "岳阳楼": {"lat": 29.3879, "lon": 113.1092, "match_keys": ["岳阳楼", "岳阳"]},
55
+ "安陆": {"lat": 31.3653, "lon": 113.7077, "match_keys": ["安陆"]},
56
+ "黄鹤楼": {"lat": 30.5484, "lon": 114.3168, "match_keys": ["黄鹤楼", "武汉"]},
57
+ "金陵(凤凰台)": {"lat": 32.0415, "lon": 118.7781, "match_keys": ["金陵", "凤凰台", "南京"]},
58
+ "庐山": {"lat": 29.5910, "lon": 115.9922, "match_keys": ["庐山", "九江"]},
59
+ "天姥山": {"lat": 29.5000, "lon": 120.8900, "match_keys": ["天姥山"]},
60
+ "金陵/长干里": {"lat": 32.0298, "lon": 118.7900, "match_keys": ["长干里"]},
61
+ "长安": {"lat": 34.2652, "lon": 108.9500, "match_keys": ["长安", "西安"]},
62
+ "长安/宫廷": {"lat": 34.2652, "lon": 108.9500, "match_keys": ["宫廷"]},
63
+ "长安/洛阳": {"lat": 34.6859, "lon": 112.4600, "match_keys": ["洛阳"]},
64
+ "桃花潭": {"lat": 30.4079, "lon": 118.4230, "match_keys": ["桃花潭", "泾县"]},
65
+ "敬亭山": {"lat": 30.9822, "lon": 118.7844, "match_keys": ["敬亭山", "宣城"]},
66
+ "天门山": {"lat": 31.4285, "lon": 118.3970, "match_keys": ["天门山", "芜湖"]},
67
+ "扬州/旅店": {"lat": 32.3934, "lon": 119.4290, "match_keys": ["扬州"]},
68
+ "夜郎": {"lat": 27.6888, "lon": 106.3773, "match_keys": ["夜郎", "桐梓"]},
69
+ "白帝城": {"lat": 31.0450, "lon": 109.5780, "match_keys": ["白帝城", "奉节"]},
70
+ "秋浦": {"lat": 30.6500, "lon": 117.4800, "match_keys": ["秋浦", "池州"]},
71
+ "当涂": {"lat": 31.5453, "lon": 118.4870, "match_keys": ["当涂", "马鞍山"]},
72
+
73
+ # 泛指类
74
+ "蜀道": {"lat": 31.0000, "lon": 107.0000, "match_keys": ["蜀道"]},
75
+ "月下独酌": {"lat": 34.2652, "lon": 108.9500, "match_keys": ["独酌", "月下"]},
76
+ "静夜思": {"lat": 32.3934, "lon": 119.4290, "match_keys": ["静夜思"]},
77
+ "长江沿线": {"lat": 30.5928, "lon": 114.3055, "match_keys": ["长江"]},
78
+ "战城南": {"lat": 35.0000, "lon": 100.0000, "match_keys": ["边塞", "战争"]},
79
+ "送友人": {"lat": 30.5928, "lon": 114.3055, "match_keys": ["送友人"]},
80
+ "将进酒": {"lat": 34.2652, "lon": 108.9500, "match_keys": ["将进酒", "豪饮"]},
81
+ "行路难": {"lat": 34.2652, "lon": 108.9500, "match_keys": ["行路难"]},
82
+ }
83
+
84
+
85
+ # --- 3. GitHub 在线加载 XLSX ---
86
+ @st.cache_data
87
+ def load_and_prepare_data_github(url):
88
+
89
+ try:
90
+ st.info("正在从 GitHub 加载 XLSX 数据...")
91
+ res = requests.get(url, timeout=10)
92
+
93
+ if res.status_code != 200:
94
+ st.error(f"GitHub 下载失败,状态码: {res.status_code}")
95
+ return pd.DataFrame()
96
+
97
+ df = pd.read_excel(io.BytesIO(res.content), sheet_name=0)
98
+ st.success("✅ 成功从 GitHub 加载数据!")
99
+
100
+ except Exception as e:
101
+ st.error(f"❌ 加载 GitHub XLSX 失败: {e}")
102
+ return pd.DataFrame()
103
+
104
+ df.columns = df.columns.str.strip()
105
+
106
+ if location_col not in df.columns or summary_col not in df.columns:
107
+ st.error(f"XLSX 缺少关键列: {location_col}, {summary_col}")
108
+ return pd.DataFrame()
109
+
110
+ # 经纬度匹配
111
+ coords_list = []
112
+ df["coords_key"] = ""
113
+
114
+ for idx, row in df.iterrows():
115
+ loc = str(row[location_col]).strip()
116
+ match = None
117
+ match_key = "未知"
118
+
119
+ for key, data in LOCATION_COORDS.items():
120
+ if loc == key:
121
+ match = data
122
+ match_key = key
123
+ break
124
+ if any(k in loc for k in data["match_keys"]):
125
+ match = data
126
+ match_key = key
127
+ break
128
+
129
+ if match:
130
+ coords_list.append((match["lat"], match["lon"]))
131
+ df.loc[idx, "coords_key"] = match_key
132
+ else:
133
+ coords_list.append((34.0478, 108.4357))
134
+
135
+ df["Latitude"] = [x[0] for x in coords_list]
136
+ df["Longitude"] = [x[1] for x in coords_list]
137
+
138
+ return df
139
+
140
+
141
+ # --- 使用 GitHub 数据加载 ---
142
+ data_df = load_and_prepare_data_github(GITHUB_XLSX_URL)
143
+
144
+
145
+ # --- 4. Chatbot (RAG) ---
146
+ def run_chatbot(cbdb_data, prompt):
147
+ cbdb_text = json.dumps(cbdb_data, ensure_ascii=False)[:5000] if cbdb_data else "无CBDB资料。"
148
+
149
+ system_prompt_rag = (
150
+ "你是一个李白生平研究的聊天机器人,擅长介绍李白的生平、作品和相关地点。"
151
+ "回答中如提及地点,请使用与地图匹配的地名,如安陆、桃花潭、黄鹤楼、长安。"
152
+ "引用 CBDB 信息时请在结尾标注“资料源自CBDB”。"
153
+ f"\n\nCBDB数据如下:{cbdb_text}"
154
+ )
155
+
156
+ try:
157
+ msgs = [{"role": "system", "content": system_prompt_rag}]
158
+ msgs.extend(st.session_state.chat_history[-5:])
159
+
160
+ resp = client.chat.completions.create(
161
+ model="deepseek-chat",
162
+ messages=msgs,
163
+ stream=False
164
+ )
165
+
166
+ answer = resp.choices[0].message.content.strip()
167
+
168
+ # 自动匹配回答的地名,对地图高亮
169
+ highlight = None
170
+ for key in data_df["coords_key"].unique():
171
+ if key != "未知" and key in answer:
172
+ highlight = key
173
+ break
174
+
175
+ st.session_state.highlight_location_key = highlight
176
+ return answer
177
+
178
+ except Exception as e:
179
+ return f"Chatbot 发生错误: {e}"
180
+
181
+
182
+ # --- 5. GIS 地图 ---
183
+ def create_li_bai_map(df, highlight_key):
184
+
185
+ if df.empty:
186
+ return folium.Map(location=[34.0, 108.0], zoom_start=4)
187
+
188
+ center_lat = df["Latitude"].mean()
189
+ center_lon = df["Longitude"].mean()
190
+
191
+ m = folium.Map(
192
+ location=[center_lat, center_lon],
193
+ zoom_start=4.5,
194
+ tiles="cartodbdarkmatter"
195
+ )
196
+
197
+ # 轨迹线
198
+ points = df[["Latitude", "Longitude"]].values.tolist()
199
+ if len(points) > 1:
200
+ folium.PolyLine(points, color="#00AEEF", weight=3, opacity=0.5).add_to(m)
201
+
202
+ # 节点
203
+ for _, row in df.iterrows():
204
+ is_high = (row["coords_key"] == highlight_key)
205
+
206
+ popup_html = f"""
207
+ <b>序号:</b> {row['序号']}<br>
208
+ <b>阶段:</b> {row['阶段(大致年份)']}<br>
209
+ <b>地点:</b> {row['地点(古称/今称)']}<br>
210
+ <b>事件/诗作:</b> {row['诗作/事件摘要']}<br>
211
+ <b>核心情感:</b> {row['核心情感/主题']}<br>
212
+ <b>节点类型:</b> {row['节点类型']}
213
+ """
214
+
215
+ if is_high:
216
+ color, icon = "orange", "fire"
217
+ elif "人生事件" in row["节点类型"]:
218
+ color, icon = "blue", "user"
219
+ else:
220
+ color, icon = "green", "flag"
221
+
222
+ folium.Marker(
223
+ [row["Latitude"], row["Longitude"]],
224
+ popup=folium.Popup(popup_html, max_width=300),
225
+ icon=folium.Icon(color=color, icon=icon, prefix="fa", icon_color="white"),
226
+ ).add_to(m)
227
+
228
+ return m
229
+
230
+
231
+ # --- 6. 主界面 ---
232
+ cbdb_data = get_cbdb_data("李白")
233
+
234
+ st.header("🐉 李白生平 GIS + RAG 交互系统")
235
+
236
+ if "chat_history" not in st.session_state:
237
+ st.session_state.chat_history = []
238
+
239
+ if "highlight_location_key" not in st.session_state:
240
+ st.session_state.highlight_location_key = None
241
+
242
+
243
+ if data_df.empty:
244
+ st.error("❌ 数据加载失败,请检查 GitHub 文件")
245
+ else:
246
+ col1, col2 = st.columns([1, 1.5])
247
+
248
+ # 左侧 Chatbot
249
+ with col1:
250
+ st.subheader("💬 李白 Chatbot")
251
+
252
+ if cbdb_data:
253
+ st.info("✅ 已加载 CBDB 资料")
254
+ else:
255
+ st.warning("⚠️ CBDB 资料加载失败")
256
+
257
+ for msg in st.session_state.chat_history:
258
+ with st.chat_message(msg["role"]):
259
+ st.markdown(msg["content"])
260
+
261
+ if prompt := st.chat_input("请输入你的问题…"):
262
+ with st.chat_message("user"):
263
+ st.markdown(prompt)
264
+
265
+ st.session_state.chat_history.append({"role": "user", "content": prompt})
266
+
267
+ with st.chat_message("assistant"):
268
+ with st.spinner("AI 正在思考…"):
269
+ answer = run_chatbot(cbdb_data, prompt)
270
+ st.write(answer)
271
+
272
+ if st.session_state.highlight_location_key:
273
+ st.success(f"地图已高亮:{st.session_state.highlight_location_key}")
274
+
275
+ st.session_state.chat_history.append({"role": "assistant", "content": answer})
276
+ st.rerun()
277
+
278
+ # 右侧 GIS
279
+ with col2:
280
+ st.subheader("🗺️ 李白一生足迹地图")
281
+ st.info("提示:左侧 Chatbot 会触发地图节点高亮")
282
 
283
+ current_map = create_li_bai_map(data_df, st.session_state.highlight_location_key)
284
+ st_folium(current_map, width=800, height=700)