测试data_management函数
测试data_management函数
这是我最近正在开发的AI工具信息平台的部门功能模块测试,基于streamlit架构。整理出来与大家分享,也为我以后自己回溯找到资源。
为了测试 data_management 函数并结合 Excel 文件中的 “Tools” 表单内容,我们需要进行以下步骤:
- 确保 Excel 文件准备好:你的 Excel 文件(例如
test_tools.xlsx)应包含相关的工具数据。 - 实现
save_all_data函数:确保有一个函数用于保存数据回 Excel 文件。 - 编写完整的测试代码:将
data_management函数整合到一个 Streamlit 应用中,以便从 Excel 读取数据、执行管理操作并实时展示结果。
步骤 1:准备 Excel 文件
确保你的 Excel 文件 test_tools.xlsx 内容如下:
| Name | Category | Country | Company | Description | URL | Open Source | Popularity | LastUpdated |
|---|---|---|---|---|---|---|---|---|
| 通义千问 | 大语言模型 | 中国 | 阿里巴巴 | 阿里云企业级大模型平台 | https://tongyi.aliyun.com | 否 | 400 | 2024/2/11 |
| 智谱清言App | 大语言模型 | 中国 | 智谱AI | 新一代认知智能大模型,提供对话、问答等功能 | https://chatglm.cn/ | 否 | 5000 | 2025/1/22 |
| Tool A | 大语言模型 | USA | Company A | A great tool | http://example.com | 是 | 100 | 2023/1/1 |
| Tool B | 大语言模型 | Canada | Company B | Another great tool | http://example2.com | 否 | 200 | 2023/1/2 |
| Tool C | 大语言模型 | UK | Company C | Amazing tool | http://example3.com | 是 | 150 | 2023/1/3 |
步骤 2:实现 save_all_data 函数
确保你能将数据保存回 Excel 文件。以下是一个简单的示例实现:
def save_all_data(excel_file, tools_data, tutorials_data):"""保存所有数据到 Excel 文件"""with pd.ExcelWriter(excel_file) as writer:# 将工具数据写入工作表for category, items in tools_data.items():df = pd.DataFrame(items)df.to_excel(writer, sheet_name=category, index=False)# 如果有教程数据,也可以保存到对应的工作表if tutorials_data: # 示例,如果有必要可以添加处理tutorials_df = pd.DataFrame(tutorials_data)tutorials_df.to_excel(writer, sheet_name='Tutorials', index=False)return True
步骤 3:编写完整的 Streamlit 应用代码
将 data_management 函数整合到一个完整的 Streamlit 应用中,读取 Excel 文件并实现数据的管理功能:
import pandas as pd
import streamlit as st
import datetime# 国家标志示例
COUNTRY_FLAGS = {'中国': '🇨🇳','USA': '🇺🇸','Canada': '🇨🇦','UK': '🇬🇧'
}def save_all_data(excel_file, tools_data, tutorials_data):"""保存所有数据到Excel"""try:tools_rows = []for category, items in tools_data.items():for item in items:tools_rows.append({'Name': item['name'],'Category': category,'Country': item['country'],'Company': item.get('company', ''),'Description': item['description'],'URL': item['url'],'Open Source': item['open_source']})tools_df = pd.DataFrame(tools_rows)tutorials_rows = []for tool_name, tutorials in tutorials_data.items():for tut in tutorials:tutorials_rows.append({'TutorialID': tut['id'],'RelatedTool': tool_name,'Title': tut['title'],'URL': tut['url'],'Type': tut['type'],'DifficultyLevel': tut['difficulty'],'Duration': tut.get('duration', ''),'Rating': tut.get('rating', None),'Language': tut.get('language', '中文'),'Tags': ', '.join(tut.get('tags', [])),'VersionCompatible': tut.get('version', ''),'Author': tut.get('author', '')})tutorials_df = pd.DataFrame(tutorials_rows)with pd.ExcelWriter(excel_file, engine='openpyxl') as writer:tools_df.to_excel(writer, sheet_name='Tools', index=False)tutorials_df.to_excel(writer, sheet_name='Tutorials', index=False)return Trueexcept Exception as e:st.error(f"保存失败:{str(e)}")return Falseclass EnhancedConfig:SERPER_API_KEY = 'your api_key' # 替换为实际的 API 密钥def render_url(url):"""根据URL生成超链接"""if url and url != '无':return f'<a href="{url}" class="link-btn" target="_blank">{url}</a>'else:return "<span>无可用链接</span>"def classify_tool(name, description):"""模拟分类工具的功能"""return '大语言模型' # 示例返回def data_management(excel_file, tools_data):# 新增分类验证功能if st.sidebar.button("🔍 分类质量检查"):error_count = 0for category, items in tools_data.items():for item in items:predicted = classify_tool(item['name'], item['description'])if predicted != category:st.warning(f"分类不一致:{item['name']} 当前分类:{category},预测分类:{predicted}")error_count += 1st.info(f"完成检查,发现{error_count}个潜在分类问题")# 数据管理界面st.sidebar.subheader("数据管理")operation = st.sidebar.radio("操作类型", ["添加条目", "编辑条目", "删除分类", "增加分类"])if operation == "添加条目":category = st.selectbox("选择分类", list(tools_data.keys()) + ["新增分类"])if category == "新增分类":category = st.text_input("请输入新分类名称")with st.form("添加表单"):name = st.text_input("工具名称")url = st.text_input("官网URL")country = st.selectbox("所属国家", list(COUNTRY_FLAGS.keys()))company = st.text_input("公司名称")description = st.text_area("工具描述")open_source = st.selectbox("是否开源", ["是", "否"])popularity = st.slider("初始流行度", 500, 2000, 1000)if st.form_submit_button("提交"):if all([category, name, url]):new_item = {'name': name,'url': url,'description': description,'country': country,'open_source': open_source,'company': company,'popularity': popularity,'last_updated': datetime.datetime.now()}if category not in tools_data:tools_data[category] = []tools_data[category].append(new_item)if save_all_data(excel_file, tools_data, {}): # 假设没有教程数据st.success("添加成功!")else:st.error("请填写必填字段(分类、名称、URL)")elif operation == "编辑条目":category = st.selectbox("选择分类", list(tools_data.keys()))items = tools_data.get(category, [])if items:index = st.selectbox("选择条目", range(len(items)), format_func=lambda x: items[x]['name'])with st.form("编辑表单"):new_category = st.text_input("新分类名称", value=category)name = st.text_input("工具名称", value=items[index]['name'])url = st.text_input("官网URL", value=items[index]['url'])# 确保安全地获取国家try:selected_country_index = list(COUNTRY_FLAGS.keys()).index(items[index]['country'])except ValueError:selected_country_index = 0 # 默认到第一个国家country = st.selectbox("所属国家", list(COUNTRY_FLAGS.keys()), index=selected_country_index)company = st.text_input("公司名称", value=items[index]['company'])description = st.text_area("工具描述", value=items[index]['description'])open_source = st.selectbox("是否开源", ["是", "否"],index=["是", "否"].index(items[index]['open_source']))if st.form_submit_button("保存修改"):del tools_data[category][index]if new_category not in tools_data:tools_data[new_category] = []tools_data[new_category].append({'name': name,'url': url,'description': description,'country': country,'open_source': open_source,'company': company})if not tools_data[category]:del tools_data[category]if save_all_data(excel_file, tools_data, {}): # 假设没有教程数据st.success("修改已保存!")else:st.warning("该分类下没有条目可供编辑或删除!")elif operation == "增加分类":new_category = st.text_input("请输入新分类名称")if st.button("提交"):if new_category:if new_category not in tools_data:tools_data[new_category] = []save_all_data(excel_file, tools_data, {})st.success(f"分类 '{new_category}' 已成功添加!")else:st.error("该分类已存在,请选择其他名称。")else:st.error("分类名称不能为空。")elif operation == "删除分类":category = st.selectbox("选择分类", list(tools_data.keys()))if st.button("确认删除"):del tools_data[category]if save_all_data(excel_file, tools_data, {}): # 假设没有教程数据st.success(f"分类 {category} 已删除!")def main():# 从 Excel 文件读取工具数据excel_file = 'test.xlsx'tools_data = {}# 读取 Excel 文件内容df = pd.read_excel(excel_file, sheet_name='Tools')# 构建工具数据字典for _, row in df.iterrows():category = row['Category']if category not in tools_data:tools_data[category] = []tools_data[category].append({'name': row['Name'],'url': row['URL'],'description': row['Description'],'country': row['Country'],'open_source': row['Open Source'],'company': row['Company'],'popularity': row['Popularity'],'last_updated': row['LastUpdated']})data_management(excel_file, tools_data)if __name__ == "__main__":main()
步骤 4:运行测试
将上述代码保存为 Python 文件,例如 data_management_app.py,然后在命令行中运行以下命令:
streamlit run data_management_app.py
验证输出
当应用启动后,你应该能够通过侧边栏操作来:
- 进行分类质量检查
- 添加、编辑和删除条目
- 增加或删除分类
确保在每次操作后正确更新 Excel 文件,并在页面上显示相应的结果和消息。
注意事项
- Excel 文件路径:确保 Excel 文件路径正确或与脚本在同一目录下。
- 异常处理:在操作中添加异常处理以捕获错误。
- 数据有效性检查:确保用户输入的数据格式正确。
通过这些步骤,你应该能够测试 data_management 函数。如果有任何问题或进一步的要求,请随时告诉我!
相关文章:
测试data_management函数
测试data_management函数 这是我最近正在开发的AI工具信息平台的部门功能模块测试,基于streamlit架构。整理出来与大家分享,也为我以后自己回溯找到资源。 为了测试 data_management 函数并结合 Excel 文件中的 “Tools” 表单内容,我们需要…...
微信小程序---计划时钟设计与实现
微信小程序-计划时钟已上线,欢迎各位小伙伴的测试和使用~(微信小程序搜计划时钟即可使用) 在这篇博客中,我们将探讨如何在微信小程序中设计和实现一个任务管理功能,该功能允许用户添加、删除和查看任务。任务管理系统的核心是基于日期和时间的任务管理,可以设置任务的开…...
深度学习之图像回归(二)
前言 这篇文章主要是在图像回归(一)的基础上对该项目进行的优化。(一)主要是帮助迅速入门 理清一个深度学习项目的逻辑 这篇文章则主要注重在此基础上对于数据预处理和模型训练进行优化前者会通过涉及PCA主成分分析 特征选择 后…...
深入理解HttpSecurity的设计
一、HttpSecurity的应用 在前章节的介绍中我们讲解了基于配置文件的使用方式,也就是如下的使用。 也就是在配置文件中通过 security:http 等标签来定义了认证需要的相关信息,但是在SpringBoot项目中,我们慢慢脱离了xml配置文件的方式,在SpringSecurity中提供了HttpSecurity…...
15增减字符串匹配(贪心)思路解析+源码
文章目录 题目[](https://leetcode.cn/problems/di-string-match/)算法原理贪心证明源码总结题目 假设s="I D I D"也就是增降增降,在0-4中,每两个数存在这种方式数组为【1, 3,2, 4,0】;(如下图) 算法原理 解法:贪心 1.当遇到“I”:选择当前最小的那个数 2…...
Java NIO与传统IO性能对比分析
Java NIO与传统IO性能对比分析 在Java中,I/O(输入输出)操作是开发中最常见的任务之一。传统的I/O方式基于阻塞模型,而Java NIO(New I/O)引入了非阻塞和基于通道(Channel)和缓冲区&a…...
14.7 LangChain Experimental 模块解析:解锁 Auto-GPT 开发新范式
LangChain Experimental 模块解析:解锁 Auto-GPT 开发新范式 关键词:LangChain Experimental、Auto-GPT 实现、自主智能体开发、Agent 架构设计、实验性功能实践 1. LangChain Experimental 模块的定位与核心能力 模块定位解析: #mermaid-svg-4xz2OlZBUFjkBmqw {font-fami…...
wps中的js开发
严格区分大小写 /*** learn_js Macro*/ function test() {Range(D7).Value2Selection.Value2; // Selection.formula "100" }function Workbook_SheetSelectionChange(Sh, Target) {if(Sh.Name Sheet1) {test();}}function test2() {// 把I4单元格及其周边有数的单…...
day16_推荐系统和总结
文章目录 day16_推荐系统和总结一、推荐实现1、基于流行度推荐(掌握)1.1 近期热门商品推荐1.2 个人热门商品推荐 2、基于隐语义模型的协同过滤推荐(了解)2.1 ALS算法介绍2.2 推荐代码 3、基于物品的协同过滤推荐(了解&…...
一文说清楚编码、摘要、加密、公钥、私钥、解密、签名、验签
编码 对信息进行编码,没有信息损失,任何人都能通过编码方式对信息进行解码。例如 ASCII 码,base64 编码。 例如下面是 ASCII 编码表: 摘要 对信息计算摘要值,有信息损失,例如 md5 摘要,sh…...
Repeated Sequence
记suma[1]a[2]a[3]...a[n]。 该序列以a[1],a[2],a[3]....a[n]为循环节,明显的,问题可转化为:s%sum是否为该序列的某个连续子序列和。 断环为链。将a复制一份。 枚举a[i]为左端点的所有区间的和。再查找s是否存在。二分O&#x…...
CT dicom 去除床板 去除床位,检查床去除
1. 前言 医院拍摄患者CT与MRI 图像, 但是CT图像中就会出现检查床的区域,来看CT扫描设备是什么样子的,红色标出区域 可以在图中看到,在头部位置安装有固定头部的类似支架的东西,这个东西拍摄出来时什么样子呢ÿ…...
react 踩坑记 too many re-renders.
报错信息: too many re-renders. React limits the number of randers to prevent an infinite loop. 需求 tabs只有特定标签页才展示某些按钮 button要用 传递函数引用方式 ()>{} *还有要注意子组件内loading触发 导致的重复渲染...
YOLOv8与BiFormer注意力机制的融合:提升多场景目标检测性能的研究
文章目录 1. YOLOv8的改进背景2. BiFormer注意力机制的核心原理2.1 Bi-level Attention结构2.2 路由策略与加权融合 3. YOLOv8与BiFormer的结合3.1 YOLOv8架构概述3.2 BiFormer与YOLOv8的融合策略 4. 实现代码示例5. 结果分析与实验5.1 数据集与实验设置5.2 实验结果 6. 进一步…...
Ubuntu24.04LTS的下载安装超细图文教程(VMware虚拟机及正常安装)
😸个人主页👉:神兽汤姆猫 📖系列专栏:开发语言环境配置 、 Java学习 、Java面试 、Markdown等 学习上的每一次进步,均来自于平时的努力与坚持。 💕如果此篇文章对您有帮助的话,请点…...
c++贪心系列
各位小伙伴们新年好呀,这是年后的第一篇文章,那么还是一样,我们继续学习这个贪心算法。 第一题 题目链接 2418. 按身高排序 - 力扣(LeetCode) 题目解析 代码原理 方法一 1.先创建一个下标数组,将两个数…...
爬虫第七篇数据爬取及解析
这篇博客旨在分享学习过程中的心得和体会,如果有错误请指出,感谢大家。 经过前面的学习,那么我们也就进入了数据爬取的阶段,大家跟着我的步伐一起来学习一下,爬虫的数据爬取与数据解析(本篇主要针对于带有…...
LangChain 技术入门指南:探索语言模型的无限可能
在当今的技术领域,LangChain 正逐渐崭露头角,成为开发语言模型应用的强大工具。如果你渴望深入了解并掌握这一技术,那么就跟随本文一起开启 LangChain 的入门之旅吧! (后续将持续输出关于LangChain的技术文章,有兴趣的同学可以关注…...
解锁D3.js与PlantUML的交互奥秘:探索知识图谱数据可视化新领域
解锁D3.js与PlantUML的交互魔法:数据可视化新征程 在前端开发的广袤天地里,数据可视化一直是一颗璀璨的明珠,吸引着无数开发者探索其奥秘。而当D3.js这一强大的JavaScript库,遇上专注于创建UML图的PlantUML,一场奇妙的…...
OpenCV机器学习(8)随机森林(Random Forests)算法cv::ml::RTrees类
操作系统:ubuntu22.04 OpenCV版本:OpenCV4.9 IDE:Visual Studio Code 编程语言:C11 算法描述 cv::ml::RTrees 是 OpenCV 机器学习模块中的一部分,用于实现随机森林(Random Forests)算法。随机森林是一种集…...
渲染学进阶内容——模型
最近在写模组的时候发现渲染器里面离不开模型的定义,在渲染的第二篇文章中简单的讲解了一下关于模型部分的内容,其实不管是方块还是方块实体,都离不开模型的内容 🧱 一、CubeListBuilder 功能解析 CubeListBuilder 是 Minecraft Java 版模型系统的核心构建器,用于动态创…...
多种风格导航菜单 HTML 实现(附源码)
下面我将为您展示 6 种不同风格的导航菜单实现,每种都包含完整 HTML、CSS 和 JavaScript 代码。 1. 简约水平导航栏 <!DOCTYPE html> <html lang"zh-CN"> <head><meta charset"UTF-8"><meta name"viewport&qu…...
SpringTask-03.入门案例
一.入门案例 启动类: package com.sky;import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCach…...
AI病理诊断七剑下天山,医疗未来触手可及
一、病理诊断困局:刀尖上的医学艺术 1.1 金标准背后的隐痛 病理诊断被誉为"诊断的诊断",医生需通过显微镜观察组织切片,在细胞迷宫中捕捉癌变信号。某省病理质控报告显示,基层医院误诊率达12%-15%,专家会诊…...
给网站添加live2d看板娘
给网站添加live2d看板娘 参考文献: stevenjoezhang/live2d-widget: 把萌萌哒的看板娘抱回家 (ノ≧∇≦)ノ | Live2D widget for web platformEikanya/Live2d-model: Live2d model collectionzenghongtu/live2d-model-assets 前言 网站环境如下,文章也主…...
关于easyexcel动态下拉选问题处理
前些日子突然碰到一个问题,说是客户的导入文件模版想支持部分导入内容的下拉选,于是我就找了easyexcel官网寻找解决方案,并没有找到合适的方案,没办法只能自己动手并分享出来,针对Java生成Excel下拉菜单时因选项过多导…...
前端中slice和splic的区别
1. slice slice 用于从数组中提取一部分元素,返回一个新的数组。 特点: 不修改原数组:slice 不会改变原数组,而是返回一个新的数组。提取数组的部分:slice 会根据指定的开始索引和结束索引提取数组的一部分。不包含…...
mac:大模型系列测试
0 MAC 前几天经过学生优惠以及国补17K入手了mac studio,然后这两天亲自测试其模型行运用能力如何,是否支持微调、推理速度等能力。下面进入正文。 1 mac 与 unsloth 按照下面的进行安装以及测试,是可以跑通文章里面的代码。训练速度也是很快的。 注意…...
leetcode_69.x的平方根
题目如下 : 看到题 ,我们最原始的想法就是暴力解决: for(long long i 0;i<INT_MAX;i){if(i*ix){return i;}else if((i*i>x)&&((i-1)*(i-1)<x)){return i-1;}}我们直接开始遍历,我们是整数的平方根,所以我们分两…...
spring boot使用HttpServletResponse实现sse后端流式输出消息
1.以前只是看过SSE的相关文章,没有具体实践,这次接入AI大模型使用到了流式输出,涉及到给前端流式返回,所以记录一下。 2.resp要设置为text/event-stream resp.setContentType("text/event-stream"); resp.setCharacter…...
