jwf-common-python
封装了一些通用的功能
安装
pip install jwf-common-python
仓库内开发和运行测试,请先按开发协作同步并激活本地环境。
从旧包迁移
从 1.0.0 起,安装名改为 jwf-common-python,导入名改为 jwf_common_python。
不再提供 common_packages 或 common_python 导入路径。调用项目需要更新依赖声明、锁文件及所有导入。
pip uninstall common-packages
pip install jwf-common-python
例如,将 from common_packages.translate import WordInfo 改为
from jwf_common_python.translate import WordInfo。
pypi首页
可以 README 使用右边的目录进行快速浏览
1. db utils
[x] mysql
安装依赖
使用
# mysql配置
mysql_config = {
"host": "xxx"
"port": xxx
"user" : "xxx"
"password" :"xxx"
"database" : "xxx"
}
mysql_op = MysqlOperator(**mysql_config)
# 接口1: 获取所有表名
tables: set[str] = mysql_op.fetch_all_tables()
# 接口2: 执行`查询sql`,返回执行结果
data: DataFrame, columns: list[str] = mysql_op.fetch_specify_sql_data("SELECT * FROM customers")
# 接口3: 执行`插入sql`,使用指定dataframe数据,指定表名
need_insert_data = [
{"customer_name": "test1", "email": "test1@gmail.com"},
{"customer_name": "test2", "email": "test2@gmail.com"},
]
need_insert_dataframe = pd.DataFrame(need_insert_data)
rows: int = mysql_op.insert_database_mysql(need_insert_dataframe, "customers")
2. file storage
[x] local storage
# 接口对象
local_config = {
"storage_home_dir" = "xxx"
}
local = LocalStorage(**local_config)
# 接口1: 写入本地文件内容
file_name: str = "test_save_file.txt"
content: bytes = "abc测试123!@!@".encode()
# file_path 是路径
status: bool, file_path: str = local_obj.save(file_name, content)
# 接口2: 读取本地文件内容
file_name: str = "test_save_file.txt"
content: bytes = "abc测试123!@!@".encode()
status: bool, actual_content: str = local_obj.load(file_name)
[x] tencent cos storage
# 接口对象
tencent_cos_config = {
"bucket": "xxx",
"region": "xxx",
"secret_key": "xxx",
"secret_id": "xxx"
}
tencent_cos = TencentCos(**tencent_cos_config)
# 接口1: 写入cos文件内容
file_name: str = "test_save_file.txt"
content: bytes = "abc测试123!@!@".encode()
status: bool, actual_file_name: str = tencent_cos_obj.save(
filename=file_name, content=content
)
# 接口2: 读取cos文件内容
file_name: str = "test_save_file.txt"
status: bool, actual_content: bytes = tencent_cos_obj.load(file_name)
3. translation
封装翻译接口
[x] mircrosoft 翻译
from jwf_common_python.translate import SentenceInfo, WordInfo
from jwf_common_python.translate.microsoft import TranslateMicrosoft
# ------- 初始化 -------
config: dict = {
"text_endpoint": "xxx",
"word_endpoint": "xxx",
"word_sample_endpoint": "xxx",
"location_region": "xxx",
"key": "xxx",
"tts_microsoft_config": {
"key": "xxx",
"location_region": "xxx",
}
}
microsoft_obj = TranslateMicrosoft(**config)
# ------- 1. 单词api -------
# 获取原生单词翻译结果
raw_word_translate_res = translate_microsoft_obj.translate_word(
word="fly",
source_language_code="en",
target_language_code="zh-CN",
)
# 格式化为标准结果
res: WordInfo = translate_microsoft_obj.format_word_response(raw_word_translate_res)
# ------- 2. 句子api -------
# 获取原生句子翻译结果
res_tran: dict = translate_microsoft_obj.translate_sentence(
text=self.text,
source_language_code=self.source_language_code,
target_language_code=self.target_language_code,
)
# 格式化为标准结果
res: SentenceInfo = translate_microsoft_obj.format_sentence_response(sentence_translate_data)
-
参考:
-
- tts文档
- 创建tts服务:在
Azure --> Azure AI services --> 语音服务
-
将要支持的:
- [ ] google 翻译
- [ ] Deepl 翻译
- [ ] openAI 翻译
-
兼容已有服务:
- [x] tencent TMT 文本翻译,见下方用法及接口下线说明
-
不打算支持的:
[x] 腾讯云 TMT 文本翻译(旧接口兼容)
jwf_common_python.translate.tencent.TencentTranslate 保留原有文本翻译接口,
补齐单词、句子翻译及标准化结果。密钥、地域、项目 ID、超时均通过参数传入;
导入模块时不加载 SDK,函数不打印、不写文件,SDK 异常直接向调用方传播。
此模块使用官方 CommonClient 调用已有 TMT 文本接口,无需安装 TMT 产品 SDK,
也不要求降级其他产品的 SDK。依照腾讯云下线公告,
该接口计划于 2027-01-31 停止销售、2030-12-31 停止所有服务。
新项目应参考公告中的替代方案,本模块不自动切换接口。
pip install 'tencentcloud-sdk-python-common>=3.0.1042,<4'
from jwf_common_python.translate.tencent import TencentTranslate
translator = TencentTranslate(
secret_id="your-secret-id", secret_key="your-secret-key",
region="ap-shanghai", project_id=0, timeout=30,
# token="temporary-credential-token", # 可选临时凭证
)
# 完整 Response 响应体,保留 RequestId 以及未被预定义的服务端字段。
raw = translator.translate("hello", source_language_code="auto", target_language_code="zh-CN")
word = translator.translate_word("apple")
word_info = translator.format_word_response(word)
sentence = translator.translate_sentence("Hello world!")
sentence_info = translator.format_sentence_response(sentence)
translator.close() # 也可使用 with TencentTranslate(...) as translator:
translate 每次创建独立参数字典,支持 untranslated_text 指定不翻译的内容。
zh-CN 自动转换为腾讯的 zh,zh-TW 保持不变;目标语言不能为 auto。
TMT 不提供词典和音频数据,标准化结果中的词性 Other、频率 0.0 及空例句、
变体、音频均为占位值;原始单词响应保留在 extended_info。
download_audio_file 显式抛出 NotImplementedError,音频应由 TTS 服务提供。
支持 with 和可重复调用的 close(),关闭后不能继续翻译。
离线测试(无需真实密钥、不调用腾讯云服务):
pytest tests/test_tencent_translate
4. tts接口
封装文本转语音接口
[x] Azure(Microsoft)文本转语音
from jwf_common_python.tts.azure import TTSMicrosoft
tts = TTSMicrosoft(key="your-key", location_region="eastasia", language="zh")
audio: bytes = tts.convert_text_to_speech("你好")
使用 requests,返回 24 kHz WAV 音频。language="zh" 使用云健,
language="en"(客户端默认值)使用 Andrew Multilingual。网络超时默认 30 秒,
认证或合成失败时抛出异常,不打印令牌或音频数据。
本地真实测试:将 .env.example 复制为根目录 .env,填写 AZURE_SPEECH_KEY
和资源所在区域 AZURE_SPEECH_REGION,例如 eastasia。可选配置
AZURE_TTS_LANGUAGE(手动测试默认 zh)和 AZURE_TTS_TEXT。
然后在仓库根目录运行:
pytest tests/test_tts/test_azure_manual.py -m manual -s
测试会真实获取令牌并合成一次,保存 test_temp_data/azure_tts.wav,
可直接打开试听;重复运行覆盖该测试音频。普通 pytest 默认跳过真实调用。
开发环境已包含测试依赖;该测试无需启动数据库或 Docker 服务。
离线测试(mock HTTP):
pytest tests/test_tts/microsoft_test.py tests/test_tts/test_azure_local_config.py
[x] 统一音色列表
from jwf_common_python.tts import TTSVoiceList
voices = TTSVoiceList.get_voices()
目前聚合腾讯云本地维护的音色,无需密钥、SDK 或网络请求。
返回列表中每项的顶层固定包含 name、voice_id、description、gender、
supplier、category、voice_key 和 other。name 用于展示,
voice_id 保留供应商原始标识和值类型,用于合成。voice_key 是全局唯一的稳定字符串,
展示名变更时继续使用原键。语言、采样率、情感等其他字段归入 other 字典,无额外字段时为 {}。
保持供应商返回顺序,每次返回独立副本,不影响供应商原始接口及其完整数据。
离线单元测试:
pytest tests/test_tts/test_voice_list.py
[x] 腾讯云 TextToVoice 语音合成
依据 Apifox 项目 8929040 的接口 524819309 实现,使用腾讯云公共 SDK
处理 TC3 签名,无需安装 TTS 产品 SDK:
pip install 'tencentcloud-sdk-python-common>=3.0.1042,<4'
from jwf_common_python.tts.tencent import TTSTencent
voices = TTSTencent.get_voices() # 返回 tts.py 中的本地音色数据,无需密钥
with TTSTencent(secret_id="your-secret-id", secret_key="your-secret-key") as tts:
response = tts.text_to_voice("你好", voice_type=1001)
subtitles = response["Subtitles"]
request_id = response["RequestId"]
- 语音合成只提供
text_to_voice,返回完整 Response 字典,
保留 Base64 Audio、字幕和请求标识;音频由调用方按需解码。
get_voices() 返回本地维护的音色列表,包含音色 ID、语言、采样率、情感等
原始字段。返回副本,修改结果不会影响后续调用;不连接腾讯云获取音色。
- 使用长期 SecretId/SecretKey,不发送 Token。可配置
region(默认留空)和
timeout(默认 30 秒);未传 session_id 时,每次请求自动生成 UUID。
- 默认开启字幕、WAV 格式、正常语速和音量(
speed=0、volume=0),
模型 1、中文、16000 Hz。文本和音色 voice_type 必须传入,按需覆盖可选业务字段:
volume、speed、project_id、model_type、fast_voice_type、
primary_language、sample_rate、codec、enable_subtitle、segment_rate、
emotion_category、emotion_intensity。复刻音色 200000000 必须提供 fast_voice_type。
- 文本长度、SSML、音色与语言/采样率/字幕/情感的兼容性由服务端判定,
不自动拆分长文本。HTTP 200 中的业务错误也会抛出 SDK 异常,保留错误码和请求 ID。
不打印或自动保存音频;使用
with 或 close() 释放连接。
离线单元测试(mock HTTP,不需要真实密钥):
pytest tests/test_tts/test_tencent_tts.py tests/test_tts/test_tencent_params.py
test_tencent_tts.py 和 test_tencent_params.py 使用 mock,不调用真实腾讯云。
本地真实测试:先按开发协作同步 uv 环境,将根目录 .env.example 复制为 .env,
填写 TENCENTCLOUD_SECRET_ID、TENCENTCLOUD_SECRET_KEY 和必填音色
TENCENT_TTS_VOICE_TYPE,可修改 TENCENT_TTS_TEXT 指定测试文本。
.env 已被 Git 忽略。然后在仓库根目录执行:
source .venv/bin/activate
pytest tests/test_tts/test_tencent_manual.py -m manual -s
真实服务测试入口是 test_tencent_manual.py,-m manual 显式启用真实调用,
-s 在终端显示生成文件的路径。开发环境已包含依赖,无需添加 --noconftest。
这会真实调用一次腾讯云,保存 test_temp_data/tencent_tts.wav 和
test_temp_data/tencent_tts_response.json,重复运行会覆盖这两个测试文件。
可直接打开 WAV 试听,JSON 中保留音频、字幕和请求 ID。
开发环境已包含测试依赖;该测试无需启动 MySQL、Docker 等服务。
普通 pytest 默认排除 manual;只有显式指定 -m manual 才运行该测试。
5. Ai接口
解释句子,分析长难句
- [ ] openAI 翻译
- [ ] gemini 翻译
6. sms
腾讯云
7. oauth
google文档
google oauth2:
配置文件:
[oauth2.google]
client_id = "xxx"
client_secret = "xxx"
# 认证完成之后的回调地址,必须与google console中配置的一致
redirect_uri = "http://localhost:9080/aaa"
# 访问权限
scope = "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"
使用:
from jwf_common_python.oauth.google import GoogleOAuth2
config = global_config["oauth2"]["google"]
google_oauth2_obj = GoogleOAuth2(**config)
# 1. 获取授权地址
url = oauth2_google_obj.get_web_auth_url()
# 2. 获取用户信息
user_info = oauth2_google_obj.get_user_info("code 123")
6. llm 大模型
百度的ernie大模型
配置文件:
[llm.baidu_ernie]
client_id = "xxxx"
client_secret = "xxxx"
使用:
from jwf_common_python.llm.baidu_ernie import LLMBaiduErnie
config = global_config["llm"]["baidu_ernie"]
llm_baidu_ernie_obj = LLMBaiduErnie(**config)
# 1. 获取大模型回答结果
res: str = llm_baidu_ernie_obj.send_model_request(text)
# 2. 使用大模型判断是否为自然语言
status: bool = llm_baidu_ernie_obj.is_natural_language(text)
7. geography 地理位置
汽车服务
汽车销售
汽车维修
摩托车服务
餐饮服务
购物服务
生活服务
体育休闲服务
医疗保健服务
住宿服务
风景名胜
商务住宅
政府机构及社会团体
科教文化服务
交通设施服务
金融保险服务
公司企业
道路附属设施
地名地址信息
公共设施
事件活动
室内设施
虚拟数据
通行设施
汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施|事件活动|室内设施|虚拟数据|通行设施
使用,查看单元测试文件
英文文本与词表处理
jwf_common_python.language_utils 提供文本取词、章节提取、词表过滤、词频统计、
长度排序及网页取词,替代旧 _other/_language_utils/language.py。
导入时不扫描目录、不打印、不配置全局日志;处理结果直接返回,不写文件。
from jwf_common_python.language_utils import (
extract_words, get_chapter_words, word_frequencies, format_words,
read_word_lists, filter_words, fetch_words_from_pages,
)
words = extract_words(
"Apple apple banana and pear.",
exclude_words=["and"], known_words=["pear"],
)
frequencies = word_frequencies(words) # [("apple", 2), ("banana", 1)]
word_list_text = format_words(words, top_n=100) # 返回逐行词表文本
chapter_words = get_chapter_words(
"Chapter One\nHello world!\nChapter Two\nNext chapter",
"Chapter One", "Chapter Two",
)
# 读取文件时必须显式传入路径;不会自动读取 utils/、files/ 或当前目录词表。
# known = read_word_lists(["data/known.txt", "data/local_words.txt"])
# new_words = filter_words(words, known_words=known, unique=True)
# page_words = fetch_words_from_pages(["https://example.com"], known_words=known)
新旧功能对应: