finwiki-extract 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ # -*- coding: utf-8 -*-
2
+ """FinWiki: 中文年报财务字段抽取工具包(候选行窗口 + 严格 JSON 解析 + 勾稽校验)。"""
3
+ __version__ = "0.1.0"
4
+ FIELDS = ["revenue", "net_profit", "total_assets", "total_liab", "equity"]
5
+ ALIASES = {
6
+ "revenue": ["营业收入", "营业总收入", "主营业务收入", "营收"],
7
+ "net_profit": ["归属于母公司所有者的净利润", "归母净利润", "净利润"],
8
+ "total_assets": ["资产总计", "资产总额", "总资产"],
9
+ "total_liab": ["负债合计", "负债总额", "总负债"],
10
+ "equity": ["所有者权益合计", "股东权益合计", "净资产"],
11
+ }
12
+ SYSTEM_PROMPT = (
13
+ "你是财务数据抽取器。只输出一个 JSON 对象,键为 revenue, net_profit, total_assets, "
14
+ "total_liab, equity;单位统一为元;无法确定的值输出 null。不要输出解释。"
15
+ )
finwiki_extract/cli.py ADDED
@@ -0,0 +1,69 @@
1
+ # -*- coding: utf-8 -*-
2
+ """CLI:finwiki extract / finwiki model / finwiki validate。"""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+
9
+ from . import __version__
10
+ from .core import build_messages, parse_json, validate
11
+
12
+ OLLAMA_URL = "http://127.0.0.1:11434/api/chat"
13
+ MODEL_TAG = "finwiki-3b-v5b"
14
+
15
+
16
+ def _ollama_chat(messages, model=MODEL_TAG, timeout=600):
17
+ import urllib.request
18
+
19
+ payload = {"model": model, "messages": messages, "stream": False,
20
+ "options": {"temperature": 0, "num_gpu": 0, "num_ctx": 4096}}
21
+ req = urllib.request.Request(OLLAMA_URL, data=json.dumps(payload).encode(),
22
+ headers={"Content-Type": "application/json"})
23
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
24
+ return json.loads(resp.read().decode())["message"]["content"]
25
+
26
+
27
+ def cmd_extract(args):
28
+ text = open(args.text, encoding="utf-8").read() if args.text != "-" else sys.stdin.read()
29
+ messages = build_messages(text)
30
+ if args.backend == "ollama":
31
+ content = _ollama_chat(messages, model=args.model)
32
+ else:
33
+ content = json.dumps({f: None for f in
34
+ ["revenue", "net_profit", "total_assets", "total_liab", "equity"]})
35
+ print("[info] backend=stub 仅演示流程;请用 --backend ollama 或自行接入模型", file=sys.stderr)
36
+ obj = parse_json(content)
37
+ pretty = json.dumps(obj, ensure_ascii=False, indent=2) if obj else content
38
+ print(pretty)
39
+ if obj and args.validate:
40
+ print(json.dumps(validate(obj), ensure_ascii=False, indent=2))
41
+
42
+
43
+ def cmd_validate(args):
44
+ obj = json.load(open(args.json, encoding="utf-8"))
45
+ print(json.dumps(validate(obj), ensure_ascii=False, indent=2))
46
+
47
+
48
+ def main():
49
+ p = argparse.ArgumentParser(prog="finwiki", description="FinWiki 中文年报财务字段抽取")
50
+ p.add_argument("--version", action="version", version=f"finwiki {__version__}")
51
+ sub = p.add_subparsers(dest="cmd", required=True)
52
+
53
+ e = sub.add_parser("extract", help="从报表文本抽取 5 字段")
54
+ e.add_argument("--text", required=True, help="文本文件路径,或 - 表示 stdin")
55
+ e.add_argument("--backend", default="stub", choices=["stub", "ollama"])
56
+ e.add_argument("--model", default=MODEL_TAG)
57
+ e.add_argument("--validate", action="store_true", help="输出勾稽校验结果")
58
+ e.set_defaults(func=cmd_extract)
59
+
60
+ v = sub.add_parser("validate", help="校验已有 JSON 的勾稽关系")
61
+ v.add_argument("--json", required=True)
62
+ v.set_defaults(func=cmd_validate)
63
+
64
+ args = p.parse_args()
65
+ args.func(args)
66
+
67
+
68
+ if __name__ == "__main__":
69
+ main()
@@ -0,0 +1,100 @@
1
+ # -*- coding: utf-8 -*-
2
+ """核心:候选行窗口构造、提示词、严格 JSON 解析、勾稽校验。"""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from typing import Any, Dict, List, Optional
8
+
9
+ from . import ALIASES, FIELDS, SYSTEM_PROMPT
10
+
11
+ NUM = re.compile(r"-?\d[\d,,]*(?:\.\d+)?")
12
+
13
+
14
+ def build_window(text: str, context: int = 2) -> str:
15
+ """从报表文本中截取字段别名所在行及其上下文,构造候选行窗口。"""
16
+ lines = [ln.strip() for ln in text.replace("\u3000", " ").splitlines() if ln.strip()]
17
+ keep: List[int] = []
18
+ for i, ln in enumerate(lines):
19
+ if any(a in ln for names in ALIASES.values() for a in names):
20
+ keep.extend(range(max(0, i - context), min(len(lines), i + context + 1)))
21
+ if not keep: # 全文回退
22
+ return "\n".join(lines[:200])
23
+ return "\n".join(lines[i] for i in sorted(set(keep)))
24
+
25
+
26
+ def build_messages(text: str) -> List[Dict[str, str]]:
27
+ return [
28
+ {"role": "system", "content": SYSTEM_PROMPT},
29
+ {"role": "user", "content": build_window(text)},
30
+ ]
31
+
32
+
33
+ def parse_json(content: str) -> Optional[Dict[str, Any]]:
34
+ """容忍 markdown 代码块与前后噪声的 JSON 解析。"""
35
+ s = (content or "").strip()
36
+ s = re.sub(r"^```(?:json)?\s*", "", s)
37
+ s = re.sub(r"\s*```$", "", s)
38
+ m = re.search(r"\{.*\}", s, flags=re.S)
39
+ if not m:
40
+ return None
41
+ try:
42
+ obj = json.loads(m.group(0))
43
+ except Exception:
44
+ return None
45
+ return {f: obj.get(f) for f in FIELDS} if isinstance(obj, dict) else None
46
+
47
+
48
+ def to_yuan(value: Any, unit_hint: Optional[str] = None) -> Optional[float]:
49
+ """数值转元:支持万元/亿元后缀提示。"""
50
+ if value is None:
51
+ return None
52
+ if isinstance(value, str):
53
+ v = NUM.search(value.replace(",", "").replace(",", ""))
54
+ if not v:
55
+ return None
56
+ num = float(v.group(0))
57
+ else:
58
+ num = float(value)
59
+ hint = (unit_hint or "").replace(" ", "")
60
+ if "亿" in hint:
61
+ num *= 1e8
62
+ elif "万" in hint:
63
+ num *= 1e4
64
+ return num
65
+
66
+
67
+ def validate(record: Dict[str, Any], tol: float = 0.02) -> Dict[str, Any]:
68
+ """勾稽校验:A = L + E;返回问题列表(不硬改值)。"""
69
+ ta, tl, eq = record.get("total_assets"), record.get("total_liab"), record.get("equity")
70
+ issues: List[str] = []
71
+ if None not in (ta, tl, eq) and ta:
72
+ try:
73
+ diff = abs(float(tl) + float(eq) - float(ta)) / max(abs(float(ta)), 1.0)
74
+ if diff > tol:
75
+ issues.append(f"articulation_mismatch:{diff:.4f}")
76
+ except Exception:
77
+ issues.append("articulation_non_numeric")
78
+ for f in FIELDS:
79
+ v = record.get(f)
80
+ if v is not None:
81
+ try:
82
+ if float(v) < 0 and f not in ("net_profit",):
83
+ issues.append(f"negative:{f}")
84
+ except Exception:
85
+ issues.append(f"non_numeric:{f}")
86
+ return {"record": record, "valid": not issues, "issues": issues}
87
+
88
+
89
+ def match(pred: Any, gold: Any, tol: float = 0.01) -> bool:
90
+ """单位容错匹配(±1%):1e3/1e4/1e6/1e8 等换算后任一命中即视为正确。"""
91
+ try:
92
+ p, g = float(pred), float(gold)
93
+ except Exception:
94
+ return False
95
+ if abs(p - g) / max(abs(g), 1.0) <= tol:
96
+ return True
97
+ for k in (1e3, 1e4, 1e6, 1e8, 1e-3, 1e-4, 1e-6, 1e-8):
98
+ if abs(p * k - g) / max(abs(g), 1.0) <= tol:
99
+ return True
100
+ return False
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: finwiki-extract
3
+ Version: 0.1.0
4
+ Summary: Chinese annual-report financial field extraction: candidate-row windows, strict JSON parsing and articulation checks (FinWiki)
5
+ Author-email: Yin Kang <13767758705@163.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://gitee.com/yin-kang83/finwiki-extract
8
+ Project-URL: Repository, https://gitee.com/yin-kang83/finwiki-extract
9
+ Project-URL: Model weights, https://doi.org/10.5281/zenodo.24882685
10
+ Keywords: finance,annual-report,extraction,llm,xbrl,chinese
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Topic :: Office/Business :: Financial :: Accounting
14
+ Classifier: Natural Language :: Chinese (Simplified)
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ License-File: NOTICE
19
+ Dynamic: license-file
20
+
21
+ # FinWiki Extract
22
+
23
+ 中文年报财务字段抽取工具包:**候选行窗口构造 + 严格 JSON 解析 + 勾稽校验**。
24
+ Companion toolkit for the FinWiki-3B extraction model (research release).
25
+
26
+ ## 安装
27
+
28
+ ```bash
29
+ pip install finwiki-extract
30
+ ```
31
+
32
+ ## 用法
33
+
34
+ ```bash
35
+ # 从报表文本抽取 5 字段(默认 stub 演示流程;Ollama 后端需本地模型)
36
+ finwiki extract --text report.txt --backend ollama
37
+
38
+ # 校验已有结果(A = L + E)
39
+ finwiki validate --json result.json
40
+ ```
41
+
42
+ Python API:
43
+
44
+ ```python
45
+ from finwiki_extract.core import build_messages, parse_json, validate, match
46
+ messages = build_messages(open("report.txt", encoding="utf-8").read())
47
+ obj = parse_json('{"revenue": 1, ...}') # 容忍 markdown 包裹
48
+ report = validate(obj) # 勾稽校验,不硬改值
49
+ ```
50
+
51
+ ## 模型权重
52
+
53
+ - FinWiki-3B-v5b(Qwen2.5-3B + LoRA,GGUF q4_K_M,1.8GB):见 `MODEL_CARD.md`;
54
+ - 权重 DOI:[10.5281/zenodo.24882685](https://doi.org/10.5281/zenodo.24882685)(Zenodo 记录含 model card/包源码;GGUF 权重 1.8GB 见仓库 Release 附件)
55
+ - **仅研究用途**,不构成投资/审计意见。
56
+
57
+ ## 输出字段
58
+
59
+ `revenue` / `net_profit`(归母口径)/ `total_assets` / `total_liab` / `equity`,单位元,缺数输出 `null`。
60
+
61
+ ## 许可
62
+
63
+ - 代码:MIT(见 `LICENSE`);
64
+ - 模型权重:Apache-2.0(底座 Qwen2.5-3B-Instruct,见 `NOTICE`);
65
+ - 训练数据不随包分发。
@@ -0,0 +1,10 @@
1
+ finwiki_extract/__init__.py,sha256=Ii2ZndWESydxeCXt-mZYs9gm0I0b83DirxYaXnGBVl8,868
2
+ finwiki_extract/cli.py,sha256=P2ADuDW-X57DzmzrKWmcjldra6OXGwRpZefe-4SIuq4,2662
3
+ finwiki_extract/core.py,sha256=5M_FdpF-D9gBQJd5kDjO1eq3sZAgCP0rt8I1VlFHupw,3508
4
+ finwiki_extract-0.1.0.dist-info/licenses/LICENSE,sha256=tamLv3AnlwnD2o8vOXJX2Reff5-ggTeEps-O3a3HWKA,1074
5
+ finwiki_extract-0.1.0.dist-info/licenses/NOTICE,sha256=Z8UDTylgPjcpO_ZsDBMutcKvIDNBktiOdnuYqLdITeM,496
6
+ finwiki_extract-0.1.0.dist-info/METADATA,sha256=c_TpW8b91xsZcZvGel0udy8EcZoPadMZeV_iBclx6Sk,2371
7
+ finwiki_extract-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ finwiki_extract-0.1.0.dist-info/entry_points.txt,sha256=9uS94132dKP8VHit8dQIGK-QMYYoA8SoStRv30zdMes,53
9
+ finwiki_extract-0.1.0.dist-info/top_level.txt,sha256=dNnkxhogh13fa63kaH700gQ_qENDtO-6-d3uoY01b1w,16
10
+ finwiki_extract-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ finwiki = finwiki_extract.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yin Kang (尹康)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,11 @@
1
+ FinWiki-3B-v5b is a fine-tuned derivative of Qwen2.5-3B-Instruct.
2
+
3
+ Qwen2.5-3B-Instruct
4
+ Copyright (c) Alibaba Cloud. Licensed under the Apache License, Version 2.0.
5
+ https://huggingface.co/Qwen/Qwen2.5-3B-Instruct
6
+
7
+ This release (weights: Apache-2.0; code: MIT) is an independent research
8
+ artifact. It is not affiliated with or endorsed by Alibaba Cloud.
9
+
10
+ Training data (annual-report text and derived labels) is NOT distributed with
11
+ the weights. See MODEL_CARD.md for limitations and intended use.
@@ -0,0 +1 @@
1
+ finwiki_extract