发布三语生成算法、代码与数据检查说明
Browse files- README.md +39 -0
- 分片清单.json +0 -0
- 发布状态.json +5 -0
- 检查报告.json +14 -0
- 生成算法.文言.md +37 -0
- 生成算法.汉语.md +33 -0
- 生成算法.英语.md +33 -0
- 程序/使用说明.md +31 -0
- 程序/全量词典翻译.py +199 -0
- 程序/词典翻译.py +189 -0
- 许可与来源.md +12 -0
- 词典许可证.txt +21 -0
README.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- zh
|
| 4 |
+
- en
|
| 5 |
+
license: other
|
| 6 |
+
license_name: upstream-code-licenses
|
| 7 |
+
license_link: https://huggingface.co/datasets/yuyan-lang/codeparrot-github-code-chinese-translation-v1/blob/main/%E8%AE%B8%E5%8F%AF%E4%B8%8E%E6%9D%A5%E6%BA%90.md
|
| 8 |
+
size_categories:
|
| 9 |
+
- 100M<n<1B
|
| 10 |
+
task_categories:
|
| 11 |
+
- text-generation
|
| 12 |
+
pretty_name: CodeParrot Chinese Dictionary Substitution v1
|
| 13 |
+
configs:
|
| 14 |
+
- config_name: default
|
| 15 |
+
data_files:
|
| 16 |
+
- split: train
|
| 17 |
+
path: 数据/*.parquet
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
# CodeParrot GitHub Code Chinese Translation v1
|
| 21 |
+
|
| 22 |
+
**Deterministic dictionary substitution, not LLM translation.** Natural Chinese fluency, semantic equivalence and executable code are not guaranteed.
|
| 23 |
+
|
| 24 |
+
**Release preparation:** 1,126 local shards have been generated; the upload may still be incomplete. See 发布状态.json and the manifest for availability.
|
| 25 |
+
|
| 26 |
+
[English algorithm](生成算法.英语.md) · [现代汉语](生成算法.汉语.md) · [先秦文言](生成算法.文言.md)
|
| 27 |
+
|
| 28 |
+
## Load / 使用
|
| 29 |
+
|
| 30 |
+
```python
|
| 31 |
+
from datasets import load_dataset
|
| 32 |
+
stream = load_dataset("yuyan-lang/codeparrot-github-code-chinese-translation-v1", streaming=True, split="train")
|
| 33 |
+
row = next(iter(stream))
|
| 34 |
+
print(row["content_中文"])
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
Original English columns are retained alongside Chinese derivatives. Only the three translated columns aim to eliminate ASCII alphabetic characters; the dataset as a whole contains English.
|
| 38 |
+
|
| 39 |
+
See [validation](检查报告.json), [shard mapping](分片清单.json), [provenance and licenses](许可与来源.md), and the reproducible source under 程序/. The three algorithm documents describe the final implementation; historical LLM experiments are background only.
|
分片清单.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
发布状态.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"状态": "准备上传",
|
| 3 |
+
"预期分片": 1126,
|
| 4 |
+
"预期行数": 115086922
|
| 5 |
+
}
|
检查报告.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"分片数": 1126,
|
| 3 |
+
"总行数": 115086922,
|
| 4 |
+
"总字节": 487902053782,
|
| 5 |
+
"元数据异常": [],
|
| 6 |
+
"抽样行数": 1024,
|
| 7 |
+
"抽样英文字母残留": [],
|
| 8 |
+
"文件摘要": {
|
| 9 |
+
"词典翻译.py": "b1d5be4bd6439676f1d646d082367d807921c824e4d1074bfa1cb52e5488fcb1",
|
| 10 |
+
"全量词典翻译.py": "3ffeeefd10bec25a21dfa42399639aa164adb1f5c4b16c4fd065563519f9308c",
|
| 11 |
+
"英汉词库.csv": "1a6947e04785db63613a92e14903cdae7954f7e84860b10e68e5c7cbb3f9c3cf"
|
| 12 |
+
},
|
| 13 |
+
"说明": "仅元数据全查与分片首64行抽样,不是全数据内容验证;尚未校验每行原文一致性。"
|
| 14 |
+
}
|
生成算法.文言.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 代码语料汉译·词典代换第一版
|
| 2 |
+
|
| 3 |
+
此取 CodeParrot 之代码,以词典代其英文。非豫言之程序,亦不保其可行、义同、辞顺。今版不用大模型,不取旧模型译名之库。
|
| 4 |
+
|
| 5 |
+
## 数与制
|
| 6 |
+
|
| 7 |
+
凡一千一百二十六片,一亿一千五百零八万六千九百二十二行,字节四千八百七十九亿零二百零五万三千七百八十二。源片与译片一一相应,行序不易。源之仓名、路径、大小、正文、许可皆存;别增正文、路径、仓名三中文列。大小乃原文之数,非译文之数。独设训练集,不别验证与测试,亦不增语言与唯一号。
|
| 8 |
+
|
| 9 |
+
## 法
|
| 10 |
+
|
| 11 |
+
一、读 ECDICT。词键去首尾空白,折大小写为一。重词取先得之可用义。先取标为计算机之义,次取常义;去领域、括注、词性,取首个含汉字而无英文字母之义项,惟留汉字与数字。常用术语以小表定之。
|
| 12 |
+
|
| 13 |
+
二、取 exchange 所记过去、分词、复数等形,归其原词;此版不取其零项。单词以散列表索之;三字母以上之子词及多词之组,各立前缀树。
|
| 14 |
+
|
| 15 |
+
三、全段合唯一号之式者,代以“全局唯一标识符”;全段十六进制长逾十字符者,代以“二进制数据”。零天之数,依字母表代换。
|
| 16 |
+
|
| 17 |
+
四、先存大小写以断驼峰及缩写,再索词组。邻词间空格、下划线、连字符可通,余结构符号则断。词组取最长。未得者,索整词,索变形,乃以动态规划断子词:先求未覆字母最少,次求段数最少。一二字母不入子词树,整词则仍可索。
|
| 18 |
+
|
| 19 |
+
五、余英字依甲乙丙丁戊己庚辛壬癸子丑寅卯辰巳午未申酉戌亥物天地人代之。数字与汉字存。去下划线、英文空格、制表符;两英文组件间独立之连字符亦去。余标点、数字、换行存。非谓尽去天下空白及连字符也。
|
| 20 |
+
|
| 21 |
+
六、译词相接,不改句序。以有限内存记十万词之近用结果,不写旧库。每千零二十四行暂存,写盘而原子易名,断后可续;既竟,合为一片。
|
| 22 |
+
|
| 23 |
+
## 所以然
|
| 24 |
+
|
| 25 |
+
算力有限,故求省费。昔试模型译词、合库、去重、复用组件、机械代号、批量推理、多端调度、纠错修复;调用仍众。后限推理于二十四时,遂尽用词典。昔之模型服务、短词干支缓存与百分之十五符号判句法,皆非今版之法。此重规模、可复现与成本,轻于义之精确,须明言之。
|
| 26 |
+
|
| 27 |
+
## 检与限
|
| 28 |
+
|
| 29 |
+
全片元数据可读,逐片行数与源同。分取十六片各首六十四行,共千零二十四行,三中文列未见英文字母。此抽检,非尽检;未逐行核源文之同,未度译义之准确。原文、字段名、许可中有英文,固其所当有。亦未尽去凭证与私隐。
|
| 30 |
+
|
| 31 |
+
多义、缩写、专名及断词,皆可误。去空白则排版与字符串之义可变,易关键词则程序多不可行,代哈希及唯一号则身份失。可供分词与语言代换对照之研究,未证能益编程模型也。
|
| 32 |
+
|
| 33 |
+
## 源与许可
|
| 34 |
+
|
| 35 |
+
源出 https://huggingface.co/datasets/codeparrot/github-code ,本地所记修订为 b5661e6b17396364b2bcf8e68977b0d28e1ebd19 ,尚未逐文件独立核之。词典出 https://github.com/skywind3000/ECDICT ,其所附 MIT 文与摘要俱存。源代码许可各异,逐行许可字段不易;词典之许可不得覆诸代码。用者须守各源许可及署名之责,此不为许可完备之保证。
|
| 36 |
+
|
| 37 |
+
欲恒定引其行,以发布修订、译片名、零起行号为据。清单列源译之对应,行内未增标识与摘要。
|
生成算法.汉语.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CodeParrot 中文词典替换语料 v1
|
| 2 |
+
|
| 3 |
+
本数据集是 codeparrot/github-code 的确定性词典替换版本。不是豫言程序,也不保证源语言可执行性、语义等价或自然中文。最终版本未调用 LLM、未读取旧模型翻译缓存。
|
| 4 |
+
|
| 5 |
+
## 规模与字段
|
| 6 |
+
|
| 7 |
+
1,126 个 Parquet 分片,115,086,922 行,487,902,053,782 字节(约 487.90 GB / 454.39 GiB)。每个输入分片对应一个输出分片,原始顺序不变。保留 repo_name、path、size、content、license;新增 content_中文、path_中文、repo_name_中文。size 是原文大小,不是译文字节数。没有新增 language、UUID 或训练/验证/测试分桶,仅提供 train。
|
| 8 |
+
|
| 9 |
+
## 算法:实现顺序
|
| 10 |
+
|
| 11 |
+
1. 加载 ECDICT CSV。英文字典键 strip 后 casefold;重复键取首个可用释义。先尝试 [计] 标记释义,再尝试一般释义;删除领域标签、括号说明、词性前缀,取首个含汉字且无 ASCII 字母的逗号/分号分隔片段,保留其中汉字与数字。内置人工术语表覆盖部分常见选义。
|
| 12 |
+
2. exchange 字段中的 d/p/i/3/r/t/s 词形映射回原词。0 字段不参与此版本处理。
|
| 13 |
+
3. 构建单词哈希表、至少三字母的子词 Trie 和多词词组 Trie。原始文本先识别整段 UUID、超过十字符的完整十六进制串,分别输出“全局唯一标识符”“二进制数据”。十六进制字面量 0x... 用字母机械映射处理。
|
| 14 |
+
4. ASCII 字母串在保留原始大小写时按驼峰与缩写边界切分,例如 HTTPServer → HTTP / Server。随后优先匹配由相邻词组成的最长词典词组;空格、下划线、连字符可连接词组,其他结构符号阻断匹配。
|
| 15 |
+
5. 未命中词组时查询完整单词,随后词形,最后动态规划子词分解:先最小化未覆盖字母数,再最小化片段数。不把一两字母词作为子词 Trie 候选;完整一两字母单词仍可查词典/术语表。此算法可能错误拆分未知名称。
|
| 16 |
+
6. 未覆盖字母按 a–z → 甲乙丙丁戊己庚辛壬癸子丑寅卯辰巳午未申酉戌亥物天地人转换;数字保留。中文原样保留。非字母段删除下划线、ASCII 空格和制表符;两个英文组件之间独立的连字符删除,其他标点、数字、换行保留。不能宣称所有 Unicode 空格或所有连字符都被删除。
|
| 17 |
+
7. 逐词拼接不调整语序。单词计算用最多100,000项内存 LRU 缓存;派生结果不写旧 SQLite 缓存。批量读取每1,024行,写临时文件后 fsync 并原子替换;完整分片汇总为 Parquet。中断后已保存批次可跳过。
|
| 18 |
+
|
| 19 |
+
## 算力约束与研发历史
|
| 20 |
+
|
| 21 |
+
优化源于有限计算资源。此前试验了逐词模型翻译、三类缓存合并、词项去重、组件复用、哈希与UUID机械处理、批量模型推理、多端点调度、重试及修复。模型调用量仍然过大,在仅能再提供24小时推理的限制下,最终选择完全词典替换。历史模型服务、短词干支缓存和句子15%符号分类器不属于本版发布算法;所有内容走同一词典流程。此版本优先规模、可复现性与成本,明确牺牲语义质量。
|
| 22 |
+
|
| 23 |
+
## 已做检查与局限
|
| 24 |
+
|
| 25 |
+
所有1,126个分片元数据可读,逐片行数与输入相等。跨16个分片的首64行,共1,024行抽样,三个中文列未检出 [a-zA-Z]。这不是全量内容验证,未逐行验证英文原文一致性,也未测量语义准确率。原文列、字段名、license 等元数据含英文属正常。没有进行完整隐私或凭证清理。
|
| 26 |
+
|
| 27 |
+
词典可能选择错误义项,短词、专名、缩写、驼峰以及上下文皆可能被误处理。删除空白会破坏语法、字符串字面量和排版;关键词改写使代码通常不可执行。UUID与哈希会丢失身份。适合作为分词、语言替换和预训练对照实验基线,尚无证据表明能够改善模型编程能力。
|
| 28 |
+
|
| 29 |
+
## 来源、许可与追踪
|
| 30 |
+
|
| 31 |
+
上游:https://huggingface.co/datasets/codeparrot/github-code 。本地下载来源修订记录为 b5661e6b17396364b2bcf8e68977b0d28e1ebd19;逐文件独立核验未完成。ECDICT:https://github.com/skywind3000/ECDICT ,附上下载时的 MIT 许可文本与 SHA-256。原始代码包含多种许可证,保留每行 license;项目声明、脚本许可或词典MIT许可不覆盖原始代码。使用者须遵守各来源许可证及署名要求,词典的第三方词条来源亦应自行审阅。引用路径不是对上游代码许可完整核验的证明。
|
| 32 |
+
|
| 33 |
+
稳定引用建议使用本数据集发布 commit + 输出分片名 + 零起始行号;清单给出输出分片与源分片对应。当前行内不增加来源ID,内容摘要可由使用者计算。
|
生成算法.英语.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CodeParrot Chinese Dictionary Substitution v1
|
| 2 |
+
|
| 3 |
+
A deterministic dictionary-substitution derivative of codeparrot/github-code. This is not executable Yuyan code, a semantics-preserving translation, or a high-quality natural-language translation. The final pipeline makes no LLM calls and does not read the earlier model-generated cache.
|
| 4 |
+
|
| 5 |
+
## Data
|
| 6 |
+
|
| 7 |
+
1,126 Parquet shards; 115,086,922 rows; 487,902,053,782 bytes (487.90 GB, approximately 454.39 GiB). Each output shard corresponds to one input shard and retains row order. Original columns: repo_name, path, size, content, license. Added columns: content_中文, path_中文, repo_name_中文. size describes the original file. Only a train split is provided; no inferred language, UUID, validation split, or test split is added.
|
| 8 |
+
|
| 9 |
+
## Implemented algorithm
|
| 10 |
+
|
| 11 |
+
1. Load ECDICT CSV. Normalize dictionary keys with strip and casefold; retain the first usable definition for duplicate keys. Prefer definitions marked [计], otherwise general definitions. Remove domain labels, parenthetical explanations and leading part-of-speech notation. Select the first comma/semicolon-delimited candidate containing Han characters and no ASCII letters, then retain Han characters and digits. A small explicit terminology table overrides selected meanings.
|
| 12 |
+
2. Map d/p/i/3/r/t/s exchange forms to the original dictionary word; the exchange 0 field is not used.
|
| 13 |
+
3. Build a word hash table, a character Trie for words of at least three ASCII letters, and a multiword phrase Trie. Whole-string UUIDs become 全局唯一标识符; whole-string hexadecimal sequences longer than ten characters become 二进制数据. Hexadecimal literals beginning with 0x receive mechanical letter substitution.
|
| 14 |
+
4. Split ASCII alphabetic runs at camel-case and acronym boundaries while preserving case for segmentation (HTTPServer → HTTP / Server). Prefer the longest dictionary phrase across adjacent components separated by spaces, underscores or hyphens. Other structural characters stop phrase matching.
|
| 15 |
+
5. For unmatched components, try the complete word, inflection lookup, then dynamic programming over dictionary subwords. Minimize uncovered letters first, and number of segments second. One- and two-letter words are excluded from the subword Trie but can still match as whole words. Unknown names can be segmented incorrectly.
|
| 16 |
+
6. Convert remaining a–z letters to 甲乙丙丁戊己庚辛壬癸子丑寅卯辰巳午未申酉戌亥物天地人. Preserve digits and existing Chinese. Remove underscores, ASCII spaces and tabs from non-letter segments. Remove a standalone hyphen between two alphabetic components; retain other punctuation and line breaks. This is not a universal Unicode whitespace or hyphen normalization policy.
|
| 17 |
+
7. Concatenate translations without reordering sentence syntax. Use an in-memory LRU of up to 100,000 word results, not the previous SQLite cache. Write resumable 1,024-row batches through temporary files, fsync and atomic rename, then consolidate each shard.
|
| 18 |
+
|
| 19 |
+
## Resource constraints and prior experiments
|
| 20 |
+
|
| 21 |
+
Limited compute motivated the optimizations. Earlier experiments used LLM translation, unified caches, deduplication, component reuse, mechanical hash/UUID handling, batch inference, multiple endpoints, retries and repairs. With only 24 additional inference hours available, the released pipeline switched completely to dictionary substitution. The older model services, short-token cache mappings and 15% symbol sentence classifier are not used in this release. Scale, reproducibility and cost were prioritized over semantic fidelity.
|
| 22 |
+
|
| 23 |
+
## Validation and limitations
|
| 24 |
+
|
| 25 |
+
Metadata for all 1,126 shards was readable, and per-shard row counts matched the inputs. The first 64 rows of each of 16 distributed shards (1,024 rows total) contained no [a-zA-Z] in the three translated columns. This is a limited sample, not exhaustive validation. Row-by-row original-content equality and semantic accuracy have not been measured. Original columns, field names and license values legitimately contain English. No exhaustive credential or privacy filtering has been performed.
|
| 26 |
+
|
| 27 |
+
Polysemy, acronyms, names and component segmentation can produce incorrect translations. Whitespace removal changes formatting and string literals. Keyword substitution generally makes source code non-executable. Hash and UUID substitution loses identity. Intended uses include tokenizer comparisons, controlled language-substitution experiments and exploratory pretraining baselines; improved programming performance has not been established.
|
| 28 |
+
|
| 29 |
+
## Provenance and licensing
|
| 30 |
+
|
| 31 |
+
Upstream: https://huggingface.co/datasets/codeparrot/github-code . The locally recorded source revision is b5661e6b17396364b2bcf8e68977b0d28e1ebd19; an independent per-file revision verification has not been completed. Dictionary: https://github.com/skywind3000/ECDICT ; the downloaded MIT notice and SHA-256 are included. Original code remains subject to its individual licenses, retained in the license column. Neither a project statement nor the dictionary MIT notice relicenses upstream code. Users must comply with source licenses and attribution obligations. The dictionary's third-party source provenance should also be reviewed; this release does not certify license completeness.
|
| 32 |
+
|
| 33 |
+
For stable references, use a release commit, output shard name and zero-based row index. The manifest maps output shards to source shards; identifiers and hashes are not added to every row.
|
程序/使用说明.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 纯词典翻译初版
|
| 2 |
+
|
| 3 |
+
不调用 LLM、不连接翻译或缓存服务、不改旧缓存。加载 ECDICT 生成内存词表和词组/子词 Trie,优先计算机释义,辅以脚本中的人工选义表。词组优先最长匹配;未命中的单词查询词形,随后动态规划子词匹配,仍未覆盖的字母按干支与物天地人转换。
|
| 4 |
+
|
| 5 |
+
驼峰、下划线、连字符作为词边界。中文结果删除下划线和横向空白,英文词之间的连字符删除,保留数字、换行和结构标点。句子是逐词替换,语序不调整。输出不是可执行代码。
|
| 6 |
+
|
| 7 |
+
运行文本:
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
.venv/bin/python 千问数据集翻译/英汉词典/词典翻译.py --文本 'getUserName file not found'
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
运行文本文件:
|
| 14 |
+
|
| 15 |
+
```bash
|
| 16 |
+
.venv/bin/python 千问数据集翻译/英汉词典/词典翻译.py --输入 原文.txt --输出 千问数据集翻译/英汉词典/试译.txt
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
运行单个 Parquet:
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
.venv/bin/python 千问数据集翻译/英汉词典/词典翻译.py \
|
| 23 |
+
--输入 data/codeparrot-github-code/data/train-00000-of-01126.parquet \
|
| 24 |
+
--输出 千问数据集翻译/词典翻译结果/第零分片.parquet
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
原有字段全部保留,新增 content_中文、path_中文、repo_name_中文(仅在原字段存在时)。按128行分批写出,不需要把完整分片放进内存。初版没有断点续传;中断的输出可能不完整,重新运行同一命令会重写输出。不能使用同一个输入输出路径。
|
| 28 |
+
|
| 29 |
+
末尾统计中,单词统计为有容量限制的内存缓存实际计算次数,重复命中内存缓存不重复计数;词组统计为匹配次数。
|
| 30 |
+
|
| 31 |
+
已验证文本中的词组、驼峰、汉字、数字及十六进制场景。尚未运行全量翻译;词典选义与子词划分仍有歧义。
|
程序/全量词典翻译.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""纯词典全量翻译,按批保存,重新执行可跳过已完成批次。"""
|
| 2 |
+
import argparse as 参数解析
|
| 3 |
+
import hashlib as 哈希
|
| 4 |
+
import json as 编码
|
| 5 |
+
import multiprocessing as 多进程
|
| 6 |
+
import os as 系统
|
| 7 |
+
import signal as 信号
|
| 8 |
+
import time as 时间
|
| 9 |
+
import fcntl as 文件锁
|
| 10 |
+
from queue import Empty as 队列空
|
| 11 |
+
from tqdm import tqdm as 进度条
|
| 12 |
+
from concurrent.futures import ProcessPoolExecutor as 进程池
|
| 13 |
+
from pathlib import Path as 路径
|
| 14 |
+
import pyarrow as 箭头
|
| 15 |
+
import pyarrow.parquet as 列式
|
| 16 |
+
from 词典翻译 import 词典翻译器
|
| 17 |
+
|
| 18 |
+
翻译器 = None
|
| 19 |
+
事件队列 = None
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def 初始化工作进程():
|
| 23 |
+
# Ctrl+C 由主进程统一处理,防止工作进程接到中断后继续领取后续任务。
|
| 24 |
+
信号.signal(信号.SIGINT, 信号.SIG_IGN)
|
| 25 |
+
信号.signal(信号.SIGTERM, 信号.SIG_DFL)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def 请求停止(编号, 栈):
|
| 29 |
+
raise KeyboardInterrupt
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def 停止工作进程(池):
|
| 33 |
+
信号.signal(信号.SIGINT, 信号.SIG_IGN)
|
| 34 |
+
信号.signal(信号.SIGTERM, 信号.SIG_IGN)
|
| 35 |
+
工作进程 = list((池._processes or {}).values())
|
| 36 |
+
for 进程 in 工作进程:
|
| 37 |
+
if 进程.is_alive():
|
| 38 |
+
进程.terminate()
|
| 39 |
+
截止 = 时间.monotonic() + 3
|
| 40 |
+
for 进程 in 工作进程:
|
| 41 |
+
进程.join(timeout=max(0, 截止-时间.monotonic()))
|
| 42 |
+
for 进程 in 工作进程:
|
| 43 |
+
if 进程.is_alive():
|
| 44 |
+
进程.kill()
|
| 45 |
+
for 进程 in 工作进程:
|
| 46 |
+
进程.join()
|
| 47 |
+
池.shutdown(wait=False, cancel_futures=True)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def 处理分片(任务):
|
| 51 |
+
输入, 输出, 批量, 逐文件 = 任务
|
| 52 |
+
完成文件 = 输出 / '译文.parquet'
|
| 53 |
+
if 完成文件.exists():
|
| 54 |
+
return str(输入.name), '已完成,跳过'
|
| 55 |
+
输出.mkdir(parents=True, exist_ok=True)
|
| 56 |
+
批次文件 = []
|
| 57 |
+
行号 = 0
|
| 58 |
+
源文件 = 列式.ParquetFile(输入)
|
| 59 |
+
事件队列.put(('开始', 输入.name, 0, 源文件.metadata.num_rows))
|
| 60 |
+
for 批号, 批次 in enumerate(源文件.iter_batches(batch_size=批量)):
|
| 61 |
+
文件 = 输出 / f'第{批号:06d}批.parquet'
|
| 62 |
+
批次文件.append(文件)
|
| 63 |
+
if not 文件.exists():
|
| 64 |
+
表 = 箭头.Table.from_batches([批次])
|
| 65 |
+
字段列表 = [名称 for 名称 in ('content','path','repo_name') if 名称 in 表.column_names]
|
| 66 |
+
原文列 = {名称:表[名称].to_pylist() for 名称 in 字段列表}
|
| 67 |
+
译文列 = {名称:[] for 名称 in 字段列表}
|
| 68 |
+
for 偏移 in range(len(批次)):
|
| 69 |
+
for 名称 in 字段列表:
|
| 70 |
+
原文 = 原文列[名称][偏移]
|
| 71 |
+
译文列[名称].append(翻译器.翻译(原文) if 原文 is not None else None)
|
| 72 |
+
if (偏移+1) % 32 == 0:
|
| 73 |
+
事件队列.put(('进度', 输入.name, 行号+偏移+1, 源文件.metadata.num_rows))
|
| 74 |
+
for 名称 in 字段列表:
|
| 75 |
+
字段 = 名称 + '_中文'
|
| 76 |
+
if 字段 in 表.column_names:
|
| 77 |
+
表 = 表.drop([字段])
|
| 78 |
+
表 = 表.append_column(字段, 箭头.array(译文列[名称], type=箭头.string()))
|
| 79 |
+
临时 = 文件.with_suffix('.临时')
|
| 80 |
+
列式.write_table(表, 临时, compression='zstd')
|
| 81 |
+
with 临时.open('rb') as 句柄:
|
| 82 |
+
系统.fsync(句柄.fileno())
|
| 83 |
+
临时.replace(文件)
|
| 84 |
+
if 逐文件:
|
| 85 |
+
日志 = '\n'.join(f'文件 {输入.name}:{行号+偏移}:success(纯词典)' for 偏移 in range(len(批次)))
|
| 86 |
+
事件队列.put(('日志', 日志))
|
| 87 |
+
行号 += len(批次)
|
| 88 |
+
事件队列.put(('进度', 输入.name, 行号, 源文件.metadata.num_rows))
|
| 89 |
+
临时 = 输出 / '译文.临时'
|
| 90 |
+
写入器 = None
|
| 91 |
+
try:
|
| 92 |
+
for 文件 in 批次文件:
|
| 93 |
+
for 批次 in 列式.ParquetFile(文件).iter_batches(batch_size=批量):
|
| 94 |
+
表 = 箭头.Table.from_batches([批次])
|
| 95 |
+
if 写入器 is None:
|
| 96 |
+
写入器 = 列式.ParquetWriter(临时, 表.schema, compression='zstd')
|
| 97 |
+
写入器.write_table(表)
|
| 98 |
+
finally:
|
| 99 |
+
if 写入器:
|
| 100 |
+
写入器.close()
|
| 101 |
+
if 写入器:
|
| 102 |
+
with 临时.open('rb') as 句柄:
|
| 103 |
+
系统.fsync(句柄.fileno())
|
| 104 |
+
临时.replace(完成文件)
|
| 105 |
+
for 文件 in 批次文件:
|
| 106 |
+
文件.unlink()
|
| 107 |
+
return 输入.name, f'完成 {行号} 行'
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def 主程序():
|
| 111 |
+
global 翻译器, 事件队列
|
| 112 |
+
解析器 = 参数解析.ArgumentParser(description=__doc__)
|
| 113 |
+
解析器.add_argument('--输入目录', type=路径, required=True)
|
| 114 |
+
解析器.add_argument('--输出目录', type=路径, required=True)
|
| 115 |
+
解析器.add_argument('--文件并发', type=int, default=8)
|
| 116 |
+
解析器.add_argument('--每批行数', type=int, default=1024)
|
| 117 |
+
解析器.add_argument('--逐文件日志', action='store_true')
|
| 118 |
+
参数 = 解析器.parse_args()
|
| 119 |
+
if 参数.文件并发 < 1 or 参数.每批行数 < 1:
|
| 120 |
+
解析器.error('并发和批量必须大于零')
|
| 121 |
+
分片 = sorted(参数.输入目录.glob('*.parquet'))
|
| 122 |
+
if not 分片:
|
| 123 |
+
解析器.error('输入目录没有 Parquet')
|
| 124 |
+
参数.输出目录.mkdir(parents=True, exist_ok=True)
|
| 125 |
+
锁 = (参数.输出目录/'运行锁').open('w')
|
| 126 |
+
文件锁.flock(锁, 文件锁.LOCK_EX | 文件锁.LOCK_NB)
|
| 127 |
+
词典 = 路径(__file__).parent/'英汉词库.csv'
|
| 128 |
+
配置 = {'词典':哈希.sha256(词典.read_bytes()).hexdigest(),
|
| 129 |
+
'程序':哈希.sha256((路径(__file__).parent/'词典翻译.py').read_bytes()).hexdigest(),
|
| 130 |
+
'批量':参数.每批行数,
|
| 131 |
+
'分片':[(str(文件.resolve()),文件.stat().st_size,文件.stat().st_mtime_ns) for 文件 in 分片]}
|
| 132 |
+
配置文件 = 参数.输出目录/'配置.json'
|
| 133 |
+
if 配置文件.exists() and 编码.loads(配置文件.read_text()) != 编码.loads(编码.dumps(配置)):
|
| 134 |
+
raise ValueError('输出目录的词典、程序或输入已改变,请使用新的输出目录')
|
| 135 |
+
配置文件.write_text(编码.dumps(配置, ensure_ascii=False, indent=2))
|
| 136 |
+
print('正在加载词典;工作进程共享只读词典……', flush=True)
|
| 137 |
+
翻译器 = 词典翻译器(词典)
|
| 138 |
+
任务 = [(文件,参数.输出目录/f'第{编号:05d}分片',参数.每批行数,参数.逐文件日志) for 编号,文件 in enumerate(分片)]
|
| 139 |
+
print(f'开始:{len(任务)} 分片,并发 {参数.文件并发},不调用 LLM', flush=True)
|
| 140 |
+
信号.signal(信号.SIGTERM, 请求停止)
|
| 141 |
+
上下文 = 多进程.get_context('fork')
|
| 142 |
+
事件队列 = 上下文.Queue(maxsize=256)
|
| 143 |
+
活跃 = {}
|
| 144 |
+
当前 = None
|
| 145 |
+
with 进度条(total=len(任务), desc='Parquet', unit='分片', position=0, dynamic_ncols=True) as 全局条, \
|
| 146 |
+
进度条(total=0, desc='分片内文件', unit='文件', position=1, dynamic_ncols=True) as 文件条, \
|
| 147 |
+
进程池(max_workers=参数.文件并发, mp_context=上下文, initializer=初始化工作进程) as 池:
|
| 148 |
+
try:
|
| 149 |
+
后续 = {池.submit(处理分片, 项):项[0] for 项 in 任务}
|
| 150 |
+
while 后续:
|
| 151 |
+
try:
|
| 152 |
+
事件 = 事件队列.get(timeout=0.1)
|
| 153 |
+
if 事件[0] == '日志':
|
| 154 |
+
进度条.write(事件[1])
|
| 155 |
+
else:
|
| 156 |
+
_, 名称, 已处理, 总数 = 事件
|
| 157 |
+
活跃[名称] = (已处理, 总数)
|
| 158 |
+
except 队列空:
|
| 159 |
+
pass
|
| 160 |
+
for 完成 in [项 for 项 in 后续 if 项.done()]:
|
| 161 |
+
输入 = 后续.pop(完成)
|
| 162 |
+
try:
|
| 163 |
+
名称, 状态 = 完成.result()
|
| 164 |
+
进度条.write(f'{名称}:{状态}')
|
| 165 |
+
except Exception as 错误:
|
| 166 |
+
进度条.write(f'{输入.name}:failed:{错误!r}')
|
| 167 |
+
活跃.pop(输入.name, None)
|
| 168 |
+
全局条.update(1)
|
| 169 |
+
if 当前 not in 活跃:
|
| 170 |
+
当前 = next(iter(活跃), None)
|
| 171 |
+
if 当前:
|
| 172 |
+
文件条.reset(total=活跃[当前][1])
|
| 173 |
+
文件条.set_description(f'文件 {当前}', refresh=False)
|
| 174 |
+
if 当前:
|
| 175 |
+
文件条.update(max(0, 活跃[当前][0]-文件条.n))
|
| 176 |
+
文件条.set_postfix_str(f'并行分片 {len(活跃)}', refresh=False)
|
| 177 |
+
# 清空最后完成分片留下的日志;只由主进程维护终端。
|
| 178 |
+
while True:
|
| 179 |
+
try:
|
| 180 |
+
事件 = 事件队列.get(timeout=0.1)
|
| 181 |
+
if 事件[0] == '日志':
|
| 182 |
+
进度条.write(事件[1])
|
| 183 |
+
except 队列空:
|
| 184 |
+
break
|
| 185 |
+
except BaseException:
|
| 186 |
+
停止工作进程(池)
|
| 187 |
+
事件队列.cancel_join_thread()
|
| 188 |
+
事件队列.close()
|
| 189 |
+
raise
|
| 190 |
+
事件队列.close()
|
| 191 |
+
print('本轮结束;失败分片可重新运行续跑。',flush=True)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
if __name__ == '__main__':
|
| 195 |
+
try:
|
| 196 |
+
主程序()
|
| 197 |
+
except KeyboardInterrupt:
|
| 198 |
+
print("\n已停止全部词典翻译工作进程;已保存批次可续跑。", flush=True)
|
| 199 |
+
raise SystemExit(130)
|
程序/词典翻译.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""纯词典中文替换:不调用模型,不访问旧翻译缓存。"""
|
| 2 |
+
import argparse as 参数解析
|
| 3 |
+
import csv as 表格
|
| 4 |
+
import re as 正则
|
| 5 |
+
from pathlib import Path as 路径
|
| 6 |
+
from functools import lru_cache as 最近缓存
|
| 7 |
+
|
| 8 |
+
字母译名 = dict(zip('abcdefghijklmnopqrstuvwxyz', '甲乙丙丁戊己庚辛壬癸子丑寅卯辰巳午未申酉戌亥物天地人'))
|
| 9 |
+
术语 = {'get':'获取', 'set':'设置', 'class':'类', 'object':'对象', 'thread':'线程',
|
| 10 |
+
'cache':'缓存', 'socket':'套接字', 'port':'端口', 'driver':'驱动程序',
|
| 11 |
+
'find':'查找', 'found':'找到', 'close':'关闭',
|
| 12 |
+
'shell':'命令解释器', 'return':'返回', 'if':'如果', 'else':'否则',
|
| 13 |
+
'for':'对于', 'while':'当', 'is':'是', 'in':'在', 'of':'的',
|
| 14 |
+
'to':'到', 'a':'一个', 'an':'一个', 'the':'该', 'not':'不',
|
| 15 |
+
'and':'和', 'or':'或', 'with':'与', 'id':'标识符', 'name':'名称',
|
| 16 |
+
'user':'用户', 'file':'文件', 'please':'请', 'before':'之前',
|
| 17 |
+
'after':'之后', 'capacity':'容量', 'transaction':'事务'}
|
| 18 |
+
英文段 = 正则.compile(r'[A-Z]+(?=[A-Z][a-z]|$)|[A-Z]?[a-z]+|[A-Z]+')
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def 提取译名(释义):
|
| 22 |
+
"""选计算机释义,否则选第一项可用中文;不把英文说明拼入译名。"""
|
| 23 |
+
释义 = 释义.replace('\\n', '\n').replace('\\r', '')
|
| 24 |
+
计算机 = 正则.findall(r'\[计\]([^\n]+)', 释义)
|
| 25 |
+
for 内容 in 计算机 + [释义]:
|
| 26 |
+
内容 = 正则.sub(r'\[[^\]]*\]|【[^】]*】|\([^)]*\)|([^)]*)', '', 内容)
|
| 27 |
+
for 项 in 正则.split(r'[\n,,;;/]', 内容):
|
| 28 |
+
项 = 正则.sub(r'^[a-z.\s]+', '', 项).strip()
|
| 29 |
+
if 正则.search(r'[\u4e00-\u9fff]', 项) and not 正则.search(r'[A-Za-z]', 项):
|
| 30 |
+
项 = 正则.sub(r'[^\u4e00-\u9fff0-9]', '', 项)
|
| 31 |
+
if 项:
|
| 32 |
+
return 项
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class 词典翻译器:
|
| 37 |
+
def __init__(自身, 文件):
|
| 38 |
+
自身.词表 = {}
|
| 39 |
+
自身.词形 = {}
|
| 40 |
+
with 路径(文件).open(encoding='utf-8', newline='') as 输入:
|
| 41 |
+
for 行 in 表格.DictReader(输入):
|
| 42 |
+
原词 = 行['word'].strip().casefold()
|
| 43 |
+
译名 = 提取译名(行['translation'])
|
| 44 |
+
if 译名 and 原词:
|
| 45 |
+
自身.词表.setdefault(原词, 译名)
|
| 46 |
+
for 项 in 行.get('exchange', '').split('/'):
|
| 47 |
+
if ':' in 项:
|
| 48 |
+
类型, 变体 = 项.split(':', 1)
|
| 49 |
+
if 类型 in {'d','p','i','3','r','t','s'} and 变体:
|
| 50 |
+
自身.词形.setdefault(变体.casefold(), 原词)
|
| 51 |
+
自身.词表.update(术语)
|
| 52 |
+
自身.子词树 = {}
|
| 53 |
+
自身.词组树 = {}
|
| 54 |
+
for 原词, 译名 in 自身.词表.items():
|
| 55 |
+
if 正则.fullmatch('[a-z]+', 原词) and len(原词) >= 3:
|
| 56 |
+
节点 = 自身.子词树
|
| 57 |
+
for 字 in 原词:
|
| 58 |
+
节点 = 节点.setdefault(字, {})
|
| 59 |
+
节点['译名'] = 译名
|
| 60 |
+
if 正则.fullmatch(r'[a-z]+(?:[ _-]+[a-z]+)+', 原词):
|
| 61 |
+
节点 = 自身.词组树
|
| 62 |
+
for 词 in 正则.split('[ _-]+', 原词):
|
| 63 |
+
节点 = 节点.setdefault(词, {})
|
| 64 |
+
节点['译名'] = 译名
|
| 65 |
+
自身.统计 = {'词典':0, '词形':0, '子词':0, '兜底字符':0, '词组':0}
|
| 66 |
+
|
| 67 |
+
@最近缓存(maxsize=100000)
|
| 68 |
+
def 单词(自身, 原词):
|
| 69 |
+
词 = 原词.casefold()
|
| 70 |
+
if 词 in 自身.词表:
|
| 71 |
+
自身.统计['词典'] += 1
|
| 72 |
+
return 自身.词表[词]
|
| 73 |
+
原型 = 自身.词形.get(词)
|
| 74 |
+
if 原型 in 自身.词表:
|
| 75 |
+
自身.统计['词形'] += 1
|
| 76 |
+
return 自身.词表[原型]
|
| 77 |
+
# 先最小化未覆盖字母数,再最小化切分数量。每个短子词至少三字母。
|
| 78 |
+
长度 = len(词)
|
| 79 |
+
最优 = [(0,0,'',0)] + [None] * 长度
|
| 80 |
+
for 起点 in range(长度):
|
| 81 |
+
未覆盖, 段数, 输出, 子词数 = 最优[起点]
|
| 82 |
+
方案 = (未覆盖+1, 段数+1, 输出+字母译名[词[起点]], 子词数)
|
| 83 |
+
if 最优[起点+1] is None or 方案[:2] < 最优[起点+1][:2]:
|
| 84 |
+
最优[起点+1] = 方案
|
| 85 |
+
节点 = 自身.子词树
|
| 86 |
+
for 终点 in range(起点, 长度):
|
| 87 |
+
节点 = 节点.get(词[终点])
|
| 88 |
+
if 节点 is None:
|
| 89 |
+
break
|
| 90 |
+
if '译名' in 节点:
|
| 91 |
+
方案 = (未覆盖, 段数+1, 输出+节点['译名'], 子词数+1)
|
| 92 |
+
if 最优[终点+1] is None or 方案[:2] < 最优[终点+1][:2]:
|
| 93 |
+
最优[终点+1] = 方案
|
| 94 |
+
未覆盖, _, 输出, 子词数 = 最优[-1]
|
| 95 |
+
自身.统计['兜底字符'] += 未覆盖
|
| 96 |
+
自身.统计['子词'] += 子词数
|
| 97 |
+
return 输出
|
| 98 |
+
|
| 99 |
+
def 翻译(自身, 文本):
|
| 100 |
+
# 在拆词之前处理整段哈希、UUID、十六进制字���量。
|
| 101 |
+
if 正则.fullmatch(r'[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}', 文本.strip()):
|
| 102 |
+
return '全局唯一标识符'
|
| 103 |
+
if 正则.fullmatch(r'[0-9a-fA-F]{11,}', 文本.strip()):
|
| 104 |
+
return '二进制数据'
|
| 105 |
+
文本 = 正则.sub(r'(?<![\w])0[xX][0-9a-fA-F]+(?:_[0-9a-fA-F]+)*',
|
| 106 |
+
lambda 匹配: '0天'+匹配[0][2:].lower().translate(str.maketrans(字母译名)), 文本)
|
| 107 |
+
# 驼峰先拆分;保持数字、中文、换行及结构标点的位置。
|
| 108 |
+
项目 = []
|
| 109 |
+
for 匹配 in 正则.finditer(r'[A-Za-z]+|[^A-Za-z]+', 文本):
|
| 110 |
+
项 = 匹配[0]
|
| 111 |
+
项目.extend(英文段.findall(项) if 项[0].isascii() and 项[0].isalpha() else [项])
|
| 112 |
+
输出 = []
|
| 113 |
+
位置 = 0
|
| 114 |
+
while 位置 < len(项目):
|
| 115 |
+
项 = 项目[位置]
|
| 116 |
+
if not 正则.fullmatch('[A-Za-z]+', 项):
|
| 117 |
+
清理 = 正则.sub(r'[_ \t]+', '', 项)
|
| 118 |
+
if 清理 == '-' and 位置 > 0 and 位置+1 < len(项目) and 正则.fullmatch('[A-Za-z]+', 项目[位置-1]) and 正则.fullmatch('[A-Za-z]+', 项目[位置+1]):
|
| 119 |
+
清理 = ''
|
| 120 |
+
输出.append(清理)
|
| 121 |
+
位置 += 1
|
| 122 |
+
continue
|
| 123 |
+
节点 = 自身.词组树
|
| 124 |
+
游标 = 位置
|
| 125 |
+
最后命中 = None
|
| 126 |
+
while 游标 < len(项目) and 正则.fullmatch('[A-Za-z]+', 项目[游标]):
|
| 127 |
+
节点 = 节点.get(项目[游标].casefold())
|
| 128 |
+
if 节点 is None:
|
| 129 |
+
break
|
| 130 |
+
if '译名' in 节点:
|
| 131 |
+
最后命中 = (游标+1, 节点['译名'])
|
| 132 |
+
游标 += 1
|
| 133 |
+
if 游标 < len(项目) and 正则.fullmatch(r'[_\- \t]+', 项目[游标]):
|
| 134 |
+
游标 += 1
|
| 135 |
+
if 最后命中:
|
| 136 |
+
位置, 译文 = 最后命中
|
| 137 |
+
输出.append(译文)
|
| 138 |
+
自身.统计['词组'] += 1
|
| 139 |
+
else:
|
| 140 |
+
输出.append(自身.单词(项))
|
| 141 |
+
位置 += 1
|
| 142 |
+
return ''.join(输出)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def 主程序():
|
| 146 |
+
解析器 = 参数解析.ArgumentParser(description=__doc__)
|
| 147 |
+
解析器.add_argument('--词典', type=路径, default=路径(__file__).parent/'英汉词库.csv')
|
| 148 |
+
解析器.add_argument('--文本')
|
| 149 |
+
解析器.add_argument('--输入', type=路径)
|
| 150 |
+
解析器.add_argument('--输出', type=路径)
|
| 151 |
+
参数 = 解析器.parse_args()
|
| 152 |
+
if 参数.文本 is None and (参数.输入 is None or 参数.输出 is None):
|
| 153 |
+
解析器.error('指定 --文本,或同时指定 --输入 和 --输出')
|
| 154 |
+
翻译器 = 词典翻译器(参数.词典)
|
| 155 |
+
if 参数.文本 is not None:
|
| 156 |
+
print(翻译器.翻译(参数.文本))
|
| 157 |
+
elif 参数.输入.suffix == '.parquet':
|
| 158 |
+
import pyarrow as 箭头
|
| 159 |
+
import pyarrow.parquet as 列式
|
| 160 |
+
if 参数.输入.resolve() == 参数.输出.resolve():
|
| 161 |
+
解析器.error('输出不能覆盖原文')
|
| 162 |
+
参数.输出.parent.mkdir(parents=True, exist_ok=True)
|
| 163 |
+
写入器 = None
|
| 164 |
+
try:
|
| 165 |
+
for 批次 in 列式.ParquetFile(参数.输入).iter_batches(batch_size=128):
|
| 166 |
+
表 = 箭头.Table.from_batches([批次])
|
| 167 |
+
for 名称 in ('content','path','repo_name'):
|
| 168 |
+
if 名称 in 表.column_names:
|
| 169 |
+
译文 = [翻译器.翻译(值.as_py()) if 值.as_py() is not None else None for 值 in 表[名称]]
|
| 170 |
+
字段名 = 名称+'_中文'
|
| 171 |
+
if 字段名 in 表.column_names:
|
| 172 |
+
表 = 表.drop([字段名])
|
| 173 |
+
表 = 表.append_column(字段名, 箭头.array(译文, type=箭头.string()))
|
| 174 |
+
if 写入器 is None:
|
| 175 |
+
写入器 = 列式.ParquetWriter(参数.输出, 表.schema, compression='zstd')
|
| 176 |
+
写入器.write_table(表)
|
| 177 |
+
finally:
|
| 178 |
+
if 写入器:
|
| 179 |
+
写入器.close()
|
| 180 |
+
else:
|
| 181 |
+
if 参数.输入.resolve() == 参数.输出.resolve():
|
| 182 |
+
解析器.error('输出不能覆盖原文')
|
| 183 |
+
参数.输出.parent.mkdir(parents=True, exist_ok=True)
|
| 184 |
+
参数.输出.write_text(翻译器.翻译(参数.输入.read_text(encoding='utf-8')), encoding='utf-8')
|
| 185 |
+
print(翻译器.统计)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
if __name__ == '__main__':
|
| 189 |
+
主程序()
|
许可与来源.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 许可与来源 / Licenses and provenance
|
| 2 |
+
|
| 3 |
+
Original code and its dictionary-substituted derivatives remain subject to applicable upstream code licenses; no blanket MIT license is asserted for this dataset. Retain original repository, path, content and license fields when reusing it. License metadata is inherited from the source repository and is not a per-file legal audit.
|
| 4 |
+
|
| 5 |
+
上游代码及派生内容适用各原始许可证,不将整个数据集标为 MIT。原始版权与署名文本保留在 content 列;中文代换不替代原始法律文本。代码的许可证包括 MIT、Apache、BSD、GPL、AGPL、LGPL、MPL、EPL 等,上游完整列表见其数据卡。
|
| 6 |
+
|
| 7 |
+
- CodeParrot source: https://huggingface.co/datasets/codeparrot/github-code
|
| 8 |
+
- ECDICT source: https://github.com/skywind3000/ECDICT
|
| 9 |
+
- Downloaded ECDICT notice: 词典许可证.txt
|
| 10 |
+
- Source-code publication permission/license for the project scripts is not separately specified by this preparation step; contact the publisher for reuse rights.
|
| 11 |
+
|
| 12 |
+
This release does not certify third-party dictionary-entry provenance or completeness of upstream attribution. Generated translations are not replacements for legally authoritative source notices.
|
词典许可证.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2025 Linwei
|
| 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.
|