生产实习——项目说明文档

css样式说明

st.markdown("""
    <style>                
    .big-font {
        font-size:50px !important;
        color: #FFD622;
        animation: pulse 2s infinite;
    }
    @keyframes pulse {
        0% {
            transform: scale(1);
        }
        50% {
            transform: scale(1.1);
        }
        100% {
            transform: scale(1);
        }
    }
    </style>
    """, unsafe_allow_html=True)

这段css样式是对陈亮说的都对进行一个动态效果黄色,pulse是那个动态效果

下面这段代码是stbutton这个是对按钮进行样式美化,设置颜色为蓝色,圆形边框

hover是鼠标停留效果,设置按钮又悬浮作用,切换颜色,box-shadow是设置阴影

st.markdown("""
    <style>
    .stButton>button {
        color: #4F8BF9;
        border-radius: 50px;
        height: 3em;
        width: 12em;
        font-weight:bold;
        transition: all 0.3s ease-in-out;
    }

    .stButton>button:hover {
        background-color: #4F8BF9;
        color: white;
        border: none;
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
    }
    </style>
    """, unsafe_allow_html=True)

 下面这段css

body是调用roboto字体为蓝黑色

main除是设置主页面背景颜色,设置了阴影

textinpute 设置外圈为白色,输入框为淡蓝色

st.markdown("""
<style>
    @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap');

    body {
        font-family: 'Roboto', sans-serif;
        background-color: #e6f2ff;
        color: #1a5f7a;
    }
    .main {
        background-color: #f0f8ff;
        padding: 2rem;
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    .stButton>button {
        background-color: #4da3ff;
        color: white;
        border-radius: 20px;
        border: none;
        padding: 0.5rem 1rem;
        font-weight: bold;
    }
    .stTextInput>div>div>input {
        background-color: #ffffff;
        border-radius: 20px;
        border: 1px solid #b3d9ff;
        padding: 0.5rem 1rem;
    }
    .stSelectbox>div>div>input {
        background-color: #ffffff;
        border-radius: 20px;
        border: 1px solid #b3d9ff;
        padding: 0.5rem 1rem;
    }
    h1, h2, h3 {
        color: #1a5f7a;
    }
    .stSidebar {
        background-color: #4da3ff;
        color: white;
    }
    .stSidebar .sidebar-content {
        padding: 2rem 1rem;
    }
    .stSidebar .sidebar-content h1 {
        color: white;
        font-size: 1.5rem;
        margin-bottom: 2rem;
    }
    /* 自定义选项菜单样式 */
    .nav-link {
        color: #ffffff !important;
        background-color: #4da3ff;
    }
    .nav-link:hover, .nav-link.active {
        color: #4da3ff !important;
        background-color: #ffffff !important;
        font-weight: bold;
    }
    .nav-link-selected {
        background-color: #ffffff !important;
        color: #4da3ff !important;
        font-weight: bold;
    }
</style>
""", unsafe_allow_html=True)

颜色渐变效果

st.markdown("""
<style>
.main {
    background: linear-gradient(120deg, #E6F2FF 0%, #FFFFFF 100%);
}
.sidebar .sidebar-content {
    background: linear-gradient(180deg, #4da3ff 0%, #FFFFFF 100%);
}
.stApp {
    background: linear-gradient(120deg, #E6F2FF 0%, #FFFFFF 100%);
}
</style>
""", unsafe_allow_html=True)

 从streamlit_lottie库对应的网站中获取网页信息,并取得json文件信息的动画效果

def load_lottieurl(url: str):
    r = requests.get(url)
    if r.status_code != 200:
        return None
    return r.json()

第二个 resize_image 函数:

  1. 参数:

    • image: 输入的图像对象
    • max_size: 最大尺寸,默认为 (300, 300)
  2. 功能:

    • 保持图像的宽高比
    • 将图像调整到不超过指定的最大尺寸
  3. 步骤:

    • 获取原图的宽度和高度
    • 计算缩放比例,取宽度和高度缩放比例的较小值
    • 计算新的尺寸
    • 使用 image.resize() 调整图像大小,使用 LANCZOS 重采样方法
  4. 特点:

    • 同时考虑宽度和高度限制
    • 使用 LANCZOS 重采样,通常能提供更好的图像质量
    • 适合需要控制图像整体大小的场景
def resize_image(image, max_size=(300, 300)):
    img_width, img_height = image.size
    ratio = min(max_size[0] / img_width, max_size[1] / img_height)
    new_size = (int(img_width * ratio), int(img_height * ratio))
    return image.resize(new_size, Image.LANCZOS)

这段代码是一个名为chepai的函数,它实现了一个车牌检测工具的用户界面。让我详细解释一下这段代码:

  1. 函数开始时,声明了一些全局变量,这些可能在其他地方定义并在这个函数中使用。

  2. 使用st.header()设置了页面标题为"车牌检测工具"。

  3. 初始化session state:

    • 检查'predictions'是否在session state中,如果不在,则初始化为空列表。
    • session state用于在Streamlit应用的不同运行之间保持状态。
  4. 加载并显示一个Lottie动画:

    • 使用load_lottieurl()函数从URL加载动画。
    • 如果加载成功,使用st_lottie()显示动画。
  5. 显示所有之前的预测结果:

    • 遍历st.session_state.predictions中的所有预测。
    • 对每个预测,显示预测结果文本、原始图片和处理后的图片。
    • 使用resize_image()函数调整图片大小。
  6. 文件上传功能:

    • 使用st.file_uploader()创建一个文件上传器,允许用户上传图片。
  7. 处理上传的文件:

    • 如果有文件被上传,读取图片并转换为OpenCV格式。
    • 添加一个"开始预测"按钮。
    • 当按钮被点击时,调用process_frame()函数处理图片,获取处理后的图片和预测结果。
    • 将新的预测结果添加到session state中。
    • 使用st.experimental_rerun()重新运行应用以显示新结果。
  8. 清除功能:

    • 添加一个"清除所有预测"按钮。
    • 当按钮被点击时,清空st.session_state.predictions并重新运行应用。

这个函数使用了Streamlit库来创建Web应用界面,允许用户上传图片,进行车牌检测,并显示历史预测结果。它还包含了一些交互元素,如动画和按钮,以提升用户体验。

def chepai():
    global car_plate_w, car_plate_h, char_w, char_h, plate_model_path, char_model_path

    st.header("车牌检测工具")

    # 初始化 session state
    if 'predictions' not in st.session_state:
        st.session_state.predictions = []

    # 添加 Lottie 动画
    lottie_car = load_lottieurl("https://assets3.lottiefiles.com/packages/lf20_khzniaya.json")
    if lottie_car:
        st_lottie(lottie_car, height=200, key="car_animation")

    # 显示所有预测结果
    for i, pred in enumerate(st.session_state.predictions):
        st.write(f"预测 {i + 1}")
        st.write("预测结果:", pred['result'])

        cols = st.columns(2)
        with cols[0]:
            resized_image = resize_image(pred['original'])
            st.image(resized_image, caption='上传的图片')
        with cols[1]:
            resized_processed = resize_image(pred['processed'])
            st.image(resized_processed, caption='预测结果')

    # 文件上传
    uploaded_file = st.file_uploader("上传一张图片", type=["jpg", "jpeg", "png"])

    if uploaded_file is not None:
        # 读取原始图片
        image = Image.open(uploaded_file)
        img_array = np.array(image)
        img_cv2 = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)

        # 添加一个按钮来触发预测
        if st.button('开始预测'):
            # 进行预测
            processed_img, result = process_frame(img_cv2)

            # 保存预测结果
            st.session_state.predictions.append({
                'original': image,
                'processed': Image.fromarray(cv2.cvtColor(processed_img, cv2.COLOR_BGR2RGB)),
                'result': result
            })
            st.experimental_rerun()

    # 添加清除所有预测的按钮
    if st.button('清除所有预测'):
        st.session_state.predictions = []
        st.experimental_rerun()

这个函数 get_system_info() 用于获取当前系统的 CPU 和内存使用情况。让我详细解释一下:

  1. 函数定义:

    python复制代码

    def get_system_info():

    这定义了一个不需要参数的函数。

  2. 异常处理

    python复制代码

    try: # 主要代码 except Exception as e: # 错误处理

    使用 try-except 块来捕获可能发生的任何异常,确保函数不会因为错误而崩溃。

  3. 获取 CPU 使用率:

    python复制代码

    cpu = psutil.cpu_percent(interval=1)

    • 使用 psutil.cpu_percent() 函数获取 CPU 使用率。
    • interval=1 参数表示测量 1 秒内的 CPU 使用率。
    • 返回值是一个百分比。
  4. 获取内存使用率:

    python制代码

    memory = psutil.virtual_memory().percent

    • psutil.virtual_memory() 返回一个包含内存使用信息的对象。
    • .percent 属性获取内存使用的百分比。
  5. 返回格式化的字符串:

    python复制代码

    return f"CPU使用率: {cpu:.1f}%\n内存使用率: {memory:.1f}%"

    • 使用 f-string 格式化输出字符串。
    • {cpu:.1f} 和 {memory:.1f} 将数值格式化为一位小数。
    • \n 用于在 CPU 和内存信息之间换行。
  6. 错误处理:

    python复制代码

    return f"获取系统信息时出错: {str(e)}"

    如果在获取系统信息时发生任何异常,函数将返回一个错误信息。

总结:

  • 这个函数使用 psutil 库来获取系统的 CPU 和内存使用情况。
  • 它返回一个格式化的字符串,显示 CPU 和内存的使用百分比。
  • 使用异常处理来确保函数的稳定性,即使在获取系统信息失败的情况下也能返回有意义的信息。
  • 这种函数通常用于系统监控、性能分析或在应用程序中显示系统状态。
def get_system_info():
    try:
        cpu = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory().percent
        return f"CPU使用率: {cpu:.1f}%\n内存使用率: {memory:.1f}%"
    except Exception as e:
        return f"获取系统信息时出错: {str(e)}"

这个函数 execute_command(command) 用于执行系统命令并返回结果。让我详细解释一下这个函数的各个部分:

  1. 函数定义:

    python复制代码

    def execute_command(command):

    定义了一个接受 command 参数的函数,这个参数是要执行的命令字符串。

  2. 异常处理:

    python复制代码

    try: # 主要代码 except subprocess.TimeoutExpired: # 超时处理 except Exception as e: # 其他异常处理

    使用 try-except 块来处理可能发生的异常。

  3. 执行命令:

    python复制代码

    result = subprocess.run(command, capture_output=True, text=True, shell=True, timeout=10)

    • 使用 subprocess.run() 来执行命令。
    • capture_output=True: 捕获命令的标准输出和标准错误。
    • text=True: 将输出作为文本返回,而不是字节。
    • shell=True: 通过 shell 执行命令,允许使用 shell 特性。
    • timeout=10: 设置 10 秒的执行超时。
  4. 返回结果:

    python复制代码

    return result.stdout if result.stdout else result.stderr

    如果有标准输出,返回标准输出;否则返回标准错误。

  5. 超时处理:

    python复制代码

    except subprocess.TimeoutExpired: return "命令执行超时"

    如果命令执行超过 10 秒,捕获 TimeoutExpired 异常并返回超时消息。

  6. 其他异常处理:

    python复制代码

    except Exception as e: return str(e)

    捕获任何其他异常,并返回异常的字符串表示。

总结:

  • 这个函数用于安全地执行系统命令。
  • 它捕获命令的输出(无论是标准输出还是标准错误)。
  • 设置了 10 秒的超时限制,防止长时间运行的命令。
  • 使用 shell 执行命令,这提供了更多灵活性,但也可能带来安全风险。
  • 异常处理确保函数在遇到问题时不会崩溃,而是返回有意义的错误信息。
def execute_command(command):
    try:
        result = subprocess.run(command, capture_output=True, text=True, shell=True, timeout=10)
        return result.stdout if result.stdout else result.stderr
    except subprocess.TimeoutExpired:
        return "命令执行超时"
    except Exception as e:
        return str(e)

这段代码定义了三个函数,用于列出指定文件夹中的快捷方式、打开应用程序,以及处理系统命令。让我逐一解释:

  1. list_shortcuts(folder_path) 函数:

    • 作用:列出指定文件夹中的所有 .lnk 快捷方式文件。
    • 实现:使用列表推导式遍历文件夹中的所有文件,选择以 '.lnk' 结尾的文件。
    • 返回:一个包含所有快捷方式文件名的列表。
  2. open_application(shortcut_path) 函数:

    • 作用:尝试打开指定路径的快捷方式。
    • 实现:
      • 使用 subprocess.Popen() 来执行快捷方式。
      • shell=True 参数允许通过 shell 执行命令。
    • 异常处理:捕获任何可能发生的异常。
    • 返回:成功或失败的消息字符串。
  3. process_system_command(prompt) 函数:

    • 作用:处理用户输入的命令,尝试打开匹配的应用程序。
    • 实现:
      • 定义快捷方式文件夹路径 folder_path
      • 调用 list_shortcuts() 获取所有快捷方式。
      • 遍历快捷方式列表,检查用户输入是否包含快捷方式名(不区分大小写,忽略 .lnk 扩展名)。
      • 如果找到匹配,调用 open_application() 打开相应的应用程序。
    • 返回:打开应用程序的结果或未找到匹配应用的消息。

工作流程:

  1. 当调用 process_system_command(prompt) 时,它首先获取指定文件夹中的所有快捷方式。
  2. 然后,它检查用户输入的 prompt 是否包含任何快捷方式的名称。
  3. 如果找到匹配,它会尝试打开相应的应用程序。
  4. 如果没有找到匹配,它会返回一个未找到应用程序的消息。
def list_shortcuts(folder_path):
    shortcuts = [f for f in os.listdir(folder_path) if f.endswith('.lnk')]
    return shortcuts
def open_application(shortcut_path):
    try:
        subprocess.Popen(shortcut_path, shell=True)
        return f"成功打开 {os.path.basename(shortcut_path)}"
    except Exception as e:
        return f"无法打开 {os.path.basename(shortcut_path)}. 错误: {str(e)}"
def process_system_command(prompt):
    folder_path = r"F:\demo"
    shortcuts = list_shortcuts(folder_path)

    for shortcut in shortcuts:
        if shortcut.lower().replace('.lnk', '') in prompt.lower():
            shortcut_path = os.path.join(folder_path, shortcut)
            return open_application(shortcut_path)

    return "没有找到匹配的应用程序。"

这段

def showLLMChatbot():
    st.title("💬 大语言模型LLM聊天机器人")
    st.markdown("""
        欢迎使用我们的AI聊天机器人!很叼!
        你可以问我问题,也可以让我帮你打开应用程序。
        """)

    if "messages" not in st.session_state:
        st.session_state.messages = []

    for message in st.session_state.messages:
        with st.chat_message(message["role"]):
            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"):
            message_placeholder = st.empty()
            message_placeholder.markdown("🤔 正在处理...")

            if "打开" in prompt.lower():
                response = process_system_command(prompt)
            else:
                try:
                    full_conversation = "\n".join([f"{m['role']}: {m['content']}" for m in st.session_state.messages])
                    gen = Generation()
                    ai_response = gen.call(
                        model='qwen-turbo',
                        prompt=full_conversation,
                        api_key=API_KEY
                    )
                    response = ai_response["output"]["text"]
                except Exception as e:
                    response = f"抱歉,AI处理过程中发生错误:{str(e)}"

            st.session_state.messages.append({"role": "assistant", "content": response})
            message_placeholder.markdown(response)

    col1, col2 = st.columns(2)
    with col1:
        if st.button("🗑️  清除聊天记录"):
            st.session_state.messages = []
            st.experimental_rerun()
    with col2:
        if st.button(" 保存聊天记录"):
            save_chat_history()

代码定义了一个名为 showLLMChatbot 的函数,它创建了一个基于 Streamlit 的聊天机器人界面。让我详细解释一下这个函数的各个部分:

  1. 设置页面标题和介绍:

    • 使用 st.title() 设置页面标题。
    • 使用 st.markdown() 添加介绍文本。
  2. 初始化聊天记录:

    • 如果 st.session_state 中没有 "messages",则初始化为空列表。
  3. 显示聊天历史:

    • 遍历 st.session_state.messages 中的消息。
    • 使用 st.chat_message() 创建聊天气泡,显示每条消息。
  4. 处理用户输入:

    • 使用 st.chat_input() 创建输入框。
    • 当用户输入内容时,将其添加到聊天记录中。
  5. 生成回复:

    • 如果用户输入包含 "打开",调用 process_system_command() 处理系统命令。
    • 否则,使用 AI 模型生成回复:
      • 构建完整的对话历史。
      • 使用 Generation() 类调用 AI 模型(这里使用的是 'qwen-turbo' 模型)。
      • 捕获可能的异常并提供错误信息。
  6. 显示 AI 回复:

    • 创建一个占位符来显示 "正在处理" 消息。
    • 获取到回复后,更新占位符显示实际回复。
    • 将 AI 回复添加到聊天记录中。
  7. 添加功能按钮:

    • 创建两列布局。
    • 在第一列添加 "清除聊天记录" 按钮:
      • 点击时清空聊天记录并重新运行应用。
    • 在第二列添加 "保存聊天记录" 按钮:
      • 点击时调用 save_chat_history() 函数(此函数未在代码片段中定义)。

特点和注意事项:

  • 使用 Streamlit 的会话状态(st.session_state)来保持聊天历史。
  • 结合了系统命令处理和 AI 对话功能。
  • 使用 try-except 块来处理 AI 模型调用可能出现的错误。
  • 界面包含实时更新的聊天气泡和用户输入框。
  • 提供了清除和保存聊天记录的功能。
  • 代码假设存在 API_KEYGeneration 类和 process_system_command() 函数,这些可能在其他地方定义。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值