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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
#!/usr/bin/env python
|
3 |
+
# -*- coding: utf-8 -*-
|
4 |
+
# @Time : 2024.4.16
|
5 |
+
# @Author : HinGwenWong
|
6 |
+
|
7 |
+
import copy
|
8 |
+
import os
|
9 |
+
import shutil
|
10 |
+
import time
|
11 |
+
from datetime import datetime
|
12 |
+
from pathlib import Path
|
13 |
+
|
14 |
+
import streamlit as st
|
15 |
+
import yaml
|
16 |
+
|
17 |
+
from utils.web_configs import WEB_CONFIGS
|
18 |
+
|
19 |
+
# 初始化 Streamlit 页面配置
|
20 |
+
st.set_page_config(
|
21 |
+
page_title="智能医导",
|
22 |
+
page_icon="🛒",
|
23 |
+
layout="wide",
|
24 |
+
initial_sidebar_state="expanded",
|
25 |
+
menu_items={
|
26 |
+
"Get Help": "https://github.com/nhbdgtgefr/Intelligent-Medical-Guidance-Large-Model/tree/main",
|
27 |
+
"About": "# 智能医导大模型",
|
28 |
+
},
|
29 |
+
)
|
30 |
+
from utils.rag.rag_worker import gen_rag_db
|
31 |
+
from utils.tools import resize_image
|
32 |
+
|
33 |
+
from utils.model_loader import RAG_RETRIEVER # isort:skip
|
34 |
+
|
35 |
+
|
36 |
+
@st.experimental_dialog("科室介绍", width="large")
|
37 |
+
def instruction_dialog(instruction_path):
|
38 |
+
"""
|
39 |
+
显示产品说明书的popup窗口。
|
40 |
+
|
41 |
+
通过给定的说明书路径,将文件内容以markdown格式在Streamlit应用中显示出来,并提供一个“确定”按钮供用户确认阅读。
|
42 |
+
|
43 |
+
Args:
|
44 |
+
instruction_path (str): 说明书的文件路径,该文件应为文本文件,并使用utf-8编码。
|
45 |
+
"""
|
46 |
+
print(f"Show instruction : {instruction_path}")
|
47 |
+
with open(instruction_path, "r", encoding="utf-8") as f:
|
48 |
+
instruct_lines = "".join(f.readlines())
|
49 |
+
|
50 |
+
# st.warning("一定要点击下方的【确定】按钮离开该页面", icon="⚠️")
|
51 |
+
st.markdown(instruct_lines)
|
52 |
+
# st.warning("一定要点击下方的【确定】按钮离开该页面", icon="⚠️")
|
53 |
+
if st.button("确定"):
|
54 |
+
st.rerun()
|
55 |
+
|
56 |
+
|
57 |
+
def on_btton_click(*args, **kwargs):
|
58 |
+
"""
|
59 |
+
按钮点击事件的回调函数。
|
60 |
+
"""
|
61 |
+
|
62 |
+
# 根据按钮类型执行相应操作
|
63 |
+
if kwargs["type"] == "check_instruction":
|
64 |
+
# 显示说明书
|
65 |
+
st.session_state.show_instruction_path = kwargs["instruction_path"]
|
66 |
+
|
67 |
+
elif kwargs["type"] == "process_sales":
|
68 |
+
# 切换到科室介绍页面
|
69 |
+
st.session_state.page_switch = "pages/selling_page.py"
|
70 |
+
|
71 |
+
# 更新会话状态中的产品信息
|
72 |
+
st.session_state.hightlight = kwargs["heighlights"]
|
73 |
+
product_info_struct = copy.deepcopy(st.session_state.product_info_struct_template)
|
74 |
+
product_info_str = product_info_struct[0].replace("{name}", kwargs["product_name"])
|
75 |
+
product_info_str += product_info_struct[1].replace("{highlights}", st.session_state.hightlight)
|
76 |
+
|
77 |
+
# 生成商品文案 prompt
|
78 |
+
st.session_state.first_input = copy.deepcopy(st.session_state.first_input_template).replace(
|
79 |
+
"{product_info}", product_info_str
|
80 |
+
)
|
81 |
+
|
82 |
+
# 更新图片路径和产品名称
|
83 |
+
st.session_state.image_path = kwargs["image_path"]
|
84 |
+
st.session_state.product_name = kwargs["product_name"]
|
85 |
+
|
86 |
+
# 更新发货地、快递公司名称
|
87 |
+
# st.session_state.departure_place = kwargs["departure_place"]
|
88 |
+
# st.session_state.delivery_company_name = kwargs["delivery_company_name"]
|
89 |
+
|
90 |
+
# 设置为默认数字人视频路径
|
91 |
+
st.session_state.digital_human_video_path = WEB_CONFIGS.DIGITAL_HUMAN_VIDEO_PATH
|
92 |
+
|
93 |
+
# # 清空语音
|
94 |
+
# if ENABLE_TTS:
|
95 |
+
# for message in st.session_state.messages:
|
96 |
+
# if "wav" not in message:
|
97 |
+
# continue
|
98 |
+
# Path(message["wav"]).unlink()
|
99 |
+
|
100 |
+
# 清空历史对话
|
101 |
+
st.session_state.messages = []
|
102 |
+
|
103 |
+
|
104 |
+
def make_product_container(product_name, product_info, image_height, each_card_offset):
|
105 |
+
"""
|
106 |
+
创建并展示产品信息容器。
|
107 |
+
|
108 |
+
参数:
|
109 |
+
- product_name: 产品名称。
|
110 |
+
- product_info: 包含产品信息的字典,需包括图片路径、特点和说明书路径。
|
111 |
+
- image_height: 图片展示区域的高度。
|
112 |
+
- each_card_offset: 容器内各部分间距。
|
113 |
+
"""
|
114 |
+
|
115 |
+
# 创建带边框的产品信息容器,设置高度
|
116 |
+
with st.container(border=True, height=image_height + each_card_offset):
|
117 |
+
|
118 |
+
# 页面标题
|
119 |
+
st.header(product_name)
|
120 |
+
|
121 |
+
# 划分左右两列,左侧为图片,右侧为商品信息
|
122 |
+
image_col, info_col = st.columns([0.2, 0.8])
|
123 |
+
|
124 |
+
# 图片展示区域
|
125 |
+
with image_col:
|
126 |
+
# print(f"Loading {product_info['images']} ...")
|
127 |
+
image = resize_image(product_info["images"], max_height=image_height)
|
128 |
+
st.image(image, channels="bgr")
|
129 |
+
|
130 |
+
# 产品信息展示区域
|
131 |
+
with info_col:
|
132 |
+
|
133 |
+
# 说明书按钮
|
134 |
+
st.subheader("科室介绍", divider="grey")
|
135 |
+
st.button(
|
136 |
+
"查看",
|
137 |
+
key=f"check_instruction_{product_name}",
|
138 |
+
on_click=on_btton_click,
|
139 |
+
kwargs={
|
140 |
+
"type": "check_instruction",
|
141 |
+
"product_name": product_name,
|
142 |
+
"instruction_path": product_info["instruction"],
|
143 |
+
},
|
144 |
+
)
|
145 |
+
|
146 |
+
# 主要信息展示
|
147 |
+
st.subheader("主要医生", divider="grey")
|
148 |
+
|
149 |
+
heighlights_str = "、".join(product_info["heighlights"])
|
150 |
+
st.text(heighlights_str)
|
151 |
+
|
152 |
+
|
153 |
+
# st.button("更新", key=f"update_manual_{product_name}")
|
154 |
+
|
155 |
+
# 讲解按钮
|
156 |
+
st.subheader("医导小助手", divider="grey")
|
157 |
+
st.button(
|
158 |
+
"开始讲解",
|
159 |
+
key=f"process_sales_{product_name}",
|
160 |
+
on_click=on_btton_click,
|
161 |
+
kwargs={
|
162 |
+
"type": "process_sales",
|
163 |
+
"product_name": product_name,
|
164 |
+
"heighlights": heighlights_str,
|
165 |
+
"image_path": product_info["images"],
|
166 |
+
# "departure_place": product_info["departure_place"],
|
167 |
+
# "delivery_company_name": product_info["delivery_company_name"],
|
168 |
+
},
|
169 |
+
)
|
170 |
+
|
171 |
+
|
172 |
+
def delete_old_files(directory, limit_time_s=60 * 60 * 5):
|
173 |
+
"""
|
174 |
+
删除指定目录下超过一定时间的文件。
|
175 |
+
|
176 |
+
:param directory: 要检查和删除文件的目录路径
|
177 |
+
"""
|
178 |
+
# 获取当前时间戳
|
179 |
+
current_time = time.time()
|
180 |
+
|
181 |
+
# 遍历目录下的所有文件和子目录
|
182 |
+
for file_path in Path(directory).iterdir():
|
183 |
+
|
184 |
+
# 获取文件的修改时间戳
|
185 |
+
file_mtime = os.path.getmtime(file_path)
|
186 |
+
|
187 |
+
# 计算文件的年龄(以秒为单位)
|
188 |
+
file_age_seconds = current_time - file_mtime
|
189 |
+
|
190 |
+
# 检查文件是否超过 n 秒
|
191 |
+
if file_age_seconds > limit_time_s:
|
192 |
+
try:
|
193 |
+
|
194 |
+
if file_path.is_dir():
|
195 |
+
shutil.rmtree(file_path)
|
196 |
+
continue
|
197 |
+
|
198 |
+
# 删除文件
|
199 |
+
file_path.unlink()
|
200 |
+
print(f"Deleted: {file_path}")
|
201 |
+
except Exception as e:
|
202 |
+
print(f"Error deleting {file_path}: {e}")
|
203 |
+
|
204 |
+
|
205 |
+
def get_sales_info():
|
206 |
+
"""
|
207 |
+
从配置文件中加载销售相关信息,并存储到session状态中。
|
208 |
+
|
209 |
+
该函数不接受参数,也不直接返回任何值,但会更新全局的session状态,包括:
|
210 |
+
- sales_info: 系统问候语,针对销售角色定制
|
211 |
+
- first_input_template: 对话开始时的第一个输入模板
|
212 |
+
- product_info_struct_template: 产品信息结构模板
|
213 |
+
|
214 |
+
"""
|
215 |
+
|
216 |
+
# 加载对话配置文件
|
217 |
+
with open(WEB_CONFIGS.CONVERSATION_CFG_YAML_PATH, "r", encoding="utf-8") as f:
|
218 |
+
dataset_yaml = yaml.safe_load(f)
|
219 |
+
|
220 |
+
role_type_data = dataset_yaml.get("role_type", {})
|
221 |
+
if WEB_CONFIGS.SALES_NAME in role_type_data:
|
222 |
+
sales_info = role_type_data[WEB_CONFIGS.SALES_NAME]
|
223 |
+
else:
|
224 |
+
print(f"键 '{WEB_CONFIGS.SALES_NAME}' 不存在于 'role_type' 中")
|
225 |
+
sales_info = None # 或者赋予一个默认值
|
226 |
+
|
227 |
+
# 从配置中提取角色信息
|
228 |
+
sales_info = dataset_yaml["role_type"][WEB_CONFIGS.SALES_NAME]
|
229 |
+
|
230 |
+
# 从配置中提取对话设置相关的信息
|
231 |
+
system = dataset_yaml["conversation_setting"]["system"]
|
232 |
+
first_input = dataset_yaml["conversation_setting"]["first_input"]
|
233 |
+
product_info_struct = dataset_yaml["product_info_struct"]
|
234 |
+
|
235 |
+
# 将销售角色名和角色信息插入到 system prompt
|
236 |
+
system_str = system.replace("{role_type}", WEB_CONFIGS.SALES_NAME).replace("{character}", "、".join(sales_info))
|
237 |
+
|
238 |
+
# 更新session状态,存储销售相关信息
|
239 |
+
st.session_state.sales_info = system_str
|
240 |
+
st.session_state.first_input_template = first_input
|
241 |
+
st.session_state.product_info_struct_template = product_info_struct
|
242 |
+
|
243 |
+
|
244 |
+
def init_product_info():
|
245 |
+
# 读取 yaml 文件
|
246 |
+
with open(WEB_CONFIGS.PRODUCT_INFO_YAML_PATH, "r", encoding="utf-8") as f:
|
247 |
+
product_info_dict = yaml.safe_load(f)
|
248 |
+
|
249 |
+
# 根据 ID 排序,避免乱序
|
250 |
+
product_info_dict = dict(sorted(product_info_dict.items(), key=lambda item: item[1]["id"]))
|
251 |
+
|
252 |
+
product_name_list = list(product_info_dict.keys())
|
253 |
+
|
254 |
+
# 生成商品信息
|
255 |
+
for row_id in range(0, len(product_name_list), WEB_CONFIGS.EACH_ROW_COL):
|
256 |
+
for col_id, col_handler in enumerate(st.columns(WEB_CONFIGS.EACH_ROW_COL)):
|
257 |
+
with col_handler:
|
258 |
+
if row_id + col_id >= len(product_name_list):
|
259 |
+
continue
|
260 |
+
|
261 |
+
product_name = product_name_list[row_id + col_id]
|
262 |
+
make_product_container(
|
263 |
+
product_name, product_info_dict[product_name], WEB_CONFIGS.PRODUCT_IMAGE_HEIGHT, WEB_CONFIGS.EACH_CARD_OFFSET
|
264 |
+
)
|
265 |
+
|
266 |
+
return len(product_name_list)
|
267 |
+
|
268 |
+
|
269 |
+
def init_tts():
|
270 |
+
# TTS 初始化
|
271 |
+
if "gen_tts_checkbox" not in st.session_state:
|
272 |
+
st.session_state.gen_tts_checkbox = WEB_CONFIGS.ENABLE_TTS
|
273 |
+
if WEB_CONFIGS.ENABLE_TTS:
|
274 |
+
# 清除 1 小时之前的所有语音
|
275 |
+
Path(WEB_CONFIGS.TTS_WAV_GEN_PATH).mkdir(parents=True, exist_ok=True)
|
276 |
+
delete_old_files(WEB_CONFIGS.TTS_WAV_GEN_PATH)
|
277 |
+
|
278 |
+
|
279 |
+
def init_digital_human():
|
280 |
+
# 数字人 初始化
|
281 |
+
if "digital_human_video_path" not in st.session_state:
|
282 |
+
st.session_state.digital_human_video_path = WEB_CONFIGS.DIGITAL_HUMAN_VIDEO_PATH
|
283 |
+
if "gen_digital_human_checkbox" not in st.session_state:
|
284 |
+
st.session_state.gen_digital_human_checkbox = WEB_CONFIGS.ENABLE_DIGITAL_HUMAN
|
285 |
+
|
286 |
+
if WEB_CONFIGS.ENABLE_DIGITAL_HUMAN:
|
287 |
+
# 清除 1 小时之前的所有视频
|
288 |
+
Path(WEB_CONFIGS.DIGITAL_HUMAN_GEN_PATH).mkdir(parents=True, exist_ok=True)
|
289 |
+
# delete_old_files(st.session_state.digital_human_root)
|
290 |
+
|
291 |
+
|
292 |
+
def init_asr():
|
293 |
+
# 清理 ASR 旧文件
|
294 |
+
if WEB_CONFIGS.ENABLE_ASR and Path(WEB_CONFIGS.ASR_WAV_SAVE_PATH).exists():
|
295 |
+
delete_old_files(WEB_CONFIGS.ASR_WAV_SAVE_PATH)
|
296 |
+
|
297 |
+
st.session_state.asr_text_cache = ""
|
298 |
+
|
299 |
+
|
300 |
+
def main():
|
301 |
+
"""
|
302 |
+
初始化页面配置,加载模型,处理页面跳转,并展示商品信息。
|
303 |
+
"""
|
304 |
+
print("Starting...")
|
305 |
+
|
306 |
+
# 初始化页面跳转
|
307 |
+
if "page_switch" not in st.session_state:
|
308 |
+
st.session_state.page_switch = "app.py"
|
309 |
+
st.session_state.current_page = "app.py"
|
310 |
+
|
311 |
+
# 显示商品说明书
|
312 |
+
if "show_instruction_path" not in st.session_state:
|
313 |
+
st.session_state.show_instruction_path = "X-X"
|
314 |
+
if st.session_state.show_instruction_path != "X-X":
|
315 |
+
instruction_dialog(st.session_state.show_instruction_path)
|
316 |
+
st.session_state.show_instruction_path = "X-X"
|
317 |
+
|
318 |
+
# 判断是否需要跳转页面
|
319 |
+
if st.session_state.page_switch != st.session_state.current_page:
|
320 |
+
st.switch_page(st.session_state.page_switch)
|
321 |
+
|
322 |
+
# TTS 初始化
|
323 |
+
init_tts()
|
324 |
+
|
325 |
+
# 数字人 初始化
|
326 |
+
init_digital_human()
|
327 |
+
|
328 |
+
# ASR 初始化
|
329 |
+
init_asr()
|
330 |
+
|
331 |
+
if "enable_agent_checkbox" not in st.session_state:
|
332 |
+
st.session_state.enable_agent_checkbox = WEB_CONFIGS.ENABLE_AGENT
|
333 |
+
|
334 |
+
if WEB_CONFIGS.AGENT_DELIVERY_TIME_API_KEY is None or WEB_CONFIGS.AGENT_WEATHER_API_KEY is None:
|
335 |
+
WEB_CONFIGS.ENABLE_AGENT = False
|
336 |
+
st.session_state.enable_agent_checkbox = False
|
337 |
+
|
338 |
+
# 获取销售信息
|
339 |
+
if "sales_info" not in st.session_state:
|
340 |
+
get_sales_info()
|
341 |
+
|
342 |
+
|
343 |
+
|
344 |
+
# 主页标题
|
345 |
+
|
346 |
+
st.title("智能医导大模型")
|
347 |
+
# st.header("商品页")
|
348 |
+
# 说明
|
349 |
+
st.info(
|
350 |
+
"这是小助手后台,这里需要小助手讲解的科室信息目录,选择一个科室,点击【开始讲解】即可跳转到小助手讲解页面。如果需要加入更多信息,点击下方的添加按钮即可",
|
351 |
+
icon="ℹ️",
|
352 |
+
)
|
353 |
+
|
354 |
+
# 初始化商品列表
|
355 |
+
product_num = init_product_info()
|
356 |
+
|
357 |
+
# 侧边栏显示产品数量,入驻品牌方
|
358 |
+
with st.sidebar:
|
359 |
+
# 标题
|
360 |
+
st.header("智能医导大模型", divider="grey")
|
361 |
+
st.markdown("[智能医导大模型](https://github.com/nhbdgtgefr/item)")
|
362 |
+
|
363 |
+
|
364 |
+
st.subheader(f"小助手后台信息", divider="grey")
|
365 |
+
st.markdown(f"共有科室:{product_num} 个")
|
366 |
+
|
367 |
+
# TODO 单品成交量
|
368 |
+
# st.markdown(f"共有品牌方:{len(product_name_list)} 个")
|
369 |
+
|
370 |
+
if WEB_CONFIGS.ENABLE_TTS:
|
371 |
+
# 是否生成 TTS
|
372 |
+
st.subheader(f"TTS 配置", divider="grey")
|
373 |
+
st.session_state.gen_tts_checkbox = st.toggle("生成语音", value=st.session_state.gen_tts_checkbox)
|
374 |
+
|
375 |
+
if WEB_CONFIGS.ENABLE_DIGITAL_HUMAN:
|
376 |
+
# 是否生成 数字人
|
377 |
+
st.subheader(f"数字人 配置", divider="grey")
|
378 |
+
st.session_state.gen_digital_human_checkbox = st.toggle(
|
379 |
+
"生成数字人视频", value=st.session_state.gen_digital_human_checkbox
|
380 |
+
)
|
381 |
+
|
382 |
+
# if WEB_CONFIGS.ENABLE_AGENT:
|
383 |
+
# 是否使用 agent
|
384 |
+
# st.subheader(f"Agent 配置", divider="grey")
|
385 |
+
# with st.container(border=True):
|
386 |
+
# st.markdown("**插件列表**")
|
387 |
+
# st.button("结合天气查询到货时间", type="primary")
|
388 |
+
# st.session_state.enable_agent_checkbox = st.toggle("使用 Agent 能力", value=st.session_state.enable_agent_checkbox)
|
389 |
+
|
390 |
+
# 添加新商品上传表单
|
391 |
+
with st.form(key="add_product_form"):
|
392 |
+
product_name_input = st.text_input(label="添加科室名称")
|
393 |
+
heightlight_input = st.text_input(label="添加科室医生,以'、'隔开")
|
394 |
+
# departure_place_input = st.text_input(label="发货地")
|
395 |
+
# delivery_company_input = st.text_input(label="快递公司名称")
|
396 |
+
product_image = st.file_uploader(label="上传科室图片", type=["png", "jpg", "jpeg", "bmp"])
|
397 |
+
product_instruction = st.file_uploader(label="上传科室说明书", type=["md"])
|
398 |
+
submit_button = st.form_submit_button(label="提交", disabled=WEB_CONFIGS.DISABLE_UPLOAD)
|
399 |
+
|
400 |
+
if WEB_CONFIGS.DISABLE_UPLOAD:
|
401 |
+
st.info(
|
402 |
+
"Github 上面的代码已支持上传新信息逻辑。\n但因开放性的 Web APP 没有新增信息审核机制,暂不在此开放上传信息。\n您可以 clone 本项目到您的机器启动即可使能上传按钮",
|
403 |
+
icon="ℹ️",
|
404 |
+
)
|
405 |
+
|
406 |
+
if submit_button:
|
407 |
+
update_product_info(
|
408 |
+
product_name_input,
|
409 |
+
heightlight_input,
|
410 |
+
product_image,
|
411 |
+
product_instruction,
|
412 |
+
# departure_place_input,
|
413 |
+
# delivery_company_input,
|
414 |
+
)
|
415 |
+
|
416 |
+
|
417 |
+
def update_product_info(
|
418 |
+
product_name_input, heightlight_input, product_image, product_instruction
|
419 |
+
):
|
420 |
+
"""
|
421 |
+
更新产品信息的函数。
|
422 |
+
|
423 |
+
参数:
|
424 |
+
- product_name_input: 商品名称输入,字符串类型。
|
425 |
+
- heightlight_input: 商品特性输入,字符串类型。
|
426 |
+
- product_image: 商品图片,图像类型。
|
427 |
+
- product_instruction: 商品说明书,文本类型。
|
428 |
+
- departure_place: 发货地。
|
429 |
+
- delivery_company: 快递公司。
|
430 |
+
|
431 |
+
返回值:
|
432 |
+
无。该函数直接操作UI状态,不返回任何值。
|
433 |
+
"""
|
434 |
+
|
435 |
+
# TODO 可以不输入图片和特性,大模型自动生成一版让用户自行选择
|
436 |
+
|
437 |
+
# 检查入参
|
438 |
+
if product_name_input == "" or heightlight_input == "":
|
439 |
+
st.error("科室名称和主要医生不能为空")
|
440 |
+
return
|
441 |
+
|
442 |
+
if product_image is None or product_instruction is None:
|
443 |
+
st.error("图片和科室介绍不能为空")
|
444 |
+
return
|
445 |
+
|
446 |
+
# if departure_place == "" or delivery_company == "":
|
447 |
+
# st.error("发货地和快递公司名称不能为空")
|
448 |
+
# return
|
449 |
+
|
450 |
+
# 显示上传状态,并执行上传操作
|
451 |
+
with st.status("正在上传...", expanded=True) as status:
|
452 |
+
|
453 |
+
save_tag = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
|
454 |
+
image_save_path = Path(WEB_CONFIGS.PRODUCT_IMAGES_DIR).joinpath(f"{save_tag}{Path(product_image.name).suffix}")
|
455 |
+
instruct_save_path = Path(WEB_CONFIGS.PRODUCT_INSTRUCTION_DIR).joinpath(
|
456 |
+
f"{save_tag}{Path(product_instruction.name).suffix}"
|
457 |
+
)
|
458 |
+
|
459 |
+
st.write("图片保存中...")
|
460 |
+
with open(image_save_path, "wb") as file:
|
461 |
+
file.write(product_image.getvalue())
|
462 |
+
|
463 |
+
st.write("科室介绍保存中...")
|
464 |
+
with open(instruct_save_path, "wb") as file:
|
465 |
+
file.write(product_instruction.getvalue())
|
466 |
+
|
467 |
+
st.write("更新科室明细表...")
|
468 |
+
with open(WEB_CONFIGS.PRODUCT_INFO_YAML_PATH, "r", encoding="utf-8") as f:
|
469 |
+
product_info_dict = yaml.safe_load(f)
|
470 |
+
|
471 |
+
# 排序防止乱序
|
472 |
+
product_info_dict = dict(sorted(product_info_dict.items(), key=lambda item: item[1]["id"]))
|
473 |
+
max_id_key = max(product_info_dict, key=lambda x: product_info_dict[x]["id"])
|
474 |
+
|
475 |
+
product_info_dict.update(
|
476 |
+
{
|
477 |
+
product_name_input: {
|
478 |
+
"heighlights": heightlight_input.split("、"),
|
479 |
+
"images": str(image_save_path),
|
480 |
+
"instruction": str(instruct_save_path),
|
481 |
+
"id": product_info_dict[max_id_key]["id"] + 1,
|
482 |
+
# "departure_place": departure_place,
|
483 |
+
# "delivery_company_name": delivery_company,
|
484 |
+
}
|
485 |
+
}
|
486 |
+
)
|
487 |
+
|
488 |
+
# 备份
|
489 |
+
if Path(WEB_CONFIGS.PRODUCT_INFO_YAML_BACKUP_PATH).exists():
|
490 |
+
Path(WEB_CONFIGS.PRODUCT_INFO_YAML_BACKUP_PATH).unlink()
|
491 |
+
shutil.copy(WEB_CONFIGS.PRODUCT_INFO_YAML_PATH, WEB_CONFIGS.PRODUCT_INFO_YAML_BACKUP_PATH)
|
492 |
+
|
493 |
+
# 覆盖保存
|
494 |
+
with open(WEB_CONFIGS.PRODUCT_INFO_YAML_PATH, "w", encoding="utf-8") as f:
|
495 |
+
yaml.dump(product_info_dict, f, allow_unicode=True)
|
496 |
+
|
497 |
+
st.write("生成数据库...")
|
498 |
+
if WEB_CONFIGS.ENABLE_RAG:
|
499 |
+
# 重新生成 RAG 向量数据库
|
500 |
+
gen_rag_db(force_gen=True)
|
501 |
+
|
502 |
+
# 重新加载 retriever
|
503 |
+
RAG_RETRIEVER.pop("default")
|
504 |
+
RAG_RETRIEVER.get(fs_id="default", config_path=WEB_CONFIGS.RAG_CONFIG_PATH, work_dir=WEB_CONFIGS.RAG_VECTOR_DB_DIR)
|
505 |
+
|
506 |
+
# 更新状态
|
507 |
+
status.update(label="添加科室信息成功!", state="complete", expanded=False)
|
508 |
+
|
509 |
+
st.toast("添加信息成功!", icon="🎉")
|
510 |
+
|
511 |
+
with st.spinner("准备刷新页面..."):
|
512 |
+
time.sleep(3)
|
513 |
+
|
514 |
+
# 刷新页面
|
515 |
+
st.rerun()
|
516 |
+
|
517 |
+
|
518 |
+
if __name__ == "__main__":
|
519 |
+
# streamlit run app.py --server.address=0.0.0.0 --server.port 7860
|
520 |
+
|
521 |
+
# print("Starting...")
|
522 |
+
main()
|