Skip to main content

better-commons

开箱即用的 Python 基础库,把日常开发中反复出现的「配置加载、日志、大模型调用、文件加密、性能计时、文档标注」等能力,收敛为一个个小而美的工具模块。

Python Version Version License

为什么用它

  • 少写样板代码:Hadoop 风格 XML 配置 + 环境变量覆盖,一套代码在本地 / 生产无缝切换;
  • LLM 开箱即用:对齐 OpenAI 兼容接口,内置多轮对话、续写、网关转发和 SQLite 响应缓存;
  • 安全发布:EncryptFile 开发时读写明文、发布时只保留密文,密钥由你自己掌控;
  • 可观测性:structlog 统一日志管线,异常自动捕获堆栈、自动补 trace_id;
  • 类型安全:全量类型注解,pyright / basedpyright 严格模式下 0 错误。

包含的模块

模块 导出接口 一句话说明
配置 Config / ConfigError 加载 XML 配置,支持环境变量覆盖与加密配置文件
大模型 ChatClient / ChatModel / ChatError / create_chat_client 调用 OpenAI 兼容的 LLM API,支持缓存
加密 EncryptFile 类 pathlib.Path 的透明加解密文件
日志 configure_logging 一键配置 structlog 控制台 + 文件轮转日志
标注 annot_pdf_file / annot_image_file 在 PDF / 图像上绘制版面元素框
计时 Timer / TimerError 上下文管理器 / 装饰器 / 多阶段计时

30 秒快速上手

配置与 LLM

import asyncio

from commons import Config, configure_logging, create_chat_client, ChatModel

configure_logging()

config = Config("./config/conf-template.xml", "./config/conf-private.xml")
client = create_chat_client(
    ChatModel.DEEPSEEK_V4_FLASH,
    config=config,
    max_tokens=8192,
    cache_enabled=True,
)

response = asyncio.run(
    client.chat(system_prompt="You're a good helper.", user_prompt="hello")
)
print(response)

日志

import structlog
from commons import configure_logging

# 在应用入口初始化一次:控制台彩色 + 按天轮转的文件日志
configure_logging(log_dir="./logs", backup_count=7)

logger = structlog.get_logger(__name__)

logger.info("服务启动成功", trace_id="req-10086")

try:
    1 / 0
except ZeroDivisionError:
    logger.error("计算异常")   # error 级别自动附带完整堆栈,无需 exc_info=True

PDF / 图像标注

from commons import annot_image_file, annot_pdf_file
from commons.cv.types import Point, SimpleRegion

# 一个版面元素:类别标签 + 坐标点
region = SimpleRegion("text", [Point(100, 100), Point(300, 300)])

# 在 PDF 上标注(页码 -> 区域列表),输出新文件
annot_pdf_file(
    "./config/sample.pdf",
    {0: [region], 1: [region]},
    out_file="./config/sample_annot.pdf",
)

# 在图像上标注,按 label 指定线框颜色
annot_image_file(
    "./config/test.jpg",
    regions=[region],
    color_map={"text": (200, 0, 0)},
    out_file="./config/test_annot.jpg",
)

安装

# 推荐:使用 uv
uv pip install better-commons

# 或使用 pip
pip install better-commons

帮助文档

完整的帮助文档托管在 GitHub Pages(由 DeepSeek 生成),按 Diátaxis 框架组织:

🔗 入口地址:https://iamxiatian.github.io/better-commons/

基础功能

仿照 Hadoop 格式的 XML 配置

配置文件的格式示例:

<configurations>
    <!--  配置模板  -->
    <property>
        <name>api.server.host</name>
        <value>0.0.0.0</value>
        <description>API服务器地址</description>
    </property>

    <property>
        <name>api.server.port</name>
        <value>8080</value>
        <description>API服务端口</description>
    </property>
</configurations>

使用示例

import asyncio
from commons import Config, configure_logging

configure_logging()
config = Config("./config/conf-template.xml", "./config/conf-private.xml")

# config demo
host = config.get_option_str("api.server.host") or "127.0.0.1"

# 以下语句执行时会报错,因为`api.server2.port`不存在
# port:int = config.get_int("api.server2.port")
# 以下语句会返回None
# port = config.get_option_int("api.server2.port")

port = config.get_option_int("api.server.port")

print(host, port)

日常开发

运行以下脚本,可以自动格式化代码,并发现类型错误。

make fine

开发环境设置

  1. 安装uv

    curl -fsSL https://get.uv.dev | bash
    # 或者通过pip安装
    pip install uv
    
  2. 可编辑安装本项目

    #创建虚拟环境
    uv venv
    uv pip install -e .
    
  3. 通过uv运行脚本main.py示例

    uv run -m commons.main
    
  4. 代码格式化

uv run ruff check --fix src
#或者
make fmt
  1. git设置

避免中文文件名称乱码:

git config --global core.quotepath false # 让 Git 不要将非 ASCII 字符的文件名用引号括起来

Metadata

Release files for better-commons 0.3.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for better-commons 0.3.4
File Size Uploaded Provenance Actions
better_commons-0.3.4.tar.gz 10.2 MB Without provenance Details for better_commons-0.3.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for better-commons 0.3.4
File Interpreter ABI Platform Actions
better_commons-0.3.4-py3-none-any.whl Python 3 none any Details for better_commons-0.3.4-py3-none-any.whl

Total release size: 10.2 MB

Release files / better_commons-0.3.4.tar.gz

Download URL better_commons-0.3.4.tar.gz
Size 10.2 MB
Tags Source
SHA-256 checksum
How to use checksums
98bc291472b83096d19f69bba03e448f41eafb31c127e548e85dc119fde763a0
BLAKE2b-256 checksum
How to use checksums
8d7d67e51e6b2afa14f540991aa970b16aec90492333ab27d111ee333ff9807a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / better_commons-0.3.4-py3-none-any.whl

Download URL better_commons-0.3.4-py3-none-any.whl
Size 70.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
500485e73ff21b4a3bc2f0a977e63167ce3c422723b35b2446dcab6eb9a0e994
BLAKE2b-256 checksum
How to use checksums
9a89663ef6cbf35367d304504702c255acacbf4bfaa5fd43008eb1a713203141
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for better-commons 0.3.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page