Qwen2.5-1.5B Streamlit进阶:添加语音输入、Markdown渲染、代码块高亮

张开发
2026/5/19 6:04:14 15 分钟阅读
Qwen2.5-1.5B Streamlit进阶:添加语音输入、Markdown渲染、代码块高亮
Qwen2.5-1.5B Streamlit进阶添加语音输入、Markdown渲染、代码块高亮1. 项目概述基于阿里通义千问Qwen2.5-1.5B-Instruct轻量级大语言模型我们已经构建了一个完全本地化部署的智能对话助手。现在我们将对这个基础版本进行功能升级添加三个实用功能语音输入、Markdown格式渲染和代码块语法高亮。这些增强功能将大幅提升用户体验语音输入支持通过麦克风直接输入问题特别适合移动设备使用Markdown渲染让模型的回复以更美观的格式展示支持标题、列表、表格等代码高亮对代码块进行语法高亮显示提升代码可读性这些功能都是在原有本地化部署的基础上实现的完全不涉及云端服务确保数据隐私安全。2. 环境准备与依赖安装2.1 基础环境要求确保你已经具备以下环境Python 3.8已部署Qwen2.5-1.5B-Instruct模型到本地路径基本的GPU环境可选CPU也可运行2.2 安装额外依赖在原有依赖基础上我们需要安装一些新的库pip install streamlit streamlit-microphone markdown pygments这些库的作用分别是streamlit-microphone提供语音输入功能markdown将Markdown文本转换为HTMLpygments代码语法高亮支持3. 语音输入功能实现3.1 语音输入组件集成我们在Streamlit侧边栏添加语音输入功能让用户可以通过麦克风输入问题import streamlit as st from streamlit_microphone import microphone_input # 在侧边栏添加语音输入 with st.sidebar: st.header( 语音输入) audio microphone_input( 点击开始录音, keymicrophone_input, callbackNone, ) if audio: # 这里可以添加语音识别代码 # 实际项目中需要集成语音识别API或本地模型 st.write(语音输入已接收正在处理...)3.2 语音识别处理在实际应用中你需要集成语音识别功能。这里提供一个简单的示例框架def speech_to_text(audio_data): 将音频数据转换为文本 实际项目中可以替换为本地语音识别模型或API调用 try: # 这里使用伪代码实际需要根据选择的语音识别方案实现 # 例如使用OpenAI Whisper、SpeechRecognition库等 text 这是语音识别后的文本 # 替换为实际识别结果 return text except Exception as e: st.error(f语音识别失败: {str(e)}) return None # 在语音输入处理部分 if audio: recognized_text speech_to_text(audio) if recognized_text: st.session_state.user_input recognized_text4. Markdown渲染功能4.1 Markdown文本处理为了让模型的回复以更美观的格式显示我们添加Markdown渲染功能import markdown from markdown.extensions.codehilite import CodeHiliteExtension def render_markdown(text): 将Markdown文本转换为HTML并渲染 try: # 添加代码高亮扩展 extensions [ markdown.extensions.extra, markdown.extensions.tables, CodeHiliteExtension(css_classhighlight) ] html markdown.markdown(text, extensionsextensions) return html except Exception as e: st.error(fMarkdown渲染失败: {str(e)}) return text4.2 安全渲染考虑由于渲染HTML可能存在安全风险我们需要进行适当的过滤import re from bs4 import BeautifulSoup def safe_markdown_render(text): 安全的Markdown渲染过滤潜在的危险HTML标签 # 首先渲染Markdown html_content render_markdown(text) # 使用BeautifulSoup过滤危险标签 soup BeautifulSoup(html_content, html.parser) # 允许的安全标签 allowed_tags [p, br, strong, em, ul, ol, li, h1, h2, h3, h4, h5, h6, blockquote, code, pre, span, div, table, thead, tbody, tr, th, td] # 过滤掉不在允许列表中的标签 for tag in soup.find_all(True): if tag.name not in allowed_tags: tag.unwrap() # 移除标签但保留内容 return str(soup)5. 代码块语法高亮5.1 代码高亮配置为了更好的代码显示效果我们配置Pygments进行语法高亮from pygments import highlight from pygments.lexers import get_lexer_by_name, guess_lexer from pygments.formatters import HtmlFormatter from pygments.style import Style from pygments.token import Token class CustomStyle(Style): 自定义代码高亮样式 styles { Token.Comment: italic #888, Token.Keyword: bold #0077aa, Token.String: #dd1144, Token.Name: #333, Token.Number: #009999, Token.Operator: #aa7700, } def highlight_code(code, languageNone): 对代码进行语法高亮 try: if language: lexer get_lexer_by_name(language, stripallTrue) else: lexer guess_lexer(code) formatter HtmlFormatter(styleCustomStyle, cssclasscodehilite, linenosFalse) return highlight(code, lexer, formatter) except: # 如果高亮失败返回原始代码 return fprecode{code}/code/pre5.2 集成到Markdown渲染将代码高亮功能集成到Markdown渲染中def enhanced_markdown_render(text): 增强的Markdown渲染包含代码高亮 # 先处理代码块 code_block_pattern r(\w)?\s*([\s\S]*?) def code_replacer(match): language match.group(1) or code match.group(2).strip() return highlight_code(code, language) # 先提取并高亮代码块 text_with_highlighted_code re.sub(code_block_pattern, code_replacer, text) # 然后渲染剩余的Markdown return safe_markdown_render(text_with_highlighted_code)6. 完整功能集成6.1 更新聊天界面将新功能集成到主聊天界面中import streamlit as st from streamlit_microphone import microphone_input # 初始化session state if messages not in st.session_state: st.session_state.messages [] # 页面配置 st.set_page_config(page_titleQwen2.5智能助手, page_icon, layoutwide) # 侧边栏设置 with st.sidebar: st.title( 设置) # 语音输入 st.header( 语音输入) audio microphone_input( 点击开始录音, keymicrophone_input, ) # 清空对话按钮 if st.button( 清空对话, use_container_widthTrue): st.session_state.messages [] st.rerun() # 主聊天区域 st.title( Qwen2.5智能助手) # 显示聊天记录 for message in st.session_state.messages: with st.chat_message(message[role]): if message[role] assistant: # 使用增强的Markdown渲染 st.markdown(enhanced_markdown_render(message[content]), unsafe_allow_htmlTrue) else: 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): with st.spinner(思考中...): response get_model_response(prompt, st.session_state.messages) # 使用增强渲染显示回复 st.markdown(enhanced_markdown_render(response), unsafe_allow_htmlTrue) # 添加到消息历史 st.session_state.messages.append({role: assistant, content: response})6.2 添加CSS样式为了更好的显示效果添加自定义CSS样式# 在Streamlit应用的适当位置添加CSS st.markdown( style /* 代码块样式 */ .codehilite { background-color: #f8f8f8; border: 1px solid #e1e4e8; border-radius: 6px; padding: 16px; margin: 16px 0; overflow-x: auto; } /* 语音输入按钮样式 */ .stMicrophone { margin-bottom: 10px; } /* 聊天气泡样式优化 */ .stChatMessage { padding: 16px; border-radius: 12px; margin: 8px 0; } /* 侧边栏样式 */ .css-1d391kg { padding: 20px; } /style , unsafe_allow_htmlTrue)7. 功能测试与优化7.1 测试不同场景建议测试以下场景以确保功能正常工作语音输入测试录制短语音检查识别准确性Markdown渲染测试输入包含标题、列表、表格的文本代码高亮测试测试Python、JavaScript、HTML等不同语言的代码块混合内容测试测试同时包含文本、代码、列表的复杂回复7.2 性能优化建议对于资源受限的环境可以考虑以下优化# 缓存昂贵的操作 st.cache_resource def get_highlighter(): 缓存代码高亮器实例 return HtmlFormatter(styleCustomStyle) # 延迟加载非核心功能 def lazy_load_audio(): 按需加载语音识别功能 try: import speech_recognition as sr return sr except ImportError: st.warning(语音识别功能需要额外安装speech-recognition包) return None8. 总结通过本次功能升级我们为Qwen2.5-1.5B本地智能对话助手添加了三个重要的用户体验增强功能语音输入功能让用户可以通过麦克风直接输入问题特别适合移动设备使用场景提升了交互的自然性和便捷性。Markdown渲染功能将模型的文本回复以更美观、结构化的方式展示支持标题、列表、表格等多种格式大幅提升了信息的可读性。代码块语法高亮功能专门优化了代码显示效果支持多种编程语言的语法高亮让代码示例更加清晰易读。所有这些功能都是在保持完全本地化部署的前提下实现的不依赖任何云端服务确保了用户数据的绝对隐私和安全。升级后的助手不仅功能更加强大用户体验也得到了显著提升真正实现了开箱即用、轻量高效的私有化AI对话解决方案。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。

更多文章