Add files using upload-large-folder tool
Browse files- data/数据处理脚本/网络下载工具/重新下载失败SDF.sh +47 -0
- recovery_20261030/github_initial_2025-07-22/README.md +105 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/BATMAN/fetch_pubchem_info_by_cid.py +125 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/BATMAN/split_batman_herb_ingredients.py +110 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/ETCM/crawl_etcm_herb_table.py +107 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/PubChem/fetch_pubchem_cid_by_inchikey.py +102 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/PubMed/query_pubmed_by_gene.py +44 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/SymMap/fetch_pubchem_symmap.py +183 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/SymMap/fetch_symmap_ingredients.py +141 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/SymMap/fetch_symmap_targets.py +171 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/TM-MC/fetch_pubchem_info_by_compounds.py +147 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/TM-MC/split_herb_compounds.py +118 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/data/backfill_herb2_from_source.py +486 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/data/build_tcm_libraries.py +2058 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/data/export_compound_enrichment_tasks.py +143 -0
- recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/docs/legacy_tcm_repo_readme.md +105 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/herbs.ipynb +0 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/别名拼音.py +120 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/加拼音.py +23 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/BATMAN/batman.py +196 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/DCABM/dcabm.py +40 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/ETCM2/etcm.py +120 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/HERB2/herb.py +150 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/SymMap/symmap.py +120 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/TCMIO/tcmio.py +136 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/TM-MC/tmmc.py +139 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/herb_id.py +381 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/metch_id.py +130 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/诊断.py +342 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/归档/1.py +158 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/归档/dedup.py +106 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/归档/herb.py +168 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/归档/import.py +60 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/归档/query_db.py +26 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/归档/update.py +68 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/归档/update_cid.py +137 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/归档/update_inchi.py +93 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/归档/补充.py +105 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/模型/Compound/KNN_cos_distance.py +90 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/模型/Compound/Kmeans_multi-hot.py +159 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/模型/Compound/结构下载.py +174 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/check.py +3 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/embed_herb_text.py +95 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/embedding/check.py +3 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/embedding/kg/filter_pharmacopoeia_herbs.py +264 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/embedding/kg/predict_flavor_knn.py +152 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/embedding/kg/train_kg_embedding.py +96 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/embedding/text/embed_herb_text.py +95 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/抓文本.py +156 -0
- recovery_20261030/zip_preserved_scripts/111药精图模型/模型/药典对照.py +147 -0
data/数据处理脚本/网络下载工具/重新下载失败SDF.sh
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
| 4 |
+
ROOT_DIR="$(cd "$SCRIPT_DIR/../../.." && pwd)"
|
| 5 |
+
BAD_LIST="$ROOT_DIR/RE/Fingerprint/structure/ECFP4/bad_sdf_files.txt"
|
| 6 |
+
OUTDIR="$ROOT_DIR/data/SDF"
|
| 7 |
+
FAILED_LIST="$SCRIPT_DIR/failed_redownload.txt"
|
| 8 |
+
TMP_FILE="$SCRIPT_DIR/tmp_download.sdf"
|
| 9 |
+
|
| 10 |
+
echo "=== Starting batch re-download from PubChem ==="
|
| 11 |
+
|
| 12 |
+
: > "$FAILED_LIST"
|
| 13 |
+
rm -f "$TMP_FILE"
|
| 14 |
+
|
| 15 |
+
while read -r line; do
|
| 16 |
+
# 跳过空行
|
| 17 |
+
[ -z "$line" ] && continue
|
| 18 |
+
|
| 19 |
+
# 提取 CID(去掉 .sdf 扩展名)
|
| 20 |
+
cid=$(basename "$line" .sdf)
|
| 21 |
+
|
| 22 |
+
echo "Downloading CID $cid ..."
|
| 23 |
+
|
| 24 |
+
# 三次尝试
|
| 25 |
+
success=false
|
| 26 |
+
for i in 1 2 3; do
|
| 27 |
+
curl -s "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/CID/$cid/SDF" -o "$TMP_FILE"
|
| 28 |
+
|
| 29 |
+
if [ -s "$TMP_FILE" ]; then
|
| 30 |
+
mv "$TMP_FILE" "$OUTDIR/$cid.sdf"
|
| 31 |
+
echo " ✔ Success"
|
| 32 |
+
success=true
|
| 33 |
+
break
|
| 34 |
+
else
|
| 35 |
+
echo " ✘ Failed attempt $i"
|
| 36 |
+
fi
|
| 37 |
+
done
|
| 38 |
+
|
| 39 |
+
if [ "$success" = false ]; then
|
| 40 |
+
echo "$cid" >> "$FAILED_LIST"
|
| 41 |
+
echo " ❌ Completely failed: $cid"
|
| 42 |
+
fi
|
| 43 |
+
|
| 44 |
+
done < "$BAD_LIST"
|
| 45 |
+
|
| 46 |
+
echo "=== Done ==="
|
| 47 |
+
echo "Failed list saved at $FAILED_LIST"
|
recovery_20261030/github_initial_2025-07-22/README.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🌿 TCM Scripts Collection
|
| 2 |
+
本项目汇总了多个中药数据库(如 BATMAN-TCM、TCMIO、DCABM-TCM、ETCM、HERB、SymMap、TM-MC 等)的数据处理脚本,主要用于中药与化合物的映射、化合物结构标准化(PubChem)、基因靶点提取(SymMap)、文献计量分析(PubMed)等工作,适用于中药系统药理学与数据挖掘研究场景。
|
| 3 |
+
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
## 📁 目录结构
|
| 7 |
+
Projects/
|
| 8 |
+
└── TCM/
|
| 9 |
+
├── README.md
|
| 10 |
+
└── Scripts/
|
| 11 |
+
├── BATMAN/
|
| 12 |
+
│ ├── fetch_pubchem_info_by_cid.py
|
| 13 |
+
│ └── split_batman_herb_ingredients.py
|
| 14 |
+
├── DCABM-TCM/
|
| 15 |
+
│ ├── fetch_pubchem_dcabm.py
|
| 16 |
+
│ └── split_herb_compounds.py
|
| 17 |
+
├── ETCM/
|
| 18 |
+
│ └── crawl_etcm_herb_table.py
|
| 19 |
+
├── HERB/
|
| 20 |
+
│ └── fetch_herb2_compound.py
|
| 21 |
+
├── PubChem/
|
| 22 |
+
│ └── fetch_pubchem_cid_by_inchikey.py
|
| 23 |
+
├── PubMed/
|
| 24 |
+
│ └── query_pubmed_by_gene.py
|
| 25 |
+
├── SymMap/
|
| 26 |
+
│ ├── fetch_symmap_ingredients.py
|
| 27 |
+
│ └── fetch_symmap_targets.py
|
| 28 |
+
├── TCMIO/
|
| 29 |
+
│ ├── fetch_pubchem_tcmio.py
|
| 30 |
+
│ └── split_herb_compounds.py
|
| 31 |
+
├── TM-MC/
|
| 32 |
+
│ ├── fetch_pubchem_info_by_compounds.py
|
| 33 |
+
│ └── split_herb_compounds.py
|
| 34 |
+
|
| 35 |
+
---
|
| 36 |
+
|
| 37 |
+
## 🧭 各模块功能概述
|
| 38 |
+
|
| 39 |
+
### BATMAN/
|
| 40 |
+
- `fetch_pubchem_info_by_cid.py`: 通过 CID 抓取 PubChem 化合物结构信息
|
| 41 |
+
- `split_batman_herb_ingredients.py`: 将中药-化合物信息拆分并按药物导出
|
| 42 |
+
|
| 43 |
+
### DCABM-TCM/
|
| 44 |
+
- `fetch_pubchem_dcabm.py`: 抓取 DCABM 数据中的化合物 PubChem 结构
|
| 45 |
+
- `split_herb_compounds.py`: 拆分血中成分字段并构建 CID 映射表
|
| 46 |
+
|
| 47 |
+
### ETCM/
|
| 48 |
+
- `crawl_etcm_herb_table.py`: 爬取 ETCM2.0 官网中药信息表格
|
| 49 |
+
|
| 50 |
+
### HERB/
|
| 51 |
+
- `fetch_herb2_compound.py`: 提取 HERB v2 数据集中药与成分的对应关系
|
| 52 |
+
|
| 53 |
+
### PubChem/
|
| 54 |
+
- `fetch_pubchem_cid_by_inchikey.py`: 通过 InChIKey 查询 CID 与结构信息
|
| 55 |
+
|
| 56 |
+
### PubMed/
|
| 57 |
+
- `query_pubmed_by_gene.py`: 查询基因在指定疾病中的 PubMed 关联文献数
|
| 58 |
+
|
| 59 |
+
### SymMap/
|
| 60 |
+
- `fetch_symmap_ingredients.py`: 获取中药在 SymMap 中的成分信息
|
| 61 |
+
- `fetch_symmap_targets.py`: 提取 SymMap 中药相关的靶点基因
|
| 62 |
+
|
| 63 |
+
### TCMIO/
|
| 64 |
+
- `fetch_pubchem_tcmio.py`: 抓取 TCMIO 数据中的化合物结构信息
|
| 65 |
+
- `split_herb_compounds.py`: 合并中药、化合物与关系表,并按中药拆表导出
|
| 66 |
+
|
| 67 |
+
### TM-MC/
|
| 68 |
+
- `fetch_pubchem_info_by_compounds.py`: 标准化 TM-MC 数据集中化合物结构信息
|
| 69 |
+
- `split_herb_compounds.py`: 拆分 TM-MC 中药-化合物对应关系
|
| 70 |
+
|
| 71 |
+
---
|
| 72 |
+
|
| 73 |
+
## 🛠️ 依赖安装
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
pip install pandas requests tqdm openpyxl pubchempy biopython
|
| 77 |
+
|
| 78 |
+
- - -
|
| 79 |
+
|
| 80 |
+
## 🚀 使用方式示例
|
| 81 |
+
|
| 82 |
+
cd Scripts/TCMIO
|
| 83 |
+
python fetch_pubchem_tcmio.py
|
| 84 |
+
python split_herb_compounds.py
|
| 85 |
+
|
| 86 |
+
- - -
|
| 87 |
+
|
| 88 |
+
## 📦 输出说明
|
| 89 |
+
大多数 split_*.py 脚本将中药与化合物信息按中药名称导出 Excel 文件:
|
| 90 |
+
输出文件结构示例:
|
| 91 |
+
├── 当归_Angelica.xlsx
|
| 92 |
+
├── 黄芪_Astragalus.xlsx
|
| 93 |
+
└── ...
|
| 94 |
+
|
| 95 |
+
- - -
|
| 96 |
+
|
| 97 |
+
## 📮 联系方式
|
| 98 |
+
项目作者:君诩
|
| 99 |
+
邮箱:nh96452@163.com
|
| 100 |
+
欢迎任何合作建议或反馈!
|
| 101 |
+
|
| 102 |
+
---
|
| 103 |
+
|
| 104 |
+
## 📄 许可协议
|
| 105 |
+
本项目为学习与研究目的,默认为 MIT 或 CC BY 协议。请在使用脚本时注明出处。
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/BATMAN/fetch_pubchem_info_by_cid.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""用于根据 BATMAN-TCM 拆分结果中的 PubChem CID 批量抓取化合物信息。"""
|
| 2 |
+
|
| 3 |
+
# 根据BATMAN-TCM的中药-化合物信息从PubChem数据库获取化合物信息
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import pubchempy as pcp
|
| 8 |
+
|
| 9 |
+
ERROR_LOG_FILE = "info_errors.log"
|
| 10 |
+
|
| 11 |
+
def read_cids_from_excel(file_path):
|
| 12 |
+
try:
|
| 13 |
+
df = pd.read_excel(file_path)
|
| 14 |
+
if 'CID' not in df.columns:
|
| 15 |
+
print(f"⚠ 文件 {file_path} 中未找到 'CID' 列,跳过")
|
| 16 |
+
return []
|
| 17 |
+
cids = set()
|
| 18 |
+
for item in df['CID'].dropna():
|
| 19 |
+
for cid in str(item).split('|'):
|
| 20 |
+
cid = cid.strip()
|
| 21 |
+
if cid.isdigit() and int(cid) > 0:
|
| 22 |
+
cids.add(cid)
|
| 23 |
+
return list(cids)
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(f"❌ 无法读取文件 {file_path}:{e}")
|
| 26 |
+
return []
|
| 27 |
+
|
| 28 |
+
def fetch_info_for_cid(cid, max_retries=3, delay=3):
|
| 29 |
+
for attempt in range(max_retries):
|
| 30 |
+
try:
|
| 31 |
+
compound = pcp.Compound.from_cid(cid)
|
| 32 |
+
return {
|
| 33 |
+
"PubChem CID": cid,
|
| 34 |
+
"Name": compound.iupac_name or "",
|
| 35 |
+
"Molecular Formula": compound.molecular_formula or "",
|
| 36 |
+
"SMILES": compound.canonical_smiles or "",
|
| 37 |
+
"Average Weight": compound.molecular_weight or "",
|
| 38 |
+
"InChI": compound.inchi or "",
|
| 39 |
+
"InChKey": compound.inchikey or "",
|
| 40 |
+
"CAS": "" # 暂不支持 CAS
|
| 41 |
+
}
|
| 42 |
+
except Exception as e:
|
| 43 |
+
if attempt < max_retries - 1:
|
| 44 |
+
time.sleep(delay)
|
| 45 |
+
else:
|
| 46 |
+
log_error(cid, f"{e}")
|
| 47 |
+
return {
|
| 48 |
+
"PubChem CID": cid,
|
| 49 |
+
"Name": "", "Molecular Formula": "", "SMILES": "",
|
| 50 |
+
"Average Weight": "", "InChI": "", "InChKey": "", "CAS": ""
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
def log_error(cid, message):
|
| 54 |
+
with open(ERROR_LOG_FILE, 'a', encoding='utf-8') as f:
|
| 55 |
+
f.write(f"{cid}\t{message}\n")
|
| 56 |
+
|
| 57 |
+
def load_failed_cids():
|
| 58 |
+
"""从日志中加载之前失败的 CID 并去重"""
|
| 59 |
+
if not os.path.exists(ERROR_LOG_FILE):
|
| 60 |
+
return set()
|
| 61 |
+
cids = set()
|
| 62 |
+
with open(ERROR_LOG_FILE, 'r', encoding='utf-8') as f:
|
| 63 |
+
for line in f:
|
| 64 |
+
parts = line.strip().split('\t')
|
| 65 |
+
if parts and parts[0].isdigit():
|
| 66 |
+
cids.add(parts[0])
|
| 67 |
+
return cids
|
| 68 |
+
|
| 69 |
+
def process_excel_file(input_file, output_dir, failed_only=False):
|
| 70 |
+
output_name = os.path.splitext(os.path.basename(input_file))[0]
|
| 71 |
+
output_file = os.path.join(output_dir, f"{output_name}.xlsx")
|
| 72 |
+
|
| 73 |
+
# 断点续跑:文件已存在就跳过
|
| 74 |
+
if os.path.exists(output_file) and not failed_only:
|
| 75 |
+
print(f"⏭ 已处理过,跳过:{output_name}")
|
| 76 |
+
return
|
| 77 |
+
|
| 78 |
+
cids = read_cids_from_excel(input_file)
|
| 79 |
+
if not cids:
|
| 80 |
+
return
|
| 81 |
+
|
| 82 |
+
print(f"\n🔍 正在处理文件:{output_name}(共 {len(cids)} 个 CID)")
|
| 83 |
+
|
| 84 |
+
# 加载旧错误日志的 CID
|
| 85 |
+
failed_cids = load_failed_cids() if failed_only else set()
|
| 86 |
+
|
| 87 |
+
all_data = []
|
| 88 |
+
for cid in cids:
|
| 89 |
+
if failed_only and str(cid) not in failed_cids:
|
| 90 |
+
continue # 只重跑失败项
|
| 91 |
+
info = fetch_info_for_cid(cid)
|
| 92 |
+
all_data.append(info)
|
| 93 |
+
time.sleep(0.5)
|
| 94 |
+
|
| 95 |
+
if all_data:
|
| 96 |
+
df = pd.DataFrame(all_data)
|
| 97 |
+
df.to_excel(output_file, index=False)
|
| 98 |
+
print(f"✅ 信息表保存:{output_file}")
|
| 99 |
+
else:
|
| 100 |
+
print(f"⚠ 没有抓取任何信息,未生成表格:{output_name}")
|
| 101 |
+
|
| 102 |
+
def main():
|
| 103 |
+
input_dir = r"D:\2\111数据库\中药化合物对应关系\BATMAN-TCM"
|
| 104 |
+
output_dir = r"D:\2\111数据库\数据库-化合物\BATMAN-TCM_Info"
|
| 105 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 106 |
+
|
| 107 |
+
print("✨ 支持断点续跑和失败重试")
|
| 108 |
+
|
| 109 |
+
for file in sorted(os.listdir(input_dir)):
|
| 110 |
+
if file.endswith(".xlsx"):
|
| 111 |
+
process_excel_file(os.path.join(input_dir, file), output_dir)
|
| 112 |
+
|
| 113 |
+
# 自动重试失败的 CID(添加自动覆盖旧备份)
|
| 114 |
+
if os.path.exists(ERROR_LOG_FILE):
|
| 115 |
+
print("\n🔁 正在重试失败的 CID...")
|
| 116 |
+
if os.path.exists("info_errors_backup.log"):
|
| 117 |
+
os.remove("info_errors_backup.log")
|
| 118 |
+
os.rename(ERROR_LOG_FILE, "info_errors_backup.log")
|
| 119 |
+
|
| 120 |
+
for file in sorted(os.listdir(input_dir)):
|
| 121 |
+
if file.endswith(".xlsx"):
|
| 122 |
+
process_excel_file(os.path.join(input_dir, file), output_dir, failed_only=True)
|
| 123 |
+
|
| 124 |
+
if __name__ == "__main__":
|
| 125 |
+
main()
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/BATMAN/split_batman_herb_ingredients.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""用于将 BATMAN-TCM 原始中药成分字段拆分为逐味中药的独立文件。"""
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import re
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# ========== 用户自定义路径 ==========
|
| 8 |
+
HERB_PATH = r"D:\2\111数据库\数据库download\BATMAN-TCM\herb_batman.xlsx" # 原始表格路径
|
| 9 |
+
OUTPUT_DIR = r"D:\2\111数据库\中药化合物对应关系\BATMAN-TCM" # 分表保存目录
|
| 10 |
+
SAVE_MASTER = True # 是否保存合并总表(True/False)
|
| 11 |
+
MASTER_FILENAME = "中药化合物_总汇总表.xlsx"
|
| 12 |
+
# ====================================
|
| 13 |
+
|
| 14 |
+
# 创建输出文件夹(如不存在)
|
| 15 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 16 |
+
|
| 17 |
+
# 读取中药数据
|
| 18 |
+
herb_df = pd.read_excel(HERB_PATH)
|
| 19 |
+
|
| 20 |
+
# 存储拆分后的所有行
|
| 21 |
+
expanded_rows = []
|
| 22 |
+
|
| 23 |
+
# 拆分函数:提取 CID
|
| 24 |
+
def extract_cid(ingredient_str):
|
| 25 |
+
match = re.search(r"\((\d+)\)", ingredient_str)
|
| 26 |
+
return match.group(1) if match else None
|
| 27 |
+
|
| 28 |
+
# 清洗文件名非法字符
|
| 29 |
+
def clean_filename(name):
|
| 30 |
+
if pd.isna(name):
|
| 31 |
+
return ""
|
| 32 |
+
return re.sub(r'[\\/*?:"<>|]', '_', str(name).strip())
|
| 33 |
+
|
| 34 |
+
# 遍历行进行拆分
|
| 35 |
+
for _, row in herb_df.iterrows():
|
| 36 |
+
ingredients_str = str(row.get("Ingredients", ""))
|
| 37 |
+
ingredients = ingredients_str.split("|")
|
| 38 |
+
|
| 39 |
+
for ingredient in ingredients:
|
| 40 |
+
ingredient = ingredient.strip()
|
| 41 |
+
if not ingredient:
|
| 42 |
+
continue
|
| 43 |
+
|
| 44 |
+
expanded_rows.append({
|
| 45 |
+
"Pinyin.Name": row.get("Pinyin.Name"),
|
| 46 |
+
"Chinese.Name": row.get("Chinese.Name"),
|
| 47 |
+
"English.Name": row.get("English.Name"),
|
| 48 |
+
"Latin.Name": row.get("Latin.Name"),
|
| 49 |
+
"Ingredient.Name": ingredient,
|
| 50 |
+
"CID": extract_cid(ingredient)
|
| 51 |
+
})
|
| 52 |
+
|
| 53 |
+
# 构建 DataFrame
|
| 54 |
+
expanded_df = pd.DataFrame(expanded_rows)
|
| 55 |
+
|
| 56 |
+
# 保存总表(可选)
|
| 57 |
+
if SAVE_MASTER:
|
| 58 |
+
master_path = os.path.join(OUTPUT_DIR, MASTER_FILENAME)
|
| 59 |
+
expanded_df.to_excel(master_path, index=False)
|
| 60 |
+
print(f"📄 汇总总表已保存至:{master_path}")
|
| 61 |
+
|
| 62 |
+
# === 替换空值用于分组和命名 ===
|
| 63 |
+
grouped_df = expanded_df.copy()
|
| 64 |
+
grouped_df["Pinyin.Name"] = grouped_df["Pinyin.Name"].fillna("未知拼音")
|
| 65 |
+
grouped_df["Latin.Name"] = grouped_df["Latin.Name"].fillna("未知拉丁")
|
| 66 |
+
|
| 67 |
+
# 分组并保存
|
| 68 |
+
grouped = grouped_df.groupby(["Pinyin.Name", "Latin.Name"])
|
| 69 |
+
|
| 70 |
+
from collections import defaultdict
|
| 71 |
+
|
| 72 |
+
# 用于记录相同文件名前缀出现的次数
|
| 73 |
+
file_name_counter = defaultdict(int)
|
| 74 |
+
|
| 75 |
+
for (pinyin_name, latin_name), group in grouped:
|
| 76 |
+
pinyin_clean = clean_filename(pinyin_name)
|
| 77 |
+
latin_clean = clean_filename(latin_name)
|
| 78 |
+
|
| 79 |
+
base_file_name = f"{pinyin_clean}__{latin_clean}"
|
| 80 |
+
file_name_counter[base_file_name] += 1
|
| 81 |
+
|
| 82 |
+
# 若是第一次出现就正常命名,否则添加编号后缀
|
| 83 |
+
if file_name_counter[base_file_name] == 1:
|
| 84 |
+
file_name = f"{base_file_name}.xlsx"
|
| 85 |
+
else:
|
| 86 |
+
file_name = f"{base_file_name}__{file_name_counter[base_file_name]}.xlsx"
|
| 87 |
+
|
| 88 |
+
file_path = os.path.join(OUTPUT_DIR, file_name)
|
| 89 |
+
group.to_excel(file_path, index=False)
|
| 90 |
+
|
| 91 |
+
print(f"\n✅ 全部完成,共处理 {len(grouped)} 个中药,分表已保存至:{OUTPUT_DIR}")
|
| 92 |
+
|
| 93 |
+
empty_ingredients = herb_df["Ingredients"].fillna("").apply(lambda x: all(i.strip() == "" for i in x.split("|")))
|
| 94 |
+
print(f"⚠️ 成分完全为空或无效的中药数:{empty_ingredients.sum()}")
|
| 95 |
+
|
| 96 |
+
# 用于检查是否有文件名重复(也就是组名重复)
|
| 97 |
+
seen_files = set()
|
| 98 |
+
|
| 99 |
+
for (pinyin_name, latin_name), group in grouped:
|
| 100 |
+
pinyin_clean = clean_filename(pinyin_name)
|
| 101 |
+
latin_clean = clean_filename(latin_name)
|
| 102 |
+
|
| 103 |
+
file_name = f"{pinyin_clean}__{latin_clean}.xlsx"
|
| 104 |
+
file_path = os.path.join(OUTPUT_DIR, file_name)
|
| 105 |
+
|
| 106 |
+
if file_name in seen_files:
|
| 107 |
+
print(f"⚠️ 文件名重复:{file_name}")
|
| 108 |
+
seen_files.add(file_name)
|
| 109 |
+
|
| 110 |
+
group.to_excel(file_path, index=False)
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/ETCM/crawl_etcm_herb_table.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""用于从 ETCM 数据源抓取中药基础信息表。"""
|
| 2 |
+
|
| 3 |
+
# 用于抓取ETCM2.0数据库的中药表格页
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from selenium import webdriver
|
| 8 |
+
from selenium.webdriver.common.by import By
|
| 9 |
+
from selenium.webdriver.edge.service import Service
|
| 10 |
+
from selenium.webdriver.edge.options import Options
|
| 11 |
+
from selenium.webdriver.support.ui import WebDriverWait
|
| 12 |
+
from selenium.webdriver.support import expected_conditions as EC
|
| 13 |
+
from selenium.common.exceptions import (TimeoutException, NoSuchElementException, ElementClickInterceptedException, WebDriverException)
|
| 14 |
+
|
| 15 |
+
# 配置路径
|
| 16 |
+
DATA_PATH = "D:/2/download/etcm_data.xlsx"
|
| 17 |
+
START_PAGE = 1
|
| 18 |
+
MAX_PAGE = 104 # 明确限制最大页数
|
| 19 |
+
|
| 20 |
+
# 初始化浏览器
|
| 21 |
+
def init_browser():
|
| 22 |
+
options = Options()
|
| 23 |
+
options.add_argument('--headless')
|
| 24 |
+
options.add_argument('--disable-gpu')
|
| 25 |
+
service = Service()
|
| 26 |
+
driver = webdriver.Edge(service=service, options=options)
|
| 27 |
+
driver.get("http://www.tcmip.cn/ETCM2/front/#/browse/herb")
|
| 28 |
+
return driver
|
| 29 |
+
|
| 30 |
+
# 断点续跑功能:读取上次已抓取数据
|
| 31 |
+
def load_existing_data():
|
| 32 |
+
if os.path.exists(DATA_PATH):
|
| 33 |
+
df = pd.read_excel(DATA_PATH)
|
| 34 |
+
return df
|
| 35 |
+
return pd.DataFrame(columns=["拉丁名", "拼音名", "药性", "药味", "归经"])
|
| 36 |
+
|
| 37 |
+
# 抓取单页数据
|
| 38 |
+
def get_table_data(driver):
|
| 39 |
+
try:
|
| 40 |
+
table = WebDriverWait(driver, 10).until(
|
| 41 |
+
EC.presence_of_element_located((By.CSS_SELECTOR, "table.el-table__body"))
|
| 42 |
+
)
|
| 43 |
+
rows = table.find_elements(By.CSS_SELECTOR, "tbody tr")
|
| 44 |
+
data = []
|
| 45 |
+
for row in rows:
|
| 46 |
+
cols = row.find_elements(By.CSS_SELECTOR, "td")
|
| 47 |
+
if len(cols) >= 5:
|
| 48 |
+
data.append([
|
| 49 |
+
cols[0].text.strip(),
|
| 50 |
+
cols[1].text.strip(),
|
| 51 |
+
cols[2].text.strip(),
|
| 52 |
+
cols[3].text.strip(),
|
| 53 |
+
cols[4].text.strip()
|
| 54 |
+
])
|
| 55 |
+
return data
|
| 56 |
+
except TimeoutException:
|
| 57 |
+
print("未找到表格,跳过本页")
|
| 58 |
+
return []
|
| 59 |
+
|
| 60 |
+
# 翻页逻辑(强制点击下一页按钮)
|
| 61 |
+
def go_to_next_page(driver):
|
| 62 |
+
try:
|
| 63 |
+
next_button = WebDriverWait(driver, 10).until(
|
| 64 |
+
EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn-next"))
|
| 65 |
+
)
|
| 66 |
+
if "is-disabled" in next_button.get_attribute("class"):
|
| 67 |
+
return False
|
| 68 |
+
driver.execute_script("arguments[0].click();", next_button)
|
| 69 |
+
time.sleep(2.5)
|
| 70 |
+
return True
|
| 71 |
+
except (TimeoutException, ElementClickInterceptedException):
|
| 72 |
+
print("翻页失败或已到最后一页")
|
| 73 |
+
return False
|
| 74 |
+
|
| 75 |
+
# 主程序
|
| 76 |
+
def main():
|
| 77 |
+
driver = init_browser()
|
| 78 |
+
data = load_existing_data()
|
| 79 |
+
scraped_set = set(tuple(row) for row in data.values)
|
| 80 |
+
page = START_PAGE if data.empty else (len(data) // 20 + 1)
|
| 81 |
+
|
| 82 |
+
while page <= MAX_PAGE:
|
| 83 |
+
print(f"===== 正在抓取第 {page} 页 =====")
|
| 84 |
+
page_data = get_table_data(driver)
|
| 85 |
+
new_data = [row for row in page_data if tuple(row) not in scraped_set]
|
| 86 |
+
|
| 87 |
+
if new_data:
|
| 88 |
+
print(f"抓取到 {len(new_data)} 条新数据")
|
| 89 |
+
for row in new_data:
|
| 90 |
+
scraped_set.add(tuple(row))
|
| 91 |
+
data = pd.concat([data, pd.DataFrame(new_data, columns=["拉丁名", "拼音名", "药性", "药味", "归经"])], ignore_index=True)
|
| 92 |
+
else:
|
| 93 |
+
print("本页无新数据或无数据,跳过")
|
| 94 |
+
|
| 95 |
+
if not go_to_next_page(driver):
|
| 96 |
+
break
|
| 97 |
+
|
| 98 |
+
page += 1
|
| 99 |
+
|
| 100 |
+
driver.quit()
|
| 101 |
+
|
| 102 |
+
data.drop_duplicates(inplace=True)
|
| 103 |
+
data.to_excel(DATA_PATH, index=False)
|
| 104 |
+
print(f"数据抓取完成,共 {len(data)} 条记录,已保存至:{DATA_PATH}")
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
main()
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/PubChem/fetch_pubchem_cid_by_inchikey.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""用于根据 InChIKey 从 PubChem 查询并补充 CID 信息。"""
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import requests
|
| 5 |
+
import os
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
# 设置文件路径与输出路径
|
| 9 |
+
input_file = r"D:\2\谢\蛋白文献\副本Combined_DEMs_list_with_SMILES(2).xlsx"
|
| 10 |
+
output_folder = r"D:\2\谢\蛋白文献\fenzi"
|
| 11 |
+
output_excel = r"D:\2\谢\蛋白文献\副本Combined_DEMs_list_with_CID.xlsx" # 保存带CID的新表
|
| 12 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 13 |
+
|
| 14 |
+
# 读取 Excel 表格
|
| 15 |
+
df = pd.read_excel(input_file)
|
| 16 |
+
|
| 17 |
+
# 初始化 CID 列
|
| 18 |
+
df['PubChem_CID'] = None
|
| 19 |
+
|
| 20 |
+
# 记录下载失败项
|
| 21 |
+
failed = []
|
| 22 |
+
|
| 23 |
+
# 主循环
|
| 24 |
+
for index, row in df.iterrows():
|
| 25 |
+
metabolite_name = str(row['Metabolite name']).strip()
|
| 26 |
+
inchikey = str(row['Inchikey']).strip()
|
| 27 |
+
|
| 28 |
+
# 如果已填 CID(适用于断点续跑),则使用原值
|
| 29 |
+
cid_in_df = str(row['PubChem_CID']) if pd.notna(row['PubChem_CID']) else None
|
| 30 |
+
|
| 31 |
+
# 跳过无效 InChIKey
|
| 32 |
+
if not inchikey or inchikey.lower() == 'nan':
|
| 33 |
+
print(f"[{index+1}] 跳过无效 InChIKey:{metabolite_name}")
|
| 34 |
+
failed.append(metabolite_name)
|
| 35 |
+
continue
|
| 36 |
+
|
| 37 |
+
# 查询 CID(如原表已有则跳过)
|
| 38 |
+
if cid_in_df and cid_in_df.lower() != 'none':
|
| 39 |
+
cid = cid_in_df
|
| 40 |
+
else:
|
| 41 |
+
try:
|
| 42 |
+
cid_url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/inchikey/{inchikey}/cids/TXT"
|
| 43 |
+
cid_response = requests.get(cid_url, timeout=10)
|
| 44 |
+
if cid_response.status_code == 200 and cid_response.text.strip():
|
| 45 |
+
cid = cid_response.text.strip().split('\n')[0]
|
| 46 |
+
df.at[index, 'PubChem_CID'] = cid # 写入表格
|
| 47 |
+
else:
|
| 48 |
+
raise Exception("CID 获取失败")
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"⚠ CID 查询失败:{metabolite_name} - {e}")
|
| 51 |
+
failed.append(metabolite_name)
|
| 52 |
+
continue
|
| 53 |
+
|
| 54 |
+
# 构造文件名(以 CID 命名)
|
| 55 |
+
file_path = os.path.join(output_folder, f"{cid}.sdf")
|
| 56 |
+
|
| 57 |
+
# 断点续跑:文件存在则跳过下载
|
| 58 |
+
if os.path.exists(file_path):
|
| 59 |
+
print(f"[{index+1}] 跳过已存在:{cid}.sdf")
|
| 60 |
+
continue
|
| 61 |
+
|
| 62 |
+
print(f"[{index+1}] 正在处理:{metabolite_name} (CID: {cid})")
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
# 下载 3D 或 2D SDF 文件
|
| 66 |
+
sdf_url_3d = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/SDF?record_type=3d"
|
| 67 |
+
sdf_url_2d = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/SDF?record_type=2d"
|
| 68 |
+
|
| 69 |
+
response = requests.get(sdf_url_3d, timeout=10)
|
| 70 |
+
if response.status_code == 200 and "M END" in response.text:
|
| 71 |
+
with open(file_path, 'w', encoding='utf-8') as f:
|
| 72 |
+
f.write(response.text)
|
| 73 |
+
print(f"✔ 成功下载 3D:{cid}.sdf")
|
| 74 |
+
else:
|
| 75 |
+
# 尝试 2D
|
| 76 |
+
response = requests.get(sdf_url_2d, timeout=10)
|
| 77 |
+
if response.status_code == 200 and "M END" in response.text:
|
| 78 |
+
with open(file_path, 'w', encoding='utf-8') as f:
|
| 79 |
+
f.write(response.text)
|
| 80 |
+
print(f"✔ 成功下载 2D:{cid}.sdf")
|
| 81 |
+
else:
|
| 82 |
+
raise Exception("结构下载失败")
|
| 83 |
+
|
| 84 |
+
time.sleep(0.5) # 请求间隔
|
| 85 |
+
|
| 86 |
+
except Exception as e:
|
| 87 |
+
print(f"⚠ 下载失败:{metabolite_name} - {e}")
|
| 88 |
+
failed.append(metabolite_name)
|
| 89 |
+
continue
|
| 90 |
+
|
| 91 |
+
# 保存更新后的 Excel 表格
|
| 92 |
+
df.to_excel(output_excel, index=False)
|
| 93 |
+
print(f"\n📄 新表格已保存至:{output_excel}")
|
| 94 |
+
|
| 95 |
+
# 保存失败记录
|
| 96 |
+
if failed:
|
| 97 |
+
fail_log = os.path.join(output_folder, 'download_failed.txt')
|
| 98 |
+
with open(fail_log, 'w', encoding='utf-8') as f:
|
| 99 |
+
f.write("\n".join(failed))
|
| 100 |
+
print(f"\n⚠ 共 {len(failed)} 个项目下载失败,记录保存在 {fail_log}")
|
| 101 |
+
else:
|
| 102 |
+
print("\n🎉 所有结构成功下载。")
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/PubMed/query_pubmed_by_gene.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""用于按基因和疾病关键词查询 PubMed 相关文献数量。"""
|
| 2 |
+
|
| 3 |
+
from Bio import Entrez
|
| 4 |
+
import time
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
# 设置你的邮箱(用于 NCBI 识别用户)
|
| 8 |
+
Entrez.email = "nh96452@163.com"
|
| 9 |
+
|
| 10 |
+
# 从表格中读取靶点列表
|
| 11 |
+
file_path = r"D:\2\网药\四逆散\机器学习\新建 XLSX 工作表.xlsx" # 或 your_file.csv
|
| 12 |
+
column_name = "靶点" # 你存储靶点名称的列名
|
| 13 |
+
|
| 14 |
+
# 自动判断 Excel 或 CSV
|
| 15 |
+
if file_path.endswith(".xlsx"):
|
| 16 |
+
df_input = pd.read_excel(file_path)
|
| 17 |
+
else:
|
| 18 |
+
df_input = pd.read_csv(file_path)
|
| 19 |
+
|
| 20 |
+
gene_list = df_input[column_name].dropna().astype(str).unique().tolist()
|
| 21 |
+
|
| 22 |
+
# 查询关键词中可以加入具体疾病,如 AND cancer,或只用基因名
|
| 23 |
+
query_suffix = "gastric ulcer" # 例:" AND cancer" 可指定疾病领域
|
| 24 |
+
|
| 25 |
+
# 存储结果
|
| 26 |
+
results = []
|
| 27 |
+
|
| 28 |
+
for gene in gene_list:
|
| 29 |
+
query = f"{gene}[Gene]{query_suffix}"
|
| 30 |
+
try:
|
| 31 |
+
handle = Entrez.esearch(db="pubmed", term=query)
|
| 32 |
+
record = Entrez.read(handle)
|
| 33 |
+
count = int(record["Count"])
|
| 34 |
+
results.append((gene, count))
|
| 35 |
+
print(f"{gene}: {count}")
|
| 36 |
+
except Exception as e:
|
| 37 |
+
print(f"Error for {gene}: {e}")
|
| 38 |
+
results.append((gene, 0))
|
| 39 |
+
|
| 40 |
+
time.sleep(0.5) # 避免访问过快导致被封IP
|
| 41 |
+
|
| 42 |
+
# 保存为 CSV
|
| 43 |
+
df = pd.DataFrame(results, columns=["Gene", "PubMed_Count"])
|
| 44 |
+
df.to_csv("PubMed_counts.csv", index=False)
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/SymMap/fetch_pubchem_symmap.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""用于根据 SymMap 成分信息从 PubChem 补充标准化化合物信息。"""
|
| 3 |
+
|
| 4 |
+
# 根据 SymMap 的中药-化合物信息从 PubChem 数据库获取化合物信息
|
| 5 |
+
import os
|
| 6 |
+
import time
|
| 7 |
+
import re
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import pubchempy as pcp
|
| 10 |
+
|
| 11 |
+
# ✅ 设置请求超时(PubChem API)
|
| 12 |
+
pcp.requests_timeout = 10 # 秒
|
| 13 |
+
|
| 14 |
+
def log_error(identifier, message, error_log_file):
|
| 15 |
+
with open(error_log_file, 'a', encoding='utf-8') as f:
|
| 16 |
+
f.write(f"{identifier}\t{message}\n")
|
| 17 |
+
|
| 18 |
+
def load_failed_ids(error_log_file):
|
| 19 |
+
if not os.path.exists(error_log_file):
|
| 20 |
+
return set()
|
| 21 |
+
with open(error_log_file, 'r', encoding='utf-8') as f:
|
| 22 |
+
return set(line.strip().split('\t')[0] for line in f)
|
| 23 |
+
|
| 24 |
+
def extract_cas_from_synonyms(synonyms):
|
| 25 |
+
cas_pattern = re.compile(r'^\d{2,7}-\d{2}-\d$')
|
| 26 |
+
for syn in synonyms:
|
| 27 |
+
if cas_pattern.match(syn):
|
| 28 |
+
return syn
|
| 29 |
+
return ""
|
| 30 |
+
|
| 31 |
+
def fetch_info(identifier, id_type='name', max_retries=3, delay=3, error_log_file=None):
|
| 32 |
+
"""根据 name/CID/CAS 检索 PubChem"""
|
| 33 |
+
for attempt in range(max_retries):
|
| 34 |
+
try:
|
| 35 |
+
compounds = pcp.get_compounds(identifier, id_type)
|
| 36 |
+
if not compounds:
|
| 37 |
+
raise ValueError(f"No compound found for {id_type}:{identifier}")
|
| 38 |
+
compound = compounds[0]
|
| 39 |
+
|
| 40 |
+
cas_number = ""
|
| 41 |
+
if compound.synonyms:
|
| 42 |
+
cas_number = extract_cas_from_synonyms(compound.synonyms)
|
| 43 |
+
|
| 44 |
+
return {
|
| 45 |
+
"Queried Identifier": f"{id_type}:{identifier}",
|
| 46 |
+
"PubChem CID": compound.cid or "",
|
| 47 |
+
"IUPAC Name": compound.iupac_name or "",
|
| 48 |
+
"Molecular Formula": compound.molecular_formula or "",
|
| 49 |
+
"SMILES": compound.canonical_smiles or "",
|
| 50 |
+
"Average Weight": compound.molecular_weight or "",
|
| 51 |
+
"InChI": compound.inchi or "",
|
| 52 |
+
"InChKey": compound.inchikey or "",
|
| 53 |
+
"CAS": cas_number
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
except Exception as e:
|
| 57 |
+
if attempt < max_retries - 1:
|
| 58 |
+
time.sleep(delay)
|
| 59 |
+
else:
|
| 60 |
+
if error_log_file:
|
| 61 |
+
log_error(f"{id_type}:{identifier}", str(e), error_log_file)
|
| 62 |
+
return None
|
| 63 |
+
|
| 64 |
+
def read_csv_identifiers(file_path):
|
| 65 |
+
"""
|
| 66 |
+
读取 CSV(Column_2=name, Column_7=CID, Column_8=CAS),
|
| 67 |
+
支持 | 分隔的多个值。返回列表,每个元素是一个候选值的集合(同一行的多个候选)。
|
| 68 |
+
"""
|
| 69 |
+
encodings = ["utf-8", "utf-8-sig", "gbk", "gb18030"]
|
| 70 |
+
for enc in encodings:
|
| 71 |
+
try:
|
| 72 |
+
df = pd.read_csv(file_path, encoding=enc)
|
| 73 |
+
break
|
| 74 |
+
except UnicodeDecodeError:
|
| 75 |
+
continue
|
| 76 |
+
else:
|
| 77 |
+
raise ValueError(f"❌ 无法识别文件编码: {file_path}")
|
| 78 |
+
|
| 79 |
+
all_rows = []
|
| 80 |
+
|
| 81 |
+
for _, row in df.iterrows():
|
| 82 |
+
candidates = []
|
| 83 |
+
|
| 84 |
+
# Column_2 -> name
|
| 85 |
+
names_raw = str(row.get("Column_2", "")).strip()
|
| 86 |
+
if names_raw and names_raw.lower() != "nan":
|
| 87 |
+
candidates.extend([(n.strip(), "name") for n in names_raw.split("|") if n.strip()])
|
| 88 |
+
|
| 89 |
+
# Column_7 -> CID
|
| 90 |
+
cids_raw = str(row.get("Column_7", "")).strip()
|
| 91 |
+
if cids_raw and cids_raw.lower() != "nan":
|
| 92 |
+
for c in cids_raw.split("|"):
|
| 93 |
+
c = c.strip()
|
| 94 |
+
if c.isdigit(): # CID 必须是数字
|
| 95 |
+
candidates.append((c, "cid"))
|
| 96 |
+
|
| 97 |
+
# Column_8 -> CAS(按 name 检索)
|
| 98 |
+
cas_raw = str(row.get("Column_8", "")).strip()
|
| 99 |
+
if cas_raw and cas_raw.lower() != "nan":
|
| 100 |
+
candidates.extend([(c.strip(), "name") for c in cas_raw.split("|") if c.strip()])
|
| 101 |
+
|
| 102 |
+
# 去重
|
| 103 |
+
seen = set()
|
| 104 |
+
unique_candidates = []
|
| 105 |
+
for item in candidates:
|
| 106 |
+
if item not in seen:
|
| 107 |
+
seen.add(item)
|
| 108 |
+
unique_candidates.append(item)
|
| 109 |
+
|
| 110 |
+
if unique_candidates:
|
| 111 |
+
all_rows.append(unique_candidates)
|
| 112 |
+
|
| 113 |
+
return all_rows
|
| 114 |
+
|
| 115 |
+
def process_csv_file(input_file, output_dir, error_log_file):
|
| 116 |
+
output_name = os.path.splitext(os.path.basename(input_file))[0]
|
| 117 |
+
output_file = os.path.join(output_dir, f"{output_name}.xlsx")
|
| 118 |
+
|
| 119 |
+
# 如果已有结果表格,则先读出来
|
| 120 |
+
if os.path.exists(output_file):
|
| 121 |
+
print(f"🔄 检测到已有结果表格:{output_file},将尝试补充缺失数据...")
|
| 122 |
+
df_existing = pd.read_excel(output_file)
|
| 123 |
+
else:
|
| 124 |
+
df_existing = pd.DataFrame()
|
| 125 |
+
|
| 126 |
+
rows = read_csv_identifiers(input_file)
|
| 127 |
+
if not rows:
|
| 128 |
+
print(f"⚠ 文件 {output_name} 无有效记录,跳过处理。")
|
| 129 |
+
return
|
| 130 |
+
|
| 131 |
+
all_data = []
|
| 132 |
+
|
| 133 |
+
for row_idx, candidates in enumerate(rows, 1):
|
| 134 |
+
row_success = False
|
| 135 |
+
for identifier, id_type in candidates:
|
| 136 |
+
key = f"{id_type}:{identifier}"
|
| 137 |
+
|
| 138 |
+
# 如果已有结果表格里已经有数据,跳过
|
| 139 |
+
if not df_existing.empty and "Queried Identifier" in df_existing.columns:
|
| 140 |
+
if (df_existing["Queried Identifier"] == key).any():
|
| 141 |
+
row_success = True
|
| 142 |
+
break
|
| 143 |
+
|
| 144 |
+
print(f"📦 [Row {row_idx}] 查询:{key} ...")
|
| 145 |
+
info = fetch_info(identifier, id_type, error_log_file=error_log_file)
|
| 146 |
+
if info:
|
| 147 |
+
all_data.append(info)
|
| 148 |
+
# ✅ 如果成功就不再尝试该行的其他候选值
|
| 149 |
+
if info["PubChem CID"] or info["CAS"]:
|
| 150 |
+
row_success = True
|
| 151 |
+
break
|
| 152 |
+
|
| 153 |
+
time.sleep(0.3)
|
| 154 |
+
|
| 155 |
+
if not row_success:
|
| 156 |
+
print(f"⚠ Row {row_idx} 全部候选检索失败。")
|
| 157 |
+
|
| 158 |
+
# 合并旧数据和新数据
|
| 159 |
+
if all_data:
|
| 160 |
+
df_new = pd.DataFrame(all_data)
|
| 161 |
+
if not df_existing.empty:
|
| 162 |
+
df_result = pd.concat([df_existing, df_new], ignore_index=True).drop_duplicates(subset=["Queried Identifier"])
|
| 163 |
+
else:
|
| 164 |
+
df_result = df_new
|
| 165 |
+
df_result.to_excel(output_file, index=False)
|
| 166 |
+
print(f"✅ 信息保存至:{output_file}")
|
| 167 |
+
else:
|
| 168 |
+
print(f"⚠ {output_name} 无新数据,未更新。")
|
| 169 |
+
|
| 170 |
+
def main():
|
| 171 |
+
input_dir = r"D:\2\111数据库\中药化合物对应关系\SymMap\my_project\资料" # 输入 CSV 文件夹
|
| 172 |
+
output_dir = r"D:\2\111数据库\数据库-化合物\SymMap_Info" # 输出目录
|
| 173 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 174 |
+
error_log_file = os.path.join(output_dir, "csv_info_errors.log")
|
| 175 |
+
|
| 176 |
+
print("✨ 基于 CSV 表格的 PubChem 化合物提取工具")
|
| 177 |
+
|
| 178 |
+
for file in sorted(os.listdir(input_dir)):
|
| 179 |
+
if file.endswith(".csv"):
|
| 180 |
+
process_csv_file(os.path.join(input_dir, file), output_dir, error_log_file)
|
| 181 |
+
|
| 182 |
+
if __name__ == "__main__":
|
| 183 |
+
main()
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/SymMap/fetch_symmap_ingredients.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""用于从 SymMap 抓取中药对应的成分信息。"""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import requests
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from selenium import webdriver
|
| 7 |
+
from selenium.webdriver.edge.service import Service
|
| 8 |
+
from selenium.webdriver.common.by import By
|
| 9 |
+
from selenium.webdriver.support.ui import WebDriverWait
|
| 10 |
+
from selenium.webdriver.support import expected_conditions as EC
|
| 11 |
+
|
| 12 |
+
# 设置浏览器驱动路径
|
| 13 |
+
driver_path = "D:\\Software\\edgedriver_win64\\msedgedriver.exe"
|
| 14 |
+
service = Service(driver_path)
|
| 15 |
+
driver = webdriver.Edge(service=service)
|
| 16 |
+
|
| 17 |
+
# 定义API端点URL
|
| 18 |
+
url_search = 'http://www.symmap.org/search/'
|
| 19 |
+
keys = ['矮地茶']
|
| 20 |
+
table_name = 'Ingredient'
|
| 21 |
+
save_path = r'D:\2\111数据库\中药化合物对应关系\SymMap\my_project\资料'
|
| 22 |
+
|
| 23 |
+
if not os.path.exists(save_path):
|
| 24 |
+
os.makedirs(save_path)
|
| 25 |
+
|
| 26 |
+
def get_herb_id(key):
|
| 27 |
+
search_data = {'table_name': 'Herb', 'key': key}
|
| 28 |
+
try:
|
| 29 |
+
print(f'正在发送查询请求: {key}')
|
| 30 |
+
response = requests.post(url_search, data=search_data, timeout=30)
|
| 31 |
+
response.raise_for_status()
|
| 32 |
+
print(f'{key} 查询请求成功')
|
| 33 |
+
except requests.exceptions.RequestException as e:
|
| 34 |
+
print(f'{key} 请求失败: {e}')
|
| 35 |
+
return None
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
search_json = response.json()
|
| 39 |
+
if not search_json.get('data'):
|
| 40 |
+
print(f'{key} 返回了空数据')
|
| 41 |
+
return None
|
| 42 |
+
rrid = search_json['data'][0]['Herb_id']
|
| 43 |
+
print(f'获取到 {key} 的 Herb_id: {rrid}')
|
| 44 |
+
return rrid
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print(f'{key} Herb_id 解析失败: {e}')
|
| 47 |
+
print(f'响应内容: {response.text}')
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
def fetch_ingredient_data(rrid):
|
| 51 |
+
detail_url = f'http://www.symmap.org/detail/{rrid}'
|
| 52 |
+
driver.get(detail_url)
|
| 53 |
+
seen_ids = set()
|
| 54 |
+
headers = []
|
| 55 |
+
ingredients = []
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
print(f'正在发送详细请求: {rrid}')
|
| 59 |
+
ingredient_button = WebDriverWait(driver, 30).until(
|
| 60 |
+
EC.element_to_be_clickable((By.XPATH, "//button[text()='Ingredient']"))
|
| 61 |
+
)
|
| 62 |
+
ingredient_button.click()
|
| 63 |
+
print(f'{rrid} 的详细请求成功')
|
| 64 |
+
except Exception as e:
|
| 65 |
+
print(f'请求 {rrid} 的详细信息失败: {e}')
|
| 66 |
+
return []
|
| 67 |
+
|
| 68 |
+
while True:
|
| 69 |
+
try:
|
| 70 |
+
WebDriverWait(driver, 30).until(
|
| 71 |
+
EC.presence_of_element_located(
|
| 72 |
+
(By.XPATH, "//div[contains(@class, 'fixed-table-body')]//table[contains(@class, 'table-hover')]"))
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
WebDriverWait(driver, 30).until_not(
|
| 76 |
+
EC.text_to_be_present_in_element(
|
| 77 |
+
(By.XPATH, "//div[contains(@class, 'fixed-table-body')]//table//tbody"),
|
| 78 |
+
"Searching, please wait..."
|
| 79 |
+
)
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
table = driver.find_element(By.XPATH, "//div[contains(@class, 'fixed-table-body')]//table")
|
| 83 |
+
rows = table.find_elements(By.XPATH, ".//tbody/tr")
|
| 84 |
+
|
| 85 |
+
if not headers:
|
| 86 |
+
header_elements = table.find_elements(By.XPATH, ".//thead/tr/th")
|
| 87 |
+
headers = [header.text.strip() for header in header_elements]
|
| 88 |
+
print("表头:", headers)
|
| 89 |
+
|
| 90 |
+
new_ids = set()
|
| 91 |
+
for row in rows:
|
| 92 |
+
columns = row.find_elements(By.TAG_NAME, "td")
|
| 93 |
+
if columns:
|
| 94 |
+
row_data = [col.text.strip() for col in columns]
|
| 95 |
+
row_dict = dict(zip(headers, row_data))
|
| 96 |
+
unique_id = row_data[0] # 默认用第一列为唯一标识
|
| 97 |
+
if unique_id and unique_id not in seen_ids:
|
| 98 |
+
ingredients.append(row_dict)
|
| 99 |
+
new_ids.add(unique_id)
|
| 100 |
+
|
| 101 |
+
if not new_ids:
|
| 102 |
+
print("没有新数据,停止翻页。")
|
| 103 |
+
break
|
| 104 |
+
|
| 105 |
+
seen_ids.update(new_ids)
|
| 106 |
+
|
| 107 |
+
next_button = driver.find_elements(By.XPATH, "//a[@aria-label='next page' and normalize-space(text())='›']")
|
| 108 |
+
if next_button:
|
| 109 |
+
print("点击下一页...")
|
| 110 |
+
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//a[@aria-label='next page']")))
|
| 111 |
+
next_button[0].click()
|
| 112 |
+
WebDriverWait(driver, 30).until(EC.staleness_of(rows[0]))
|
| 113 |
+
else:
|
| 114 |
+
print("没有更多页面,结束翻页。")
|
| 115 |
+
break
|
| 116 |
+
|
| 117 |
+
except Exception as e:
|
| 118 |
+
print(f"处理分页时发生错误: {e}")
|
| 119 |
+
break
|
| 120 |
+
|
| 121 |
+
print(f'提取的成分数据共 {len(ingredients)} 条')
|
| 122 |
+
return ingredients
|
| 123 |
+
|
| 124 |
+
# 主流程
|
| 125 |
+
for key in keys:
|
| 126 |
+
print(f'开始处理: {key}')
|
| 127 |
+
herb_id = get_herb_id(key)
|
| 128 |
+
if not herb_id:
|
| 129 |
+
continue
|
| 130 |
+
ingredients = fetch_ingredient_data(herb_id)
|
| 131 |
+
if not ingredients:
|
| 132 |
+
continue
|
| 133 |
+
df = pd.DataFrame(ingredients)
|
| 134 |
+
df.to_csv(os.path.join(save_path, f'{key}+{table_name}.csv'), encoding='gb18030', index=False)
|
| 135 |
+
print(f'已保存 {key} 的 {table_name} 数据')
|
| 136 |
+
print(f'完成处理: {key}\n')
|
| 137 |
+
|
| 138 |
+
# 关闭浏览器
|
| 139 |
+
driver.quit()
|
| 140 |
+
|
| 141 |
+
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/SymMap/fetch_symmap_targets.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""用于从 SymMap 抓取中药相关的靶点基因信息。"""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import requests
|
| 7 |
+
from selenium import webdriver
|
| 8 |
+
from selenium.webdriver.edge.service import Service
|
| 9 |
+
from selenium.webdriver.common.by import By
|
| 10 |
+
from selenium.webdriver.support.ui import WebDriverWait
|
| 11 |
+
from selenium.webdriver.support import expected_conditions as EC
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
|
| 14 |
+
# 浏览器驱动路径
|
| 15 |
+
driver_path = "D:\\Software\\edgedriver_win64\\msedgedriver.exe"
|
| 16 |
+
service = Service(driver_path)
|
| 17 |
+
driver = webdriver.Edge(service=service)
|
| 18 |
+
|
| 19 |
+
# 原始 Excel 文件路径和保存路径
|
| 20 |
+
excel_path = r"D:/2/download/symmap-herbname.xlsx"
|
| 21 |
+
save_path = r'D:\2\111数据库\中药化合物对应关系\SymMap\my_project\资料'
|
| 22 |
+
|
| 23 |
+
if not os.path.exists(save_path):
|
| 24 |
+
os.makedirs(save_path)
|
| 25 |
+
|
| 26 |
+
# 读取 Excel 数据
|
| 27 |
+
df_herbs = pd.read_excel(excel_path)
|
| 28 |
+
keys = df_herbs['HerbName'].dropna().unique().tolist()
|
| 29 |
+
|
| 30 |
+
# 断点续跑:读取已存在的文件名
|
| 31 |
+
finished_files = set(os.listdir(save_path))
|
| 32 |
+
finished_keys = set(f.split('+')[0] for f in finished_files if f.endswith('.csv'))
|
| 33 |
+
|
| 34 |
+
# API 配置
|
| 35 |
+
url_search = 'http://www.symmap.org/search/'
|
| 36 |
+
table_name = 'Ingredient'
|
| 37 |
+
|
| 38 |
+
# 记录空中药
|
| 39 |
+
empty_herbs = []
|
| 40 |
+
|
| 41 |
+
def get_herb_id(key, retries=3):
|
| 42 |
+
search_data = {'table_name': 'Herb', 'key': key}
|
| 43 |
+
attempt = 0
|
| 44 |
+
while attempt < retries:
|
| 45 |
+
try:
|
| 46 |
+
response = requests.post(url_search, data=search_data, timeout=30)
|
| 47 |
+
response.raise_for_status()
|
| 48 |
+
print(f"请求中药 {key} 成功")
|
| 49 |
+
search_json = response.json()
|
| 50 |
+
if not search_json.get('data'):
|
| 51 |
+
print(f"{key} 查询失败,没有返回数据")
|
| 52 |
+
return None
|
| 53 |
+
return search_json['data'][0]['Herb_id']
|
| 54 |
+
except Exception as e:
|
| 55 |
+
attempt += 1
|
| 56 |
+
print(f"查询失败: {key}, 错误: {e}, 尝试 {attempt}/{retries}")
|
| 57 |
+
time.sleep(2)
|
| 58 |
+
return None
|
| 59 |
+
|
| 60 |
+
def fetch_ingredient_data(rrid):
|
| 61 |
+
detail_url = f'http://www.symmap.org/detail/{rrid}'
|
| 62 |
+
driver.get(detail_url)
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
ingredient_button = WebDriverWait(driver, 20).until(
|
| 66 |
+
EC.element_to_be_clickable((By.XPATH, "//button[text()='Ingredient']"))
|
| 67 |
+
)
|
| 68 |
+
ingredient_button.click()
|
| 69 |
+
|
| 70 |
+
# 等待表格出现,并且至少有一行数据
|
| 71 |
+
for attempt in range(2): # 最多尝试两次
|
| 72 |
+
try:
|
| 73 |
+
WebDriverWait(driver, 20).until(
|
| 74 |
+
EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'fixed-table-body')]//table"))
|
| 75 |
+
)
|
| 76 |
+
time.sleep(2) # 给一点时间等内容填充
|
| 77 |
+
|
| 78 |
+
table = driver.find_element(By.XPATH, "//div[contains(@class, 'fixed-table-body')]//table")
|
| 79 |
+
rows = table.find_elements(By.XPATH, ".//tbody/tr")
|
| 80 |
+
|
| 81 |
+
if len(rows) > 0:
|
| 82 |
+
break
|
| 83 |
+
else:
|
| 84 |
+
if attempt == 0:
|
| 85 |
+
print("首次打开表格无数据,重点一次Ingredient按钮")
|
| 86 |
+
ingredient_button.click()
|
| 87 |
+
time.sleep(2)
|
| 88 |
+
except Exception as e:
|
| 89 |
+
print(f"等待表格出错: {e}")
|
| 90 |
+
if attempt == 0:
|
| 91 |
+
ingredient_button.click()
|
| 92 |
+
time.sleep(2)
|
| 93 |
+
else:
|
| 94 |
+
return []
|
| 95 |
+
|
| 96 |
+
except Exception as e:
|
| 97 |
+
print(f"Ingredient按钮无法点击: {e}")
|
| 98 |
+
return []
|
| 99 |
+
|
| 100 |
+
ingredients = []
|
| 101 |
+
seen_first_ids = set()
|
| 102 |
+
|
| 103 |
+
while True:
|
| 104 |
+
try:
|
| 105 |
+
table = driver.find_element(By.XPATH, "//div[contains(@class, 'fixed-table-body')]//table")
|
| 106 |
+
rows = table.find_elements(By.XPATH, ".//tbody/tr")
|
| 107 |
+
|
| 108 |
+
page_data = []
|
| 109 |
+
for row in rows:
|
| 110 |
+
cols = row.find_elements(By.TAG_NAME, "td")
|
| 111 |
+
if len(cols) > 1:
|
| 112 |
+
row_data = [col.text.strip() for col in cols]
|
| 113 |
+
page_data.append(row_data)
|
| 114 |
+
|
| 115 |
+
if not page_data:
|
| 116 |
+
break
|
| 117 |
+
|
| 118 |
+
current_ids = set(x[0] for x in page_data)
|
| 119 |
+
if current_ids & seen_first_ids:
|
| 120 |
+
break
|
| 121 |
+
else:
|
| 122 |
+
seen_first_ids.update(current_ids)
|
| 123 |
+
ingredients.extend(page_data)
|
| 124 |
+
|
| 125 |
+
next_btn = driver.find_element(By.XPATH, "//a[@aria-label='next page']")
|
| 126 |
+
if "disabled" in next_btn.get_attribute("class"):
|
| 127 |
+
break
|
| 128 |
+
driver.execute_script("arguments[0].click();", next_btn)
|
| 129 |
+
time.sleep(2)
|
| 130 |
+
except:
|
| 131 |
+
break
|
| 132 |
+
|
| 133 |
+
return ingredients
|
| 134 |
+
|
| 135 |
+
# 主循环
|
| 136 |
+
for key in tqdm(keys, desc="抓取中药成分中"):
|
| 137 |
+
if key in finished_keys:
|
| 138 |
+
print(f"跳过已完成: {key}")
|
| 139 |
+
continue
|
| 140 |
+
|
| 141 |
+
print(f"\n处理: {key}")
|
| 142 |
+
herb_id = get_herb_id(key)
|
| 143 |
+
if not herb_id:
|
| 144 |
+
print(f"未找到中药: {key}")
|
| 145 |
+
continue
|
| 146 |
+
|
| 147 |
+
ingredients = fetch_ingredient_data(herb_id)
|
| 148 |
+
if not ingredients:
|
| 149 |
+
print(f"未获取到成分: {key},保存空表格")
|
| 150 |
+
empty_herbs.append(key)
|
| 151 |
+
# 生成空DataFrame也保存
|
| 152 |
+
df_ingredients = pd.DataFrame(columns=["HerbName"])
|
| 153 |
+
df_ingredients.loc[0] = [key]
|
| 154 |
+
else:
|
| 155 |
+
max_cols = max(len(row) for row in ingredients)
|
| 156 |
+
columns = [f"Column_{i+1}" for i in range(max_cols)]
|
| 157 |
+
cleaned_ingredients = [row[:max_cols] + [''] * (max_cols - len(row)) for row in ingredients]
|
| 158 |
+
df_ingredients = pd.DataFrame(cleaned_ingredients, columns=columns)
|
| 159 |
+
df_ingredients.insert(0, "HerbName", key)
|
| 160 |
+
|
| 161 |
+
output_file = os.path.join(save_path, f'{key}+{table_name}.csv')
|
| 162 |
+
df_ingredients.to_csv(output_file, encoding='gb18030', index=False)
|
| 163 |
+
print(f"完成保存: {key}")
|
| 164 |
+
|
| 165 |
+
# 保存空的中药名字列表
|
| 166 |
+
if empty_herbs:
|
| 167 |
+
empty_path = os.path.join(save_path, "空中药名单.csv")
|
| 168 |
+
pd.DataFrame(empty_herbs, columns=["EmptyHerb"]).to_csv(empty_path, index=False, encoding="utf-8-sig")
|
| 169 |
+
print(f"\n已保存没有成分的中药名单到: {empty_path}")
|
| 170 |
+
|
| 171 |
+
driver.quit()
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/TM-MC/fetch_pubchem_info_by_compounds.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""用于根据 TM-MC 化合物名称或标识从 PubChem 抓取标准化信息。"""
|
| 2 |
+
|
| 3 |
+
# 根据TM-MC的中药-化合物信息从PubChem数据库获取化合物信息
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import pubchempy as pcp
|
| 8 |
+
|
| 9 |
+
ERROR_LOG_FILE = "info_errors.log"
|
| 10 |
+
|
| 11 |
+
def log_error(identifier, message):
|
| 12 |
+
with open(ERROR_LOG_FILE, 'a', encoding='utf-8') as f:
|
| 13 |
+
f.write(f"{identifier}\t{message}\n")
|
| 14 |
+
|
| 15 |
+
def load_failed_ids():
|
| 16 |
+
if not os.path.exists(ERROR_LOG_FILE):
|
| 17 |
+
return set()
|
| 18 |
+
ids = set()
|
| 19 |
+
with open(ERROR_LOG_FILE, 'r', encoding='utf-8') as f:
|
| 20 |
+
for line in f:
|
| 21 |
+
key = line.strip().split('\t')[0]
|
| 22 |
+
ids.add(key)
|
| 23 |
+
return ids
|
| 24 |
+
|
| 25 |
+
def fetch_info_by_identifier(identifier, id_type='cid', max_retries=3, delay=3):
|
| 26 |
+
for attempt in range(max_retries):
|
| 27 |
+
try:
|
| 28 |
+
if id_type == 'cid':
|
| 29 |
+
compound = pcp.Compound.from_cid(identifier)
|
| 30 |
+
else:
|
| 31 |
+
compound = pcp.get_compounds(identifier, id_type)[0]
|
| 32 |
+
|
| 33 |
+
return {
|
| 34 |
+
"PubChem CID": compound.cid or "",
|
| 35 |
+
"Name": compound.iupac_name or "",
|
| 36 |
+
"Molecular Formula": compound.molecular_formula or "",
|
| 37 |
+
"SMILES": compound.canonical_smiles or "",
|
| 38 |
+
"Average Weight": compound.molecular_weight or "",
|
| 39 |
+
"InChI": compound.inchi or "",
|
| 40 |
+
"InChKey": compound.inchikey or "",
|
| 41 |
+
"CAS": "" # 暂无接口支持
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
except Exception as e:
|
| 45 |
+
if attempt < max_retries - 1:
|
| 46 |
+
time.sleep(delay)
|
| 47 |
+
else:
|
| 48 |
+
log_error(f"{id_type}:{identifier}", f"{e}")
|
| 49 |
+
return {
|
| 50 |
+
"PubChem CID": "", "Name": "", "Molecular Formula": "", "SMILES": "",
|
| 51 |
+
"Average Weight": "", "InChI": "", "InChKey": "", "CAS": ""
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
def read_identifiers_from_excel(file_path):
|
| 55 |
+
try:
|
| 56 |
+
df = pd.read_excel(file_path)
|
| 57 |
+
cols = df.columns
|
| 58 |
+
records = []
|
| 59 |
+
|
| 60 |
+
for i, row in df.iterrows():
|
| 61 |
+
identifier = None
|
| 62 |
+
id_type = None
|
| 63 |
+
|
| 64 |
+
# 优先顺序:CID > COMPOUND > InChI > INCHIKEY > SMILES
|
| 65 |
+
if 'CID' in cols and pd.notna(row['CID']):
|
| 66 |
+
cid = str(row['CID']).split('|')[0].strip()
|
| 67 |
+
if cid.isdigit():
|
| 68 |
+
identifier, id_type = cid, 'cid'
|
| 69 |
+
|
| 70 |
+
elif 'COMPOUND' in cols and pd.notna(row['COMPOUND']):
|
| 71 |
+
identifier, id_type = str(row['COMPOUND']).strip(), 'COMPOUND'
|
| 72 |
+
|
| 73 |
+
elif 'InChI' in cols and pd.notna(row['InChI']):
|
| 74 |
+
identifier, id_type = str(row['InChI']).strip(), 'inchi'
|
| 75 |
+
|
| 76 |
+
elif 'INCHIKEY' in cols and pd.notna(row['INCHIKEY']):
|
| 77 |
+
identifier, id_type = str(row['INCHIKEY']).strip(), 'inchikey'
|
| 78 |
+
|
| 79 |
+
elif 'SMILES' in cols and pd.notna(row['SMILES']):
|
| 80 |
+
identifier, id_type = str(row['SMILES']).strip(), 'smiles'
|
| 81 |
+
|
| 82 |
+
if identifier and id_type:
|
| 83 |
+
records.append((identifier, id_type))
|
| 84 |
+
|
| 85 |
+
return records
|
| 86 |
+
|
| 87 |
+
except Exception as e:
|
| 88 |
+
print(f"❌ 无法读取文件 {file_path}:{e}")
|
| 89 |
+
return []
|
| 90 |
+
|
| 91 |
+
def process_excel_file(input_file, output_dir, failed_only=False):
|
| 92 |
+
output_name = os.path.splitext(os.path.basename(input_file))[0]
|
| 93 |
+
output_file = os.path.join(output_dir, f"{output_name}.xlsx")
|
| 94 |
+
|
| 95 |
+
if os.path.exists(output_file) and not failed_only:
|
| 96 |
+
print(f"⏭ 已处理过,跳过:{output_name}")
|
| 97 |
+
return
|
| 98 |
+
|
| 99 |
+
id_list = read_identifiers_from_excel(input_file)
|
| 100 |
+
if not id_list:
|
| 101 |
+
return
|
| 102 |
+
|
| 103 |
+
print(f"\n🔍 正在处理文件:{output_name}(共 {len(id_list)} 项)")
|
| 104 |
+
|
| 105 |
+
failed_ids = load_failed_ids() if failed_only else set()
|
| 106 |
+
all_data = []
|
| 107 |
+
|
| 108 |
+
for identifier, id_type in id_list:
|
| 109 |
+
if failed_only and f"{id_type}:{identifier}" not in failed_ids:
|
| 110 |
+
continue
|
| 111 |
+
info = fetch_info_by_identifier(identifier, id_type)
|
| 112 |
+
all_data.append(info)
|
| 113 |
+
time.sleep(0.5)
|
| 114 |
+
|
| 115 |
+
if all_data:
|
| 116 |
+
df = pd.DataFrame(all_data)
|
| 117 |
+
df.to_excel(output_file, index=False)
|
| 118 |
+
print(f"✅ 信息表保存:{output_file}")
|
| 119 |
+
else:
|
| 120 |
+
print(f"⚠ 没有抓取任何信息,未生成表格:{output_name}")
|
| 121 |
+
|
| 122 |
+
def main():
|
| 123 |
+
input_dir = r"D:\2\111数据库\中药化合物对应关系\TM-MC"
|
| 124 |
+
output_dir = r"D:\2\111数据库\数据库-化合物\TM-MC_Info"
|
| 125 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 126 |
+
|
| 127 |
+
print("✨ 支持多种标识符检索 + 断点续跑 + 错误重试")
|
| 128 |
+
|
| 129 |
+
for file in sorted(os.listdir(input_dir)):
|
| 130 |
+
if file.endswith(".xlsx"):
|
| 131 |
+
process_excel_file(os.path.join(input_dir, file), output_dir)
|
| 132 |
+
|
| 133 |
+
if os.path.exists(ERROR_LOG_FILE):
|
| 134 |
+
print("\n🔁 正在重试失败的项...")
|
| 135 |
+
backup_file = "info_errors_backup.log"
|
| 136 |
+
if os.path.exists(backup_file):
|
| 137 |
+
timestamp = time.strftime("%Y%m%d_%H%M%S")
|
| 138 |
+
new_backup_file = f"info_errors_backup_{timestamp}.log"
|
| 139 |
+
os.rename(backup_file, new_backup_file)
|
| 140 |
+
print(f"📦 已存在备份文件,重命名为:{new_backup_file}")
|
| 141 |
+
os.rename(ERROR_LOG_FILE, backup_file)
|
| 142 |
+
for file in sorted(os.listdir(input_dir)):
|
| 143 |
+
if file.endswith(".xlsx"):
|
| 144 |
+
process_excel_file(os.path.join(input_dir, file), output_dir, failed_only=True)
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
main()
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/collectors/TM-MC/split_herb_compounds.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""用于将数据库中的中药-化合物关系拆分或整理为逐味中药文件。"""
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import os
|
| 5 |
+
from collections import Counter
|
| 6 |
+
|
| 7 |
+
# ===== 路径设置 =====
|
| 8 |
+
herb_path = r"D:\2\111数据库\数据库download\TM-MC\herb_TM-MC.xlsx"
|
| 9 |
+
compound_path = r"D:\2\111数据库\数据库download\TM-MC\TM-MC_in.xlsx"
|
| 10 |
+
relation_path = r"D:\2\111数据库\数据库download\TM-MC\TM-MC关系表.xlsx"
|
| 11 |
+
output_dir = r"D:\2\111数据库\中药化合物对应关系\TM-MC"
|
| 12 |
+
|
| 13 |
+
# ===== 创建输出文件夹 =====
|
| 14 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 15 |
+
|
| 16 |
+
# ===== 读取数据 =====
|
| 17 |
+
herbs = pd.read_excel(herb_path)
|
| 18 |
+
compounds = pd.read_excel(compound_path)
|
| 19 |
+
relations = pd.read_excel(relation_path)
|
| 20 |
+
|
| 21 |
+
# ===== 标准化字段名(便于 merge) =====
|
| 22 |
+
herbs = herbs.rename(columns={"LATIN": "Herb_Latin", "CHINESE": "Herb_Chinese"})
|
| 23 |
+
relations = relations.rename(columns={"LATIN": "Herb_Latin", "ID": "Compound_ID"})
|
| 24 |
+
compounds = compounds.rename(columns={"ID": "Compound_ID"})
|
| 25 |
+
|
| 26 |
+
# ===== 合并中药中文名 =====
|
| 27 |
+
merged = relations.merge(herbs[["Herb_Latin", "Herb_Chinese"]], on="Herb_Latin", how="left")
|
| 28 |
+
|
| 29 |
+
# 保留CHINESE缺失的中药,命名为"Unknown"
|
| 30 |
+
merged['Herb_Chinese'] = merged['Herb_Chinese'].fillna("Unknown")
|
| 31 |
+
|
| 32 |
+
# ===== 合并化合物信息 =====
|
| 33 |
+
merged = merged.merge(compounds, on="Compound_ID", how="left")
|
| 34 |
+
|
| 35 |
+
# ===== 警告提示 =====
|
| 36 |
+
if merged["Herb_Chinese"].isnull().any():
|
| 37 |
+
print("⚠️ 存在在关系表中找不到对应中文名的中药 LATIN。")
|
| 38 |
+
if merged.isnull().any(axis=1).sum():
|
| 39 |
+
print("⚠️ 存在在关系表中找不到化合物详细信息的 Compound_ID。")
|
| 40 |
+
|
| 41 |
+
# ===== 分表并导出 =====
|
| 42 |
+
filename_counter = Counter()
|
| 43 |
+
grouped = merged.groupby(["Herb_Chinese", "Herb_Latin"])
|
| 44 |
+
saved_count = 0
|
| 45 |
+
|
| 46 |
+
for (chinese, latin), group in grouped:
|
| 47 |
+
# LATIN 为必填字段,跳过 LATIN 缺失的记录
|
| 48 |
+
if pd.isna(latin) or str(latin).strip() == "":
|
| 49 |
+
print(f"⚠️ 跳过无效分组(LATIN 为空):CHINESE={chinese}")
|
| 50 |
+
continue
|
| 51 |
+
|
| 52 |
+
# 文件名清洗函数
|
| 53 |
+
def safe_filename(name):
|
| 54 |
+
return ''.join(c if c.isalnum() or c in (' ', '_', '-') else '_' for c in str(name)).strip()
|
| 55 |
+
|
| 56 |
+
# CHINESE 允许为空,此时用占位符命名文件
|
| 57 |
+
safe_chinese = safe_filename(chinese) if pd.notna(chinese) and str(chinese).strip() else 'unknown'
|
| 58 |
+
safe_latin = safe_filename(latin)
|
| 59 |
+
|
| 60 |
+
filename = f"{safe_chinese}_{safe_latin}.xlsx"
|
| 61 |
+
output_path = os.path.join(output_dir, filename)
|
| 62 |
+
|
| 63 |
+
filename_counter[filename] += 1
|
| 64 |
+
if filename_counter[filename] > 1:
|
| 65 |
+
print(f"⚠️ 文件名重复:{filename},第 {filename_counter[filename]} 次出现,可能覆盖")
|
| 66 |
+
|
| 67 |
+
# 尝试写入
|
| 68 |
+
try:
|
| 69 |
+
group.to_excel(output_path, index=False)
|
| 70 |
+
saved_count += 1
|
| 71 |
+
except Exception as e:
|
| 72 |
+
print(f"❌ 保存失败:{filename},原因:{e}")
|
| 73 |
+
|
| 74 |
+
# ===== 精确统计 =====
|
| 75 |
+
print("\n📊 数据处理统计:")
|
| 76 |
+
print(f"总中药数(herb表):{herbs['Herb_Latin'].nunique()}")
|
| 77 |
+
print(f"关系表中中药数 :{relations['Herb_Latin'].nunique()}")
|
| 78 |
+
xlsx_files = [f for f in os.listdir(output_dir) if f.endswith('.xlsx') and not f.startswith('~$')]
|
| 79 |
+
print(f"成功导出的文件数 :{len(xlsx_files)}(实际保存:{saved_count})")
|
| 80 |
+
|
| 81 |
+
# ===== 补充信息 =====
|
| 82 |
+
unmatched_herbs = relations[~relations['Herb_Latin'].isin(herbs['Herb_Latin'])]
|
| 83 |
+
if not unmatched_herbs.empty:
|
| 84 |
+
print(f"\n🔍 有 {unmatched_herbs['Herb_Latin'].nunique()} 个 LATIN 未能匹配到 herb 表中的中药:")
|
| 85 |
+
print(unmatched_herbs['Herb_Latin'].drop_duplicates().head())
|
| 86 |
+
else:
|
| 87 |
+
print("\n✅ 所有关系表中的中药均成功匹配到 herb 表。")
|
| 88 |
+
|
| 89 |
+
# ===== 找出未出现在关系表中的中药(按 LATIN 匹配) =====
|
| 90 |
+
unmatched_herbs = herbs[~herbs['Herb_Latin'].isin(relations['Herb_Latin'])]
|
| 91 |
+
|
| 92 |
+
if not unmatched_herbs.empty:
|
| 93 |
+
unmatched_path = os.path.join(output_dir, "未匹配中药列表.xlsx")
|
| 94 |
+
unmatched_herbs.to_excel(unmatched_path, index=False)
|
| 95 |
+
|
| 96 |
+
print(f"\n📄 共发现 {len(unmatched_herbs)} 个中药未出现在关系表中,已保存至:{unmatched_path}")
|
| 97 |
+
print("📌 示例条目:")
|
| 98 |
+
print(unmatched_herbs[['Herb_Chinese', 'Herb_Latin']].head())
|
| 99 |
+
else:
|
| 100 |
+
print("\n✅ 所有中药均出现在关系表中,无遗漏。")
|
| 101 |
+
|
| 102 |
+
# 额外输出每组条目数(用于确认分组去重情况)
|
| 103 |
+
group_keys = merged.groupby(["Herb_Chinese", "Herb_Latin"]).size().reset_index(name='Count')
|
| 104 |
+
group_keys_path = os.path.join(output_dir, "中药_分组统计.xlsx")
|
| 105 |
+
group_keys.to_excel(group_keys_path, index=False)
|
| 106 |
+
print(f"\n📄 已输出分组统计文件,用于分析导出文件数少于 LATIN 数的原因:{group_keys_path}")
|
| 107 |
+
|
| 108 |
+
# ===== 找出未出现在关系表中的中药(按 LATIN 匹配) =====
|
| 109 |
+
missing_in_relations = herbs[~herbs['Herb_Latin'].isin(relations['Herb_Latin'])]
|
| 110 |
+
|
| 111 |
+
if not missing_in_relations.empty:
|
| 112 |
+
unmatched_path = os.path.join(output_dir, "herb表中存在但关系表中缺失的中药列表.xlsx")
|
| 113 |
+
missing_in_relations.to_excel(unmatched_path, index=False)
|
| 114 |
+
print(f"\n📌 共 {len(missing_in_relations)} 个中药存在于 herb 表中,但未出现在关系表中。已保存至:{unmatched_path}")
|
| 115 |
+
print("📌 示例:")
|
| 116 |
+
print(missing_in_relations[['Herb_Chinese', 'Herb_Latin']].head())
|
| 117 |
+
else:
|
| 118 |
+
print("\n✅ 所有 herb 表中的中药都在关系表中有对应关系。")
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/data/backfill_herb2_from_source.py
ADDED
|
@@ -0,0 +1,486 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""用于从 HERB 原始来源缓存回填并整理 HERB2 结果数据。"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import shutil
|
| 8 |
+
import time
|
| 9 |
+
import urllib.error
|
| 10 |
+
import urllib.request
|
| 11 |
+
from collections import Counter, defaultdict
|
| 12 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import Any
|
| 15 |
+
|
| 16 |
+
import pandas as pd
|
| 17 |
+
|
| 18 |
+
from build_tcm_libraries import normalize_cas, normalize_inchi, normalize_inchikey, normalize_pubchem, normalize_space, split_aliases, standardize_text_key
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 22 |
+
HERB2_DIR = BASE_DIR / "原始数据汇总" / "HERB2"
|
| 23 |
+
INPUT_XLSX = HERB2_DIR / "HERB2_Info_汇总_with_herbid_with_cid.xlsx"
|
| 24 |
+
BACKUP_XLSX = HERB2_DIR / "HERB2_Info_汇总_with_herbid_with_cid.before_source_backfill.xlsx"
|
| 25 |
+
REPORT_JSON = HERB2_DIR / "HERB2_source_backfill_report.json"
|
| 26 |
+
REPORT_CSV = HERB2_DIR / "HERB2_source_backfill_rows.csv"
|
| 27 |
+
CACHE_DIR = HERB2_DIR / ".herb2_source_cache"
|
| 28 |
+
API_URL = "http://47.92.70.12/chedi/api/?"
|
| 29 |
+
|
| 30 |
+
TARGET_FIELDS = [
|
| 31 |
+
"pubchemcid",
|
| 32 |
+
"iupacname",
|
| 33 |
+
"molecularformula",
|
| 34 |
+
"smiles",
|
| 35 |
+
"averageweight",
|
| 36 |
+
"inchi",
|
| 37 |
+
"inchkey",
|
| 38 |
+
"cas",
|
| 39 |
+
]
|
| 40 |
+
REPORT_COLUMNS = [
|
| 41 |
+
"herbid",
|
| 42 |
+
"queriedname",
|
| 43 |
+
"herb2ingredientid",
|
| 44 |
+
"sourceingredientname",
|
| 45 |
+
"sourceingredientalias",
|
| 46 |
+
"sourcepubchemname",
|
| 47 |
+
"sourcebackfillmatchtype",
|
| 48 |
+
"sourcebackfillstatus",
|
| 49 |
+
*TARGET_FIELDS,
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def parse_args() -> argparse.Namespace:
|
| 54 |
+
parser = argparse.ArgumentParser(description="Backfill HERB2 name-only rows from the source site.")
|
| 55 |
+
parser.add_argument("--input", type=Path, default=INPUT_XLSX)
|
| 56 |
+
parser.add_argument("--workers", type=int, default=8)
|
| 57 |
+
parser.add_argument("--timeout", type=float, default=30.0)
|
| 58 |
+
parser.add_argument("--no-overwrite", action="store_true", help="Write only report columns in memory without saving back to the input workbook.")
|
| 59 |
+
parser.add_argument("--force-refresh-cache", action="store_true")
|
| 60 |
+
return parser.parse_args()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def ensure_report_columns(df: pd.DataFrame) -> pd.DataFrame:
|
| 64 |
+
for col in REPORT_COLUMNS:
|
| 65 |
+
if col not in df.columns:
|
| 66 |
+
df[col] = ""
|
| 67 |
+
return df
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def row_needs_backfill(row: pd.Series) -> bool:
|
| 71 |
+
if normalize_space(row.get("queriedname", "")) == "":
|
| 72 |
+
return False
|
| 73 |
+
return all(normalize_space(row.get(col, "")) == "" for col in TARGET_FIELDS)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def request_json(payload: dict[str, Any], timeout: float, retries: int = 3) -> dict[str, Any]:
|
| 77 |
+
data = json.dumps(payload).encode("utf-8")
|
| 78 |
+
req = urllib.request.Request(
|
| 79 |
+
API_URL,
|
| 80 |
+
data=data,
|
| 81 |
+
headers={
|
| 82 |
+
"Content-Type": "application/json",
|
| 83 |
+
"Accept": "application/json",
|
| 84 |
+
},
|
| 85 |
+
)
|
| 86 |
+
last_error: Exception | None = None
|
| 87 |
+
for attempt in range(retries):
|
| 88 |
+
try:
|
| 89 |
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
| 90 |
+
return json.loads(resp.read().decode("utf-8"))
|
| 91 |
+
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
|
| 92 |
+
last_error = exc
|
| 93 |
+
if attempt + 1 < retries:
|
| 94 |
+
time.sleep(0.4 * (attempt + 1))
|
| 95 |
+
raise RuntimeError(f"request failed after {retries} attempts: {payload}") from last_error
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def load_cache(cache_file: Path) -> dict[str, Any] | None:
|
| 99 |
+
if not cache_file.exists():
|
| 100 |
+
return None
|
| 101 |
+
try:
|
| 102 |
+
return json.loads(cache_file.read_text(encoding="utf-8"))
|
| 103 |
+
except Exception:
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def save_cache(cache_file: Path, data: dict[str, Any]) -> None:
|
| 108 |
+
cache_file.parent.mkdir(parents=True, exist_ok=True)
|
| 109 |
+
cache_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def cached_request(
|
| 113 |
+
cache_file: Path,
|
| 114 |
+
payload: dict[str, Any],
|
| 115 |
+
timeout: float,
|
| 116 |
+
force_refresh: bool,
|
| 117 |
+
) -> dict[str, Any]:
|
| 118 |
+
if not force_refresh:
|
| 119 |
+
cached = load_cache(cache_file)
|
| 120 |
+
if cached is not None:
|
| 121 |
+
return cached
|
| 122 |
+
data = request_json(payload, timeout=timeout)
|
| 123 |
+
save_cache(cache_file, data)
|
| 124 |
+
return data
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def extract_link_title(value: Any) -> str:
|
| 128 |
+
if isinstance(value, dict):
|
| 129 |
+
value = value.get("title", "")
|
| 130 |
+
text = normalize_space(value)
|
| 131 |
+
return "" if text.upper() == "NA" else text
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def to_value(value: Any) -> str:
|
| 135 |
+
return extract_link_title(value)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def ingredient_summary_map(detail: dict[str, Any]) -> dict[str, Any]:
|
| 139 |
+
summary = detail.get("summary", [])
|
| 140 |
+
if not isinstance(summary, list) or len(summary) < 2:
|
| 141 |
+
return {}
|
| 142 |
+
headers = [normalize_space(v) for v in summary[0]]
|
| 143 |
+
values = summary[1]
|
| 144 |
+
return {header: value for header, value in zip(headers, values)}
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def build_match_indices(ingredient_rows: list[dict[str, str]]) -> tuple[dict[str, list[int]], dict[str, list[int]]]:
|
| 148 |
+
exact_index: dict[str, list[int]] = defaultdict(list)
|
| 149 |
+
text_index: dict[str, list[int]] = defaultdict(list)
|
| 150 |
+
for idx, row in enumerate(ingredient_rows):
|
| 151 |
+
name = normalize_space(row.get("ingredient_name", ""))
|
| 152 |
+
alias = normalize_space(row.get("ingredient_alias", ""))
|
| 153 |
+
formula = normalize_space(row.get("molecular_formula", ""))
|
| 154 |
+
smiles = normalize_space(row.get("canonical_smiles", ""))
|
| 155 |
+
raw_keys = [name, formula, smiles, *split_aliases(alias)]
|
| 156 |
+
for key in raw_keys:
|
| 157 |
+
key = normalize_space(key)
|
| 158 |
+
if key:
|
| 159 |
+
exact_index[key].append(idx)
|
| 160 |
+
text_key = standardize_text_key(key)
|
| 161 |
+
if text_key:
|
| 162 |
+
text_index[text_key].append(idx)
|
| 163 |
+
return exact_index, text_index
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def guess_name_type(value: str) -> str:
|
| 167 |
+
text = normalize_space(value)
|
| 168 |
+
if not text:
|
| 169 |
+
return "blank"
|
| 170 |
+
if all(ch.isalnum() or ch in ".+-" for ch in text) and any(ch.isdigit() for ch in text):
|
| 171 |
+
if "-" in text and text.count("-") == 2:
|
| 172 |
+
return "registry_or_db_id"
|
| 173 |
+
if text.startswith("InChI="):
|
| 174 |
+
return "registry_or_db_id"
|
| 175 |
+
if any(ch in text for ch in "[]()=#@\\/"):
|
| 176 |
+
return "smiles_like"
|
| 177 |
+
upper = text.upper()
|
| 178 |
+
if any(ch.isdigit() for ch in upper) and all(ch.isalpha() or ch.isdigit() for ch in upper):
|
| 179 |
+
return "molecular_formula"
|
| 180 |
+
return "chemical_name"
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def choose_match(
|
| 184 |
+
queried_name: str,
|
| 185 |
+
ingredient_rows: list[dict[str, str]],
|
| 186 |
+
exact_index: dict[str, list[int]],
|
| 187 |
+
text_index: dict[str, list[int]],
|
| 188 |
+
) -> tuple[dict[str, str] | None, str]:
|
| 189 |
+
name_type = guess_name_type(queried_name)
|
| 190 |
+
exact_key = normalize_space(queried_name)
|
| 191 |
+
text_key = standardize_text_key(queried_name)
|
| 192 |
+
|
| 193 |
+
candidate_orders = {
|
| 194 |
+
"molecular_formula": [("exact_formula", lambda r: normalize_space(r["molecular_formula"]) == exact_key),
|
| 195 |
+
("exact_alias", lambda r: exact_key in split_aliases(r["ingredient_alias"])),
|
| 196 |
+
("fold_formula", lambda r: standardize_text_key(r["molecular_formula"]) == text_key)],
|
| 197 |
+
"smiles_like": [("exact_smiles", lambda r: normalize_space(r["canonical_smiles"]) == exact_key),
|
| 198 |
+
("fold_smiles", lambda r: standardize_text_key(r["canonical_smiles"]) == text_key),
|
| 199 |
+
("exact_alias", lambda r: exact_key in split_aliases(r["ingredient_alias"]))],
|
| 200 |
+
"registry_or_db_id": [("exact_alias", lambda r: exact_key in split_aliases(r["ingredient_alias"])),
|
| 201 |
+
("fold_alias", lambda r: text_key in {standardize_text_key(v) for v in split_aliases(r["ingredient_alias"])}),
|
| 202 |
+
("exact_name", lambda r: normalize_space(r["ingredient_name"]) == exact_key)],
|
| 203 |
+
"chemical_name": [("exact_name", lambda r: normalize_space(r["ingredient_name"]) == exact_key),
|
| 204 |
+
("fold_name", lambda r: standardize_text_key(r["ingredient_name"]) == text_key),
|
| 205 |
+
("exact_alias", lambda r: exact_key in split_aliases(r["ingredient_alias"])),
|
| 206 |
+
("fold_alias", lambda r: text_key in {standardize_text_key(v) for v in split_aliases(r["ingredient_alias"])}),
|
| 207 |
+
("exact_formula", lambda r: normalize_space(r["molecular_formula"]) == exact_key),
|
| 208 |
+
("exact_smiles", lambda r: normalize_space(r["canonical_smiles"]) == exact_key)],
|
| 209 |
+
}
|
| 210 |
+
checks = candidate_orders.get(name_type, candidate_orders["chemical_name"])
|
| 211 |
+
|
| 212 |
+
for match_type, predicate in checks:
|
| 213 |
+
matches = [row for row in ingredient_rows if predicate(row)]
|
| 214 |
+
if len(matches) == 1:
|
| 215 |
+
return matches[0], match_type
|
| 216 |
+
if len(matches) > 1:
|
| 217 |
+
return None, f"ambiguous_{match_type}"
|
| 218 |
+
|
| 219 |
+
# Fast unique lookup fallback when the direct checks all fail.
|
| 220 |
+
if exact_key and len(exact_index.get(exact_key, [])) == 1:
|
| 221 |
+
return ingredient_rows[exact_index[exact_key][0]], "exact_any"
|
| 222 |
+
if text_key and len(text_index.get(text_key, [])) == 1:
|
| 223 |
+
return ingredient_rows[text_index[text_key][0]], "fold_any"
|
| 224 |
+
return None, "not_found"
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def parse_herb_ingredient_rows(detail: dict[str, Any]) -> list[dict[str, str]]:
|
| 228 |
+
table = detail.get("herb_ingredient", [])
|
| 229 |
+
if not isinstance(table, list) or len(table) < 2:
|
| 230 |
+
return []
|
| 231 |
+
rows = []
|
| 232 |
+
for raw_row in table[1:]:
|
| 233 |
+
if not isinstance(raw_row, list) or len(raw_row) < 5:
|
| 234 |
+
continue
|
| 235 |
+
ingredient_id = extract_link_title(raw_row[0])
|
| 236 |
+
rows.append(
|
| 237 |
+
{
|
| 238 |
+
"ingredient_id": ingredient_id,
|
| 239 |
+
"ingredient_name": to_value(raw_row[1]),
|
| 240 |
+
"ingredient_alias": to_value(raw_row[2]),
|
| 241 |
+
"molecular_formula": to_value(raw_row[3]),
|
| 242 |
+
"canonical_smiles": to_value(raw_row[4]),
|
| 243 |
+
}
|
| 244 |
+
)
|
| 245 |
+
return rows
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def fetch_herb_detail(herb_id: str, timeout: float, force_refresh: bool) -> dict[str, Any]:
|
| 249 |
+
cache_file = CACHE_DIR / "herb_detail" / f"{herb_id}.json"
|
| 250 |
+
payload = {
|
| 251 |
+
"func_name": "detail_api",
|
| 252 |
+
"v": herb_id,
|
| 253 |
+
"label": "Herb",
|
| 254 |
+
"key_id": herb_id,
|
| 255 |
+
}
|
| 256 |
+
return cached_request(cache_file, payload, timeout, force_refresh)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def fetch_ingredient_detail(ingredient_id: str, timeout: float, force_refresh: bool) -> dict[str, Any]:
|
| 260 |
+
cache_file = CACHE_DIR / "ingredient_detail" / f"{ingredient_id}.json"
|
| 261 |
+
payload = {
|
| 262 |
+
"func_name": "detail_api",
|
| 263 |
+
"v": ingredient_id,
|
| 264 |
+
"label": "Ingredient",
|
| 265 |
+
"key_id": ingredient_id,
|
| 266 |
+
}
|
| 267 |
+
return cached_request(cache_file, payload, timeout, force_refresh)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def collect_herb_matches(
|
| 271 |
+
df: pd.DataFrame,
|
| 272 |
+
timeout: float,
|
| 273 |
+
workers: int,
|
| 274 |
+
force_refresh: bool,
|
| 275 |
+
) -> tuple[dict[int, dict[str, str]], Counter]:
|
| 276 |
+
candidate = df[df.apply(row_needs_backfill, axis=1)].copy()
|
| 277 |
+
grouped = candidate.groupby("herbid").groups
|
| 278 |
+
match_by_row: dict[int, dict[str, str]] = {}
|
| 279 |
+
stats = Counter()
|
| 280 |
+
|
| 281 |
+
def process_herb(herb_id: str, row_indices: list[int]) -> tuple[str, list[tuple[int, dict[str, str]]] | None, str]:
|
| 282 |
+
if not herb_id:
|
| 283 |
+
return herb_id, None, "missing_herb_id"
|
| 284 |
+
try:
|
| 285 |
+
detail = fetch_herb_detail(herb_id, timeout, force_refresh)
|
| 286 |
+
except Exception as exc:
|
| 287 |
+
return herb_id, None, f"herb_detail_error:{type(exc).__name__}"
|
| 288 |
+
ingredient_rows = parse_herb_ingredient_rows(detail)
|
| 289 |
+
if not ingredient_rows:
|
| 290 |
+
return herb_id, None, "no_herb_ingredient_rows"
|
| 291 |
+
exact_index, text_index = build_match_indices(ingredient_rows)
|
| 292 |
+
row_matches: list[tuple[int, dict[str, str]]] = []
|
| 293 |
+
for row_idx in row_indices:
|
| 294 |
+
queried_name = normalize_space(df.at[row_idx, "queriedname"])
|
| 295 |
+
matched_row, match_type = choose_match(queried_name, ingredient_rows, exact_index, text_index)
|
| 296 |
+
if matched_row is None:
|
| 297 |
+
row_matches.append(
|
| 298 |
+
(
|
| 299 |
+
row_idx,
|
| 300 |
+
{
|
| 301 |
+
"sourcebackfillstatus": match_type,
|
| 302 |
+
},
|
| 303 |
+
)
|
| 304 |
+
)
|
| 305 |
+
continue
|
| 306 |
+
row_matches.append(
|
| 307 |
+
(
|
| 308 |
+
row_idx,
|
| 309 |
+
{
|
| 310 |
+
"herb2ingredientid": matched_row["ingredient_id"],
|
| 311 |
+
"sourceingredientname": matched_row["ingredient_name"],
|
| 312 |
+
"sourceingredientalias": matched_row["ingredient_alias"],
|
| 313 |
+
"sourcebackfillmatchtype": match_type,
|
| 314 |
+
"sourcebackfillstatus": "matched_herb_detail",
|
| 315 |
+
"molecularformula": matched_row["molecular_formula"],
|
| 316 |
+
"smiles": matched_row["canonical_smiles"],
|
| 317 |
+
},
|
| 318 |
+
)
|
| 319 |
+
)
|
| 320 |
+
return herb_id, row_matches, "ok"
|
| 321 |
+
|
| 322 |
+
with ThreadPoolExecutor(max_workers=workers) as executor:
|
| 323 |
+
futures = {
|
| 324 |
+
executor.submit(process_herb, herb_id, list(row_indices)): herb_id
|
| 325 |
+
for herb_id, row_indices in grouped.items()
|
| 326 |
+
}
|
| 327 |
+
for future in as_completed(futures):
|
| 328 |
+
herb_id, row_matches, status = future.result()
|
| 329 |
+
stats[status] += 1
|
| 330 |
+
if not row_matches:
|
| 331 |
+
continue
|
| 332 |
+
for row_idx, payload in row_matches:
|
| 333 |
+
match_by_row[row_idx] = payload
|
| 334 |
+
stats[payload.get("sourcebackfillstatus", "")] += 1
|
| 335 |
+
return match_by_row, stats
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def fill_from_ingredient_detail(
|
| 339 |
+
df: pd.DataFrame,
|
| 340 |
+
timeout: float,
|
| 341 |
+
workers: int,
|
| 342 |
+
force_refresh: bool,
|
| 343 |
+
) -> Counter:
|
| 344 |
+
ingredient_ids = sorted(
|
| 345 |
+
{
|
| 346 |
+
normalize_space(value)
|
| 347 |
+
for value in df.loc[df["herb2ingredientid"] != "", "herb2ingredientid"].tolist()
|
| 348 |
+
if normalize_space(value)
|
| 349 |
+
}
|
| 350 |
+
)
|
| 351 |
+
stats = Counter()
|
| 352 |
+
summary_map_by_id: dict[str, dict[str, Any]] = {}
|
| 353 |
+
|
| 354 |
+
def process_ingredient(ingredient_id: str) -> tuple[str, dict[str, Any] | None, str]:
|
| 355 |
+
try:
|
| 356 |
+
detail = fetch_ingredient_detail(ingredient_id, timeout, force_refresh)
|
| 357 |
+
except Exception as exc:
|
| 358 |
+
return ingredient_id, None, f"ingredient_detail_error:{type(exc).__name__}"
|
| 359 |
+
summary_map = ingredient_summary_map(detail)
|
| 360 |
+
if not summary_map:
|
| 361 |
+
return ingredient_id, None, "missing_summary"
|
| 362 |
+
return ingredient_id, summary_map, "ok"
|
| 363 |
+
|
| 364 |
+
with ThreadPoolExecutor(max_workers=workers) as executor:
|
| 365 |
+
futures = {executor.submit(process_ingredient, ingredient_id): ingredient_id for ingredient_id in ingredient_ids}
|
| 366 |
+
for future in as_completed(futures):
|
| 367 |
+
ingredient_id, summary_map, status = future.result()
|
| 368 |
+
stats[status] += 1
|
| 369 |
+
if summary_map is not None:
|
| 370 |
+
summary_map_by_id[ingredient_id] = summary_map
|
| 371 |
+
|
| 372 |
+
for row_idx, row in df.iterrows():
|
| 373 |
+
ingredient_id = normalize_space(row.get("herb2ingredientid", ""))
|
| 374 |
+
if not ingredient_id:
|
| 375 |
+
continue
|
| 376 |
+
summary_map = summary_map_by_id.get(ingredient_id)
|
| 377 |
+
if not summary_map:
|
| 378 |
+
continue
|
| 379 |
+
|
| 380 |
+
pubchem_name = to_value(summary_map.get("PubChem name", ""))
|
| 381 |
+
ingredient_name = normalize_space(row.get("sourceingredientname", ""))
|
| 382 |
+
fallback_name = next((value for value in [to_value(summary_map.get("IUPAC Name", "")), pubchem_name, ingredient_name] if value and value != "NA"), "")
|
| 383 |
+
|
| 384 |
+
pubchem = extract_link_title(summary_map.get("PubChem", ""))
|
| 385 |
+
formula = to_value(summary_map.get("Molecular Formula", ""))
|
| 386 |
+
canonical_smiles = to_value(summary_map.get("Canonical SMILES", ""))
|
| 387 |
+
average_weight = to_value(summary_map.get("The average molecular weight", ""))
|
| 388 |
+
inchi = to_value(summary_map.get("InChI", ""))
|
| 389 |
+
inchikey = to_value(summary_map.get("InChIKey", ""))
|
| 390 |
+
cas = to_value(summary_map.get("CAS", ""))
|
| 391 |
+
|
| 392 |
+
updates = {
|
| 393 |
+
"pubchemcid": normalize_pubchem(pubchem),
|
| 394 |
+
"iupacname": fallback_name,
|
| 395 |
+
"molecularformula": formula if formula != "NA" else normalize_space(row.get("molecularformula", "")),
|
| 396 |
+
"smiles": canonical_smiles if canonical_smiles != "NA" else normalize_space(row.get("smiles", "")),
|
| 397 |
+
"averageweight": "" if average_weight == "NA" else average_weight,
|
| 398 |
+
"inchi": "" if inchi == "NA" else normalize_inchi(inchi),
|
| 399 |
+
"inchkey": "" if inchikey == "NA" else normalize_inchikey(inchikey),
|
| 400 |
+
"cas": "" if cas == "NA" else normalize_cas(cas),
|
| 401 |
+
"sourcepubchemname": "" if pubchem_name == "NA" else pubchem_name,
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
# Fall back to the herb-level formula / smiles if the ingredient summary is sparse.
|
| 405 |
+
if not updates["molecularformula"]:
|
| 406 |
+
updates["molecularformula"] = normalize_space(row.get("molecularformula", ""))
|
| 407 |
+
if not updates["smiles"]:
|
| 408 |
+
updates["smiles"] = normalize_space(row.get("smiles", ""))
|
| 409 |
+
|
| 410 |
+
filled_any = False
|
| 411 |
+
for field, value in updates.items():
|
| 412 |
+
if field in df.columns and normalize_space(df.at[row_idx, field]) == "" and normalize_space(value) != "":
|
| 413 |
+
df.at[row_idx, field] = value
|
| 414 |
+
filled_any = True
|
| 415 |
+
if filled_any:
|
| 416 |
+
df.at[row_idx, "sourcebackfillstatus"] = "filled_ingredient_detail"
|
| 417 |
+
stats["rows_filled"] += 1
|
| 418 |
+
else:
|
| 419 |
+
if normalize_space(df.at[row_idx, "sourcebackfillstatus"]) == "":
|
| 420 |
+
df.at[row_idx, "sourcebackfillstatus"] = "matched_no_new_fields"
|
| 421 |
+
stats["rows_without_new_fields"] += 1
|
| 422 |
+
return stats
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def main() -> None:
|
| 426 |
+
args = parse_args()
|
| 427 |
+
df = pd.read_excel(args.input, dtype=str, engine="openpyxl").fillna("")
|
| 428 |
+
df = ensure_report_columns(df)
|
| 429 |
+
|
| 430 |
+
candidate_mask = df.apply(row_needs_backfill, axis=1)
|
| 431 |
+
candidate_rows = int(candidate_mask.sum())
|
| 432 |
+
print(f"candidate_rows={candidate_rows}")
|
| 433 |
+
print(f"unique_herbs={df.loc[candidate_mask, 'herbid'].replace('', pd.NA).dropna().nunique()}")
|
| 434 |
+
|
| 435 |
+
herb_matches, herb_stats = collect_herb_matches(
|
| 436 |
+
df=df,
|
| 437 |
+
timeout=args.timeout,
|
| 438 |
+
workers=args.workers,
|
| 439 |
+
force_refresh=args.force_refresh_cache,
|
| 440 |
+
)
|
| 441 |
+
print(f"herb_match_rows={len(herb_matches)}")
|
| 442 |
+
print(f"herb_stats={json.dumps(dict(herb_stats), ensure_ascii=False)}")
|
| 443 |
+
for row_idx, payload in herb_matches.items():
|
| 444 |
+
for field, value in payload.items():
|
| 445 |
+
if field in df.columns and normalize_space(df.at[row_idx, field]) == "" and normalize_space(value) != "":
|
| 446 |
+
df.at[row_idx, field] = value
|
| 447 |
+
elif field in df.columns and field == "sourcebackfillstatus":
|
| 448 |
+
df.at[row_idx, field] = value
|
| 449 |
+
|
| 450 |
+
ingredient_stats = fill_from_ingredient_detail(
|
| 451 |
+
df=df,
|
| 452 |
+
timeout=args.timeout,
|
| 453 |
+
workers=args.workers,
|
| 454 |
+
force_refresh=args.force_refresh_cache,
|
| 455 |
+
)
|
| 456 |
+
print(f"ingredient_stats={json.dumps(dict(ingredient_stats), ensure_ascii=False)}")
|
| 457 |
+
|
| 458 |
+
remaining_mask = df.apply(row_needs_backfill, axis=1)
|
| 459 |
+
report_rows = df.loc[candidate_mask, REPORT_COLUMNS].copy()
|
| 460 |
+
report_rows.to_csv(REPORT_CSV, index=False, encoding="utf-8-sig")
|
| 461 |
+
|
| 462 |
+
report = {
|
| 463 |
+
"input_file": str(args.input),
|
| 464 |
+
"candidate_rows": candidate_rows,
|
| 465 |
+
"remaining_candidate_rows": int(remaining_mask.sum()),
|
| 466 |
+
"unique_herbs": int(df.loc[candidate_mask, "herbid"].replace("", pd.NA).dropna().nunique()),
|
| 467 |
+
"unique_ingredients_matched": int(df.loc[candidate_mask, "herb2ingredientid"].replace("", pd.NA).dropna().nunique()),
|
| 468 |
+
"herb_stats": dict(herb_stats),
|
| 469 |
+
"ingredient_stats": dict(ingredient_stats),
|
| 470 |
+
"generated_at_unix": int(time.time()),
|
| 471 |
+
}
|
| 472 |
+
REPORT_JSON.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 473 |
+
|
| 474 |
+
if not args.no_overwrite:
|
| 475 |
+
if args.input.resolve() == INPUT_XLSX.resolve() and not BACKUP_XLSX.exists():
|
| 476 |
+
shutil.copy2(args.input, BACKUP_XLSX)
|
| 477 |
+
df.to_excel(args.input, index=False, engine="openpyxl")
|
| 478 |
+
print(f"saved_input={args.input}")
|
| 479 |
+
else:
|
| 480 |
+
print("save_skipped=true")
|
| 481 |
+
|
| 482 |
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
if __name__ == "__main__":
|
| 486 |
+
main()
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/data/build_tcm_libraries.py
ADDED
|
@@ -0,0 +1,2058 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""用于整合多个中药数据库并构建统一的中药-化合物知识底座。"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
from collections import Counter, defaultdict
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from difflib import SequenceMatcher
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Iterable, Mapping
|
| 12 |
+
|
| 13 |
+
import pandas as pd
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
from rdkit import Chem
|
| 17 |
+
from rdkit import RDLogger
|
| 18 |
+
from rdkit.Chem import Descriptors
|
| 19 |
+
from rdkit.Chem import rdMolDescriptors
|
| 20 |
+
|
| 21 |
+
RDLogger.DisableLog("rdApp.*")
|
| 22 |
+
HAS_RDKIT = True
|
| 23 |
+
except Exception:
|
| 24 |
+
Chem = None
|
| 25 |
+
Descriptors = None
|
| 26 |
+
rdMolDescriptors = None
|
| 27 |
+
HAS_RDKIT = False
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 31 |
+
RAW_DIR = BASE_DIR / "原始数据汇总"
|
| 32 |
+
HERB_DIR = BASE_DIR / "中药表格"
|
| 33 |
+
OUT_DIR = BASE_DIR / "整理输出"
|
| 34 |
+
|
| 35 |
+
CHECKMARK = "√"
|
| 36 |
+
|
| 37 |
+
SOURCE_URLS = {
|
| 38 |
+
"BATMAN-TCM": "http://bionet.ncpsb.org.cn/batman-tcm/#/home",
|
| 39 |
+
"DCABM-TCM": "http://bionet.ncpsb.org.cn/dcabm-tcm/#/Home",
|
| 40 |
+
"ETCM2": "http://www.tcmip.cn/ETCM2/front/#/browse/herb",
|
| 41 |
+
"HERB2": "http://47.92.70.12/FAQ/",
|
| 42 |
+
"SymMap": "http://www.symmap.org/",
|
| 43 |
+
"TCMIO": "http://tcmio.xielab.net/browse/tcms",
|
| 44 |
+
"TM-MC": "https://tm-mc.kr/index.jsp",
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
SOURCE_ORDER = [
|
| 48 |
+
"BATMAN-TCM",
|
| 49 |
+
"DCABM-TCM",
|
| 50 |
+
"ETCM2",
|
| 51 |
+
"HERB2",
|
| 52 |
+
"SymMap",
|
| 53 |
+
"TCMIO",
|
| 54 |
+
"TM-MC",
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
RELATION_CONFIG = {
|
| 58 |
+
"BATMAN-TCM": {
|
| 59 |
+
"path": RAW_DIR / "BATMAN" / "BATMAN-TCM_Info_汇总_with_herbid_with_cid.xlsx",
|
| 60 |
+
"chinese": ["chinese.name"],
|
| 61 |
+
"pinyin": ["pinyin.name"],
|
| 62 |
+
"latin": ["latin.name"],
|
| 63 |
+
"seed_herb_id": ["herbid"],
|
| 64 |
+
"compound_id": ["compound_id"],
|
| 65 |
+
"pubchem": ["pubchemcid"],
|
| 66 |
+
"name": ["name"],
|
| 67 |
+
"formula": ["molecularformula"],
|
| 68 |
+
"smiles": ["smiles"],
|
| 69 |
+
"weight": ["averageweight"],
|
| 70 |
+
"inchi": ["inchi"],
|
| 71 |
+
"inchikey": ["inchkey", "inchikey"],
|
| 72 |
+
"cas": ["cas"],
|
| 73 |
+
},
|
| 74 |
+
"DCABM-TCM": {
|
| 75 |
+
"path": RAW_DIR / "DCABM" / "DCABM-TCM_Info_汇总_with_herbid_with_cid.xlsx",
|
| 76 |
+
"chinese": ["chinesename"],
|
| 77 |
+
"pinyin": ["pinyinname"],
|
| 78 |
+
"latin": ["latinname"],
|
| 79 |
+
"seed_herb_id": ["herbid"],
|
| 80 |
+
"compound_id": ["compound_id"],
|
| 81 |
+
"pubchem": ["pubchemcid", "cid"],
|
| 82 |
+
"name": ["name"],
|
| 83 |
+
"formula": ["molecularformula"],
|
| 84 |
+
"smiles": ["smiles1", "smiles"],
|
| 85 |
+
"weight": ["averageweight"],
|
| 86 |
+
"inchi": ["inchi"],
|
| 87 |
+
"inchikey": ["inchkey", "inchikey"],
|
| 88 |
+
"cas": ["cas"],
|
| 89 |
+
},
|
| 90 |
+
"ETCM2": {
|
| 91 |
+
"path": RAW_DIR / "ETCM2" / "ETCM2_Info_汇总_with_herbid_with_cid.xlsx",
|
| 92 |
+
"chinese": ["chinesename"],
|
| 93 |
+
"pinyin": ["pinyinname"],
|
| 94 |
+
"latin": [],
|
| 95 |
+
"seed_herb_id": ["herbid"],
|
| 96 |
+
"compound_id": ["compound_id"],
|
| 97 |
+
"pubchem": ["pubchemcid"],
|
| 98 |
+
"name": ["iupacname", "queriedidentifier"],
|
| 99 |
+
"formula": ["molecularformula"],
|
| 100 |
+
"smiles": ["smiles"],
|
| 101 |
+
"weight": ["averageweight"],
|
| 102 |
+
"inchi": ["inchi"],
|
| 103 |
+
"inchikey": ["inchkey", "inchikey"],
|
| 104 |
+
"cas": ["cas"],
|
| 105 |
+
},
|
| 106 |
+
"HERB2": {
|
| 107 |
+
"path": RAW_DIR / "HERB2" / "HERB2_Info_汇总_with_herbid_with_cid.xlsx",
|
| 108 |
+
"chinese": ["herbcnname"],
|
| 109 |
+
"pinyin": ["herbpinyinname"],
|
| 110 |
+
"latin": ["herblatinname"],
|
| 111 |
+
"seed_herb_id": ["herbid.1"],
|
| 112 |
+
"compound_id": ["compound_id"],
|
| 113 |
+
"pubchem": ["pubchemcid"],
|
| 114 |
+
"name": ["iupacname", "queriedname"],
|
| 115 |
+
"formula": ["molecularformula"],
|
| 116 |
+
"smiles": ["smiles"],
|
| 117 |
+
"weight": ["averageweight"],
|
| 118 |
+
"inchi": ["inchi"],
|
| 119 |
+
"inchikey": ["inchkey", "inchikey"],
|
| 120 |
+
"cas": ["cas"],
|
| 121 |
+
"source_herb_code": ["herbid"],
|
| 122 |
+
},
|
| 123 |
+
"SymMap": {
|
| 124 |
+
"path": RAW_DIR / "SymMap" / "SymMap_Info_汇总_with_herbid_with_cid.xlsx",
|
| 125 |
+
"chinese": ["chinesename"],
|
| 126 |
+
"pinyin": ["pinyinname"],
|
| 127 |
+
"latin": ["latinname"],
|
| 128 |
+
"seed_herb_id": ["herbid"],
|
| 129 |
+
"compound_id": ["compound_id"],
|
| 130 |
+
"pubchem": ["pubchemcid"],
|
| 131 |
+
"name": ["name", "iupacname", "queriedidentifier"],
|
| 132 |
+
"formula": ["molecularformula"],
|
| 133 |
+
"smiles": ["smiles"],
|
| 134 |
+
"weight": ["averageweight"],
|
| 135 |
+
"inchi": ["inchi"],
|
| 136 |
+
"inchikey": ["inchkey", "inchikey"],
|
| 137 |
+
"cas": ["cas"],
|
| 138 |
+
},
|
| 139 |
+
"TCMIO": {
|
| 140 |
+
"path": RAW_DIR / "TCMIO" / "TCMIO_Info_汇总_with_herbid_with_cid.xlsx",
|
| 141 |
+
"chinese": ["chinesename"],
|
| 142 |
+
"pinyin": ["pinyinname"],
|
| 143 |
+
"latin": [],
|
| 144 |
+
"seed_herb_id": ["herbid"],
|
| 145 |
+
"compound_id": ["compound_id"],
|
| 146 |
+
"pubchem": ["pubchemcid", "cid"],
|
| 147 |
+
"name": ["name", "iupacname"],
|
| 148 |
+
"formula": ["molecularformula", "molecularformula.1"],
|
| 149 |
+
"smiles": ["canonicalsmiles", "smiles"],
|
| 150 |
+
"weight": ["molecularweight", "averageweight"],
|
| 151 |
+
"inchi": ["inchi"],
|
| 152 |
+
"inchikey": ["inchikey", "inchkey"],
|
| 153 |
+
"cas": ["cas"],
|
| 154 |
+
},
|
| 155 |
+
"TM-MC": {
|
| 156 |
+
"path": RAW_DIR / "TM-MC" / "TM-MC_Info_汇总_with_herbid_with_cid.xlsx",
|
| 157 |
+
"chinese": ["chinese"],
|
| 158 |
+
"pinyin": ["pinyin"],
|
| 159 |
+
"latin": ["latin"],
|
| 160 |
+
"seed_herb_id": ["herbid"],
|
| 161 |
+
"compound_id": ["compound_id"],
|
| 162 |
+
"pubchem": ["pubchemcid", "cid", "queryidentifier"],
|
| 163 |
+
"name": ["name", "iupacname"],
|
| 164 |
+
"formula": ["molecularformula", "molecularformula.1"],
|
| 165 |
+
"smiles": ["canonicalsmiles", "smiles"],
|
| 166 |
+
"weight": ["molecularweight", "averageweight"],
|
| 167 |
+
"inchi": ["inchi"],
|
| 168 |
+
"inchikey": ["inchikey", "inchkey"],
|
| 169 |
+
"cas": ["cas"],
|
| 170 |
+
},
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
HERB_SOURCE_CONFIG = {
|
| 174 |
+
"BATMAN-TCM": {
|
| 175 |
+
"path": HERB_DIR / "BATMAN-TCM.xlsx",
|
| 176 |
+
"chinese": ["Chinese.Name"],
|
| 177 |
+
"pinyin": ["Pinyin.Name"],
|
| 178 |
+
"latin": ["Latin.Name"],
|
| 179 |
+
"alias": [],
|
| 180 |
+
"english": ["English.Name"],
|
| 181 |
+
"source_code": [],
|
| 182 |
+
},
|
| 183 |
+
"DCABM-TCM": {
|
| 184 |
+
"path": HERB_DIR / "DCABM-TCM.xlsx",
|
| 185 |
+
"chinese": ["Chinese.name"],
|
| 186 |
+
"pinyin": ["Pinyin.name"],
|
| 187 |
+
"latin": ["Latin.name"],
|
| 188 |
+
"alias": [],
|
| 189 |
+
"english": ["English.name"],
|
| 190 |
+
"source_code": ["TCMID.ID", "CMAUP.ID"],
|
| 191 |
+
},
|
| 192 |
+
"ETCM2": {
|
| 193 |
+
"path": HERB_DIR / "ETCM2.xlsx",
|
| 194 |
+
"chinese": [],
|
| 195 |
+
"pinyin": ["拼音名"],
|
| 196 |
+
"latin": ["拉丁名"],
|
| 197 |
+
"alias": [],
|
| 198 |
+
"english": [],
|
| 199 |
+
"source_code": [],
|
| 200 |
+
},
|
| 201 |
+
"HERB2": {
|
| 202 |
+
"path": HERB_DIR / "HERB2.xlsx",
|
| 203 |
+
"chinese": ["Herb_cn_name"],
|
| 204 |
+
"pinyin": ["Herb_pinyin_name"],
|
| 205 |
+
"latin": ["Herb_latin_name"],
|
| 206 |
+
"alias": ["Herb_alias_name"],
|
| 207 |
+
"english": ["Herb_en_name"],
|
| 208 |
+
"source_code": ["Herb_id"],
|
| 209 |
+
},
|
| 210 |
+
"SymMap": {
|
| 211 |
+
"path": HERB_DIR / "SymMap.xlsx",
|
| 212 |
+
"chinese": ["Chinese_name"],
|
| 213 |
+
"pinyin": ["Pinyin_name"],
|
| 214 |
+
"latin": ["Latin_name"],
|
| 215 |
+
"alias": ["Alias"],
|
| 216 |
+
"english": ["English_name"],
|
| 217 |
+
"source_code": ["Herb_id", "HERBDB_ID"],
|
| 218 |
+
},
|
| 219 |
+
"TCMIO": {
|
| 220 |
+
"path": HERB_DIR / "TCMIO.xlsx",
|
| 221 |
+
"chinese": ["chinese_name"],
|
| 222 |
+
"pinyin": ["pinyin_name"],
|
| 223 |
+
"latin": [],
|
| 224 |
+
"alias": [],
|
| 225 |
+
"english": ["english_name"],
|
| 226 |
+
"source_code": ["id"],
|
| 227 |
+
},
|
| 228 |
+
"TM-MC": {
|
| 229 |
+
"path": HERB_DIR / "TM-MC.xlsx",
|
| 230 |
+
"chinese": ["CHINESE", "HANJA"],
|
| 231 |
+
"pinyin": ["PINYIN"],
|
| 232 |
+
"latin": ["LATIN"],
|
| 233 |
+
"alias": [],
|
| 234 |
+
"english": ["COMMON"],
|
| 235 |
+
"source_code": [],
|
| 236 |
+
},
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
ALIAS_SEPARATORS = r"[、;,/|\n\r;]"
|
| 240 |
+
LATIN_NAME_SEP = r"[;|/]"
|
| 241 |
+
LATIN_PART_WORDS = {
|
| 242 |
+
"radix",
|
| 243 |
+
"rhizoma",
|
| 244 |
+
"fructus",
|
| 245 |
+
"folium",
|
| 246 |
+
"cortex",
|
| 247 |
+
"semen",
|
| 248 |
+
"flos",
|
| 249 |
+
"herba",
|
| 250 |
+
"caulis",
|
| 251 |
+
"ramulus",
|
| 252 |
+
"pericarpium",
|
| 253 |
+
"tuber",
|
| 254 |
+
"bulbus",
|
| 255 |
+
"resina",
|
| 256 |
+
"spora",
|
| 257 |
+
"succus",
|
| 258 |
+
"gummi",
|
| 259 |
+
"oleum",
|
| 260 |
+
"rad.",
|
| 261 |
+
"rhiz.",
|
| 262 |
+
"fol.",
|
| 263 |
+
"fruct.",
|
| 264 |
+
"fl.",
|
| 265 |
+
"cort.",
|
| 266 |
+
}
|
| 267 |
+
LATIN_SUFFIXES = ["orum", "arum", "ius", "us", "a", "um", "is", "ii", "ae", "e", "os", "es", "i"]
|
| 268 |
+
LATIN_PART_CANONICAL = {re.sub(r"[^a-z]", "", word.lower()): re.sub(r"[^a-z]", "", word.lower()) for word in LATIN_PART_WORDS}
|
| 269 |
+
FORMULA_RE = re.compile(r"^(?:[A-Z][a-z]?\d*)+$")
|
| 270 |
+
CAS_RE = re.compile(r"^\d{2,7}-\d{2}-\d$")
|
| 271 |
+
REGISTRY_RE = re.compile(r"^(?:CHEMBL|SCHEMBL|HMDB|DB|CID)\S*$", re.I)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def read_any_table(path: Path) -> pd.DataFrame:
|
| 275 |
+
if path.suffix.lower() in {".xlsx", ".xls"}:
|
| 276 |
+
df = pd.read_excel(path, dtype=str, engine="openpyxl")
|
| 277 |
+
else:
|
| 278 |
+
for enc in ("utf-8-sig", "utf-8", "gbk"):
|
| 279 |
+
try:
|
| 280 |
+
df = pd.read_csv(path, dtype=str, encoding=enc)
|
| 281 |
+
break
|
| 282 |
+
except Exception:
|
| 283 |
+
continue
|
| 284 |
+
else:
|
| 285 |
+
raise ValueError(f"cannot read {path}")
|
| 286 |
+
return df.fillna("")
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def first_nonempty(row: pd.Series | Mapping[str, object], candidates: Iterable[str]) -> str:
|
| 290 |
+
for col in candidates:
|
| 291 |
+
if col in row:
|
| 292 |
+
value = normalize_space(row[col])
|
| 293 |
+
if value:
|
| 294 |
+
return value
|
| 295 |
+
return ""
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def coalesce_series(df: pd.DataFrame, candidates: Iterable[str]) -> pd.Series:
|
| 299 |
+
series = pd.Series([""] * len(df), index=df.index, dtype="object")
|
| 300 |
+
for col in candidates:
|
| 301 |
+
if col in df.columns:
|
| 302 |
+
values = df[col].fillna("").astype(str).map(normalize_space)
|
| 303 |
+
series = series.where(series != "", values)
|
| 304 |
+
return series.fillna("")
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def normalize_space(value: object) -> str:
|
| 308 |
+
if value is None:
|
| 309 |
+
return ""
|
| 310 |
+
text = str(value).strip()
|
| 311 |
+
text = re.sub(r"\s+", " ", text)
|
| 312 |
+
return "" if text.lower() == "nan" else text
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def split_aliases(cell: object) -> list[str]:
|
| 316 |
+
value = normalize_space(cell)
|
| 317 |
+
if not value:
|
| 318 |
+
return []
|
| 319 |
+
return [part.strip() for part in re.split(ALIAS_SEPARATORS, value) if part.strip()]
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def uniq_preserve(values: Iterable[str]) -> list[str]:
|
| 323 |
+
out = []
|
| 324 |
+
seen = set()
|
| 325 |
+
for value in values:
|
| 326 |
+
value = normalize_space(value)
|
| 327 |
+
if not value or value in seen:
|
| 328 |
+
continue
|
| 329 |
+
seen.add(value)
|
| 330 |
+
out.append(value)
|
| 331 |
+
return out
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def normalize_pubchem(value: object) -> str:
|
| 335 |
+
text = normalize_space(value)
|
| 336 |
+
if not text:
|
| 337 |
+
return ""
|
| 338 |
+
text = text.replace("Pubchem CID:", "").replace("PubChem CID:", "").strip()
|
| 339 |
+
match = re.search(r"\d+", text)
|
| 340 |
+
if not match:
|
| 341 |
+
return ""
|
| 342 |
+
digits = match.group(0)
|
| 343 |
+
return "" if digits == "0" else digits
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def normalize_cas(value: object) -> str:
|
| 347 |
+
text = normalize_space(value)
|
| 348 |
+
return text
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def normalize_inchi(value: object) -> str:
|
| 352 |
+
text = normalize_space(value)
|
| 353 |
+
return text
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def normalize_inchikey(value: object) -> str:
|
| 357 |
+
text = normalize_space(value).upper()
|
| 358 |
+
text = text.replace("INCHIKEY=", "").strip()
|
| 359 |
+
return text
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def is_formula_like(value: object) -> bool:
|
| 363 |
+
text = normalize_space(value)
|
| 364 |
+
if not text:
|
| 365 |
+
return False
|
| 366 |
+
return FORMULA_RE.fullmatch(text) is not None
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def is_cas_like(value: object) -> bool:
|
| 370 |
+
text = normalize_space(value)
|
| 371 |
+
if not text:
|
| 372 |
+
return False
|
| 373 |
+
return CAS_RE.fullmatch(text) is not None
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def is_registry_like(value: object) -> bool:
|
| 377 |
+
text = normalize_space(value)
|
| 378 |
+
if not text:
|
| 379 |
+
return False
|
| 380 |
+
return REGISTRY_RE.fullmatch(text) is not None
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def derive_structure_from_smiles(value: object) -> dict[str, str]:
|
| 384 |
+
text = normalize_space(value)
|
| 385 |
+
if not text or not HAS_RDKIT:
|
| 386 |
+
return {}
|
| 387 |
+
mol = Chem.MolFromSmiles(text)
|
| 388 |
+
if mol is None:
|
| 389 |
+
return {}
|
| 390 |
+
try:
|
| 391 |
+
canonical_smiles = Chem.MolToSmiles(mol, canonical=True)
|
| 392 |
+
inchi = Chem.MolToInchi(mol)
|
| 393 |
+
inchikey = Chem.InchiToInchiKey(inchi) if inchi else ""
|
| 394 |
+
formula = rdMolDescriptors.CalcMolFormula(mol) if rdMolDescriptors else ""
|
| 395 |
+
mw = f"{Descriptors.MolWt(mol):.4f}" if Descriptors else ""
|
| 396 |
+
except Exception:
|
| 397 |
+
return {}
|
| 398 |
+
return {
|
| 399 |
+
"smiles": canonical_smiles,
|
| 400 |
+
"inchi": inchi,
|
| 401 |
+
"inchikey": inchikey,
|
| 402 |
+
"standard_inchikey": inchikey,
|
| 403 |
+
"molecular_formula": formula,
|
| 404 |
+
"average_weight": mw,
|
| 405 |
+
"skeleton_key": inchikey.split("-")[0] if inchikey else "",
|
| 406 |
+
"derived_from_name_type": "smiles_like",
|
| 407 |
+
}
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def derive_compound_fields_from_name(raw_name: object) -> dict[str, str]:
|
| 411 |
+
text = normalize_space(raw_name)
|
| 412 |
+
if not text:
|
| 413 |
+
return {}
|
| 414 |
+
if is_formula_like(text):
|
| 415 |
+
return {
|
| 416 |
+
"molecular_formula": text,
|
| 417 |
+
"derived_from_name_type": "molecular_formula",
|
| 418 |
+
}
|
| 419 |
+
if is_cas_like(text):
|
| 420 |
+
return {
|
| 421 |
+
"cas": text,
|
| 422 |
+
"derived_from_name_type": "cas_like",
|
| 423 |
+
}
|
| 424 |
+
struct = derive_structure_from_smiles(text)
|
| 425 |
+
if struct:
|
| 426 |
+
return struct
|
| 427 |
+
if is_registry_like(text):
|
| 428 |
+
return {
|
| 429 |
+
"derived_from_name_type": "registry_or_db_id",
|
| 430 |
+
}
|
| 431 |
+
return {
|
| 432 |
+
"derived_from_name_type": "chemical_name",
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def standardize_text_key(value: object) -> str:
|
| 437 |
+
text = normalize_space(value).lower()
|
| 438 |
+
text = re.sub(r"[^0-9a-z]+", " ", text)
|
| 439 |
+
text = re.sub(r"\s+", " ", text).strip()
|
| 440 |
+
return text
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def keep_toluan80(s: str) -> str:
|
| 444 |
+
s = re.sub(r"(?i)(吐温\s*80)", "__TWW80__", s)
|
| 445 |
+
s = re.sub(r"\d+", "", s)
|
| 446 |
+
return s.replace("__TWW80__", "吐温80")
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def remove_brackets_content(s: str) -> str:
|
| 450 |
+
return re.sub(r"\(.*?\)|\(.*?\)|\[.*?\]|<.*?>", "", s).strip()
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def split_bracket_inner_and_outer(s: str) -> list[str]:
|
| 454 |
+
s = normalize_space(s)
|
| 455 |
+
if not s:
|
| 456 |
+
return []
|
| 457 |
+
inners = re.findall(r"\((.*?)\)|\((.*?)\)|\[(.*?)\]|<(.*?)>", s)
|
| 458 |
+
values = []
|
| 459 |
+
if inners:
|
| 460 |
+
for token_group in inners:
|
| 461 |
+
for token in token_group:
|
| 462 |
+
token = normalize_space(token)
|
| 463 |
+
if token:
|
| 464 |
+
values.append(token)
|
| 465 |
+
outer = remove_brackets_content(s)
|
| 466 |
+
if outer:
|
| 467 |
+
values.insert(0, outer)
|
| 468 |
+
return uniq_preserve(values)
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def strip_english_and_punct(s: str) -> str:
|
| 472 |
+
s = re.sub(r'[A-Za-z0-9\(\)\[\]<>/\\@#\$%&\*\-—_+=~`:,.;?"!%]', " ", s)
|
| 473 |
+
return re.sub(r"\s+", " ", s).strip()
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def normalize_chinese_candidate(value: object) -> list[str]:
|
| 477 |
+
text = normalize_space(value)
|
| 478 |
+
if not text:
|
| 479 |
+
return []
|
| 480 |
+
text = keep_toluan80(text)
|
| 481 |
+
candidates = []
|
| 482 |
+
outer = strip_english_and_punct(remove_brackets_content(text))
|
| 483 |
+
if outer:
|
| 484 |
+
candidates.append(re.sub(r"[\s\W_0-9]+", "", outer))
|
| 485 |
+
for part in split_bracket_inner_and_outer(text):
|
| 486 |
+
cleaned = strip_english_and_punct(part)
|
| 487 |
+
cleaned = re.sub(r"[\s\W_0-9]+", "", cleaned)
|
| 488 |
+
if cleaned and cleaned not in candidates:
|
| 489 |
+
candidates.append(cleaned)
|
| 490 |
+
base = re.sub(r"[\s\W_0-9]+", "", strip_english_and_punct(text))
|
| 491 |
+
if base and base not in candidates:
|
| 492 |
+
candidates.append(base)
|
| 493 |
+
return [item for item in candidates if item]
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def normalize_chinese_key(value: object) -> str:
|
| 497 |
+
candidates = normalize_chinese_candidate(value)
|
| 498 |
+
return candidates[0] if candidates else ""
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def normalize_pinyin_for_compare(value: object) -> str:
|
| 502 |
+
text = normalize_space(value)
|
| 503 |
+
if not text:
|
| 504 |
+
return ""
|
| 505 |
+
text = re.sub(r"\d", "", text)
|
| 506 |
+
text = re.sub(r"[^\w\s]", "", text)
|
| 507 |
+
text = re.sub(r"\s+", "", text)
|
| 508 |
+
return text.lower()
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def normalize_latin_name(value: object) -> str:
|
| 512 |
+
text = normalize_space(value)
|
| 513 |
+
if not text:
|
| 514 |
+
return ""
|
| 515 |
+
text = re.sub(r"[^A-Za-z\s]", " ", text)
|
| 516 |
+
text = re.sub(r"\s+", " ", text).strip().lower()
|
| 517 |
+
return text
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def latin_names_from_cell(value: object) -> list[str]:
|
| 521 |
+
text = normalize_space(value)
|
| 522 |
+
if not text:
|
| 523 |
+
return []
|
| 524 |
+
parts = re.split(LATIN_NAME_SEP, text)
|
| 525 |
+
out = []
|
| 526 |
+
for part in parts:
|
| 527 |
+
part = normalize_latin_name(part)
|
| 528 |
+
if part:
|
| 529 |
+
out.append(part)
|
| 530 |
+
return uniq_preserve(out)
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def latin_words(value: str) -> list[str]:
|
| 534 |
+
return normalize_latin_name(value).split()
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def latin_part_words_from_name(value: str) -> tuple[str, ...]:
|
| 538 |
+
parts = []
|
| 539 |
+
for word in latin_words(value):
|
| 540 |
+
key = re.sub(r"[^a-z]", "", word.lower())
|
| 541 |
+
if key in LATIN_PART_CANONICAL:
|
| 542 |
+
parts.append(LATIN_PART_CANONICAL[key])
|
| 543 |
+
return tuple(sorted(set(parts)))
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def latin_part_signatures(value: object) -> set[str]:
|
| 547 |
+
names = latin_names_from_cell(value)
|
| 548 |
+
if not names:
|
| 549 |
+
return {""}
|
| 550 |
+
signatures = set()
|
| 551 |
+
for name in names:
|
| 552 |
+
signatures.add("|".join(latin_part_words_from_name(name)))
|
| 553 |
+
return signatures or {""}
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def latin_first_two_non_part_words(value: str) -> str:
|
| 557 |
+
words = [word for word in latin_words(value) if re.sub(r"[^a-z]", "", word.lower()) not in LATIN_PART_CANONICAL]
|
| 558 |
+
return " ".join(words[:2]) if words else ""
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def latin_first_two_words(value: str) -> str:
|
| 562 |
+
words = normalize_latin_name(value).split()
|
| 563 |
+
return " ".join(words[:2]) if words else ""
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def remove_latin_part_words(value: str) -> str:
|
| 567 |
+
words = [word for word in normalize_latin_name(value).split() if word not in LATIN_PART_WORDS]
|
| 568 |
+
return " ".join(words)
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def latin_word_stem(word: str) -> str:
|
| 572 |
+
word = word.lower()
|
| 573 |
+
for suffix in sorted(LATIN_SUFFIXES, key=len, reverse=True):
|
| 574 |
+
if word.endswith(suffix) and len(word) - len(suffix) >= 3:
|
| 575 |
+
return word[: -len(suffix)]
|
| 576 |
+
return word
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def latin_full_two_word_key_variants(value: object) -> set[str]:
|
| 580 |
+
keys = set()
|
| 581 |
+
for name in latin_names_from_cell(value):
|
| 582 |
+
raw = latin_first_two_words(name)
|
| 583 |
+
if raw:
|
| 584 |
+
keys.add(raw)
|
| 585 |
+
for key in list(keys):
|
| 586 |
+
stems = [latin_word_stem(word) for word in key.split() if word]
|
| 587 |
+
if stems:
|
| 588 |
+
keys.add(" ".join(stems))
|
| 589 |
+
return {key for key in keys if key}
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def latin_botanical_two_word_key_variants(value: object) -> set[str]:
|
| 593 |
+
keys = set()
|
| 594 |
+
for name in latin_names_from_cell(value):
|
| 595 |
+
botanical = latin_first_two_non_part_words(name)
|
| 596 |
+
if botanical:
|
| 597 |
+
keys.add(botanical)
|
| 598 |
+
for key in list(keys):
|
| 599 |
+
stems = [latin_word_stem(word) for word in key.split() if word]
|
| 600 |
+
if stems:
|
| 601 |
+
keys.add(" ".join(stems))
|
| 602 |
+
return {key for key in keys if key}
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def latin_stems_from_value(value: object) -> set[str]:
|
| 606 |
+
stems = set()
|
| 607 |
+
for name in latin_names_from_cell(value):
|
| 608 |
+
for word in name.split():
|
| 609 |
+
stem = latin_word_stem(word)
|
| 610 |
+
if stem:
|
| 611 |
+
stems.add(stem)
|
| 612 |
+
return stems
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def latin_part_relation(left_parts: set[str], right_parts: set[str]) -> str:
|
| 616 |
+
left_nonempty = {part for part in left_parts if part}
|
| 617 |
+
right_nonempty = {part for part in right_parts if part}
|
| 618 |
+
if left_nonempty and right_nonempty:
|
| 619 |
+
return "same" if left_nonempty & right_nonempty else "different"
|
| 620 |
+
if not left_nonempty and not right_nonempty:
|
| 621 |
+
return "same"
|
| 622 |
+
return "unknown"
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def pinyin_similarity(a: str, b: str) -> float:
|
| 626 |
+
if not a or not b:
|
| 627 |
+
return 0.0
|
| 628 |
+
return SequenceMatcher(None, a, b).ratio()
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def join_sorted(values: Iterable[str], sep: str = ";") -> str:
|
| 632 |
+
items = uniq_preserve(values)
|
| 633 |
+
return sep.join(items)
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
def join_examples(values: Iterable[str], limit: int = 10, sep: str = ";") -> str:
|
| 637 |
+
items = uniq_preserve(values)
|
| 638 |
+
if not items:
|
| 639 |
+
return ""
|
| 640 |
+
if len(items) <= limit:
|
| 641 |
+
return sep.join(items)
|
| 642 |
+
return sep.join(items[:limit] + [f"...等{len(items)}项"])
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
def numeric_sort_key(value: str) -> tuple[int, str]:
|
| 646 |
+
match = re.search(r"(\d+)$", value)
|
| 647 |
+
return (int(match.group(1)) if match else 10**9, value)
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
def normalize_herb_id(value: object, width: int = 5) -> str:
|
| 651 |
+
text = normalize_space(value).upper()
|
| 652 |
+
match = re.fullmatch(r"H0*(\d+)", text)
|
| 653 |
+
if not match:
|
| 654 |
+
return text
|
| 655 |
+
return f"H{int(match.group(1)):0{width}d}"
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def next_id(existing_ids: Iterable[str], prefix: str, width: int) -> int:
|
| 659 |
+
nums = []
|
| 660 |
+
for value in existing_ids:
|
| 661 |
+
match = re.search(rf"{re.escape(prefix)}0*(\d+)$", value)
|
| 662 |
+
if match:
|
| 663 |
+
nums.append(int(match.group(1)))
|
| 664 |
+
return max(nums) + 1 if nums else 1
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
@dataclass
|
| 668 |
+
class HerbResolution:
|
| 669 |
+
herb_id: str
|
| 670 |
+
method: str
|
| 671 |
+
confidence: str
|
| 672 |
+
review_reason: str
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
class UnionFind:
|
| 676 |
+
def __init__(self, values: Iterable[str]) -> None:
|
| 677 |
+
self.parent = {value: value for value in values}
|
| 678 |
+
|
| 679 |
+
def find(self, value: str) -> str:
|
| 680 |
+
parent = self.parent[value]
|
| 681 |
+
if parent != value:
|
| 682 |
+
self.parent[value] = self.find(parent)
|
| 683 |
+
return self.parent[value]
|
| 684 |
+
|
| 685 |
+
def union(self, a: str, b: str) -> None:
|
| 686 |
+
ra, rb = self.find(a), self.find(b)
|
| 687 |
+
if ra != rb:
|
| 688 |
+
if numeric_sort_key(ra) <= numeric_sort_key(rb):
|
| 689 |
+
self.parent[rb] = ra
|
| 690 |
+
else:
|
| 691 |
+
self.parent[ra] = rb
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
def should_merge_reference_rows(row_a: dict, row_b: dict) -> tuple[bool, str]:
|
| 695 |
+
ch_a = row_a["中文名_key"]
|
| 696 |
+
ch_b = row_b["中文名_key"]
|
| 697 |
+
py_a = row_a["pinyin_key"]
|
| 698 |
+
py_b = row_b["pinyin_key"]
|
| 699 |
+
latin_full_keys_a = row_a["latin_full_keys"]
|
| 700 |
+
latin_full_keys_b = row_b["latin_full_keys"]
|
| 701 |
+
latin_bot_keys_a = row_a["latin_botanical_keys"]
|
| 702 |
+
latin_bot_keys_b = row_b["latin_botanical_keys"]
|
| 703 |
+
latin_stems_a = row_a["latin_stems"]
|
| 704 |
+
latin_stems_b = row_b["latin_stems"]
|
| 705 |
+
latin_parts_a = row_a["latin_parts"]
|
| 706 |
+
latin_parts_b = row_b["latin_parts"]
|
| 707 |
+
full_a = (ch_a, row_a["alias_key"], py_a, row_a["latin_norm"])
|
| 708 |
+
full_b = (ch_b, row_b["alias_key"], py_b, row_b["latin_norm"])
|
| 709 |
+
part_relation = latin_part_relation(latin_parts_a, latin_parts_b)
|
| 710 |
+
|
| 711 |
+
if any(full_a) and full_a == full_b:
|
| 712 |
+
return True, "exact_signature"
|
| 713 |
+
if ch_a and ch_a == ch_b:
|
| 714 |
+
if py_a and py_a == py_b and ((latin_full_keys_a & latin_full_keys_b) or not row_a["latin_norm"] or not row_b["latin_norm"]):
|
| 715 |
+
return True, "same_chinese_pinyin"
|
| 716 |
+
if (latin_full_keys_a & latin_full_keys_b) and part_relation != "different" and (not py_a or not py_b or pinyin_similarity(py_a, py_b) >= 0.75):
|
| 717 |
+
return True, "same_chinese_full_latin"
|
| 718 |
+
if (latin_bot_keys_a & latin_bot_keys_b) and part_relation != "different" and (not py_a or not py_b or pinyin_similarity(py_a, py_b) >= 0.85):
|
| 719 |
+
return True, "same_chinese_botanical_latin"
|
| 720 |
+
if len(latin_stems_a & latin_stems_b) >= 2 and part_relation != "different" and (not py_a or not py_b or pinyin_similarity(py_a, py_b) >= 0.9):
|
| 721 |
+
return True, "same_chinese_latin_stem"
|
| 722 |
+
if py_a and py_b and pinyin_similarity(py_a, py_b) >= 0.9 and (not row_a["latin_norm"] or not row_b["latin_norm"]):
|
| 723 |
+
return True, "same_chinese_similar_pinyin"
|
| 724 |
+
if not ch_a and not ch_b and py_a and py_a == py_b and (latin_full_keys_a & latin_full_keys_b):
|
| 725 |
+
return True, "blank_chinese_same_pinyin_full_latin"
|
| 726 |
+
return False, ""
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
def load_reference_herbs() -> tuple[pd.DataFrame, dict[str, str], list[dict], list[dict]]:
|
| 730 |
+
ref_path = HERB_DIR / "herbs.xlsx"
|
| 731 |
+
df = read_any_table(ref_path)
|
| 732 |
+
drop_cols = [col for col in df.columns if str(col).startswith("Unnamed:")]
|
| 733 |
+
if drop_cols:
|
| 734 |
+
df = df.drop(columns=drop_cols)
|
| 735 |
+
df["中文名_key"] = df["中文名"].map(normalize_chinese_key)
|
| 736 |
+
df["alias_key"] = df["别名"].map(lambda x: "|".join(normalize_chinese_candidate(x)))
|
| 737 |
+
df["pinyin_key"] = df["pinyin_name"].map(normalize_pinyin_for_compare)
|
| 738 |
+
df["latin_norm"] = df["Latin_name"].map(normalize_latin_name)
|
| 739 |
+
df["latin_full_keys"] = df["Latin_name"].map(latin_full_two_word_key_variants)
|
| 740 |
+
df["latin_botanical_keys"] = df["Latin_name"].map(latin_botanical_two_word_key_variants)
|
| 741 |
+
df["latin_parts"] = df["Latin_name"].map(latin_part_signatures)
|
| 742 |
+
df["latin_stems"] = df["Latin_name"].map(latin_stems_from_value)
|
| 743 |
+
|
| 744 |
+
uf = UnionFind(df["Herb_id"].tolist())
|
| 745 |
+
merge_rows = []
|
| 746 |
+
|
| 747 |
+
exact_groups = defaultdict(list)
|
| 748 |
+
for row in df.to_dict("records"):
|
| 749 |
+
key = (row["中文名_key"], row["alias_key"], row["pinyin_key"], row["latin_norm"])
|
| 750 |
+
if any(key):
|
| 751 |
+
exact_groups[key].append(row)
|
| 752 |
+
for rows in exact_groups.values():
|
| 753 |
+
if len(rows) < 2:
|
| 754 |
+
continue
|
| 755 |
+
root = rows[0]["Herb_id"]
|
| 756 |
+
for row in rows[1:]:
|
| 757 |
+
uf.union(root, row["Herb_id"])
|
| 758 |
+
merge_rows.append(
|
| 759 |
+
{
|
| 760 |
+
"old_herb_id": row["Herb_id"],
|
| 761 |
+
"new_herb_id": root,
|
| 762 |
+
"reason": "exact_signature",
|
| 763 |
+
"中文名": row["中文名"],
|
| 764 |
+
"pinyin_name": row["pinyin_name"],
|
| 765 |
+
"Latin_name": row["Latin_name"],
|
| 766 |
+
}
|
| 767 |
+
)
|
| 768 |
+
|
| 769 |
+
chinese_groups = defaultdict(list)
|
| 770 |
+
for row in df.to_dict("records"):
|
| 771 |
+
if row["中文名_key"]:
|
| 772 |
+
chinese_groups[row["中文名_key"]].append(row)
|
| 773 |
+
for rows in chinese_groups.values():
|
| 774 |
+
if len(rows) < 2:
|
| 775 |
+
continue
|
| 776 |
+
for i in range(len(rows)):
|
| 777 |
+
for j in range(i + 1, len(rows)):
|
| 778 |
+
merge, reason = should_merge_reference_rows(rows[i], rows[j])
|
| 779 |
+
if merge:
|
| 780 |
+
before_i = uf.find(rows[i]["Herb_id"])
|
| 781 |
+
before_j = uf.find(rows[j]["Herb_id"])
|
| 782 |
+
if before_i != before_j:
|
| 783 |
+
uf.union(rows[i]["Herb_id"], rows[j]["Herb_id"])
|
| 784 |
+
merge_rows.append(
|
| 785 |
+
{
|
| 786 |
+
"old_herb_id": before_j if numeric_sort_key(before_i) < numeric_sort_key(before_j) else before_i,
|
| 787 |
+
"new_herb_id": uf.find(rows[i]["Herb_id"]),
|
| 788 |
+
"reason": reason,
|
| 789 |
+
"中文名": rows[j]["中文名"],
|
| 790 |
+
"pinyin_name": rows[j]["pinyin_name"],
|
| 791 |
+
"Latin_name": rows[j]["Latin_name"],
|
| 792 |
+
}
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
groups = defaultdict(list)
|
| 796 |
+
for herb_id in df["Herb_id"]:
|
| 797 |
+
groups[uf.find(herb_id)].append(herb_id)
|
| 798 |
+
|
| 799 |
+
old_to_new = {}
|
| 800 |
+
records = []
|
| 801 |
+
for entity_idx, (_, member_ids) in enumerate(sorted(groups.items(), key=lambda item: numeric_sort_key(item[0])), start=1):
|
| 802 |
+
member_ids = sorted(member_ids, key=numeric_sort_key)
|
| 803 |
+
subset = df[df["Herb_id"].isin(member_ids)].copy()
|
| 804 |
+
entity_id = f"T{entity_idx:06d}"
|
| 805 |
+
old_to_new.update({member_id: entity_id for member_id in member_ids})
|
| 806 |
+
chinese_values = uniq_preserve(subset["中文名"].tolist())
|
| 807 |
+
alias_values = []
|
| 808 |
+
for value in subset["别名"].tolist():
|
| 809 |
+
alias_values.extend(split_aliases(value))
|
| 810 |
+
pinyin_values = uniq_preserve(subset["pinyin_name"].tolist())
|
| 811 |
+
latin_values = uniq_preserve(subset["Latin_name"].tolist())
|
| 812 |
+
preferred_chinese = chinese_values[0] if chinese_values else ""
|
| 813 |
+
preferred_pinyin = pinyin_values[0] if pinyin_values else ""
|
| 814 |
+
preferred_latin = latin_values[0] if latin_values else ""
|
| 815 |
+
records.append(
|
| 816 |
+
{
|
| 817 |
+
"Herb_id": entity_id,
|
| 818 |
+
"中文名": preferred_chinese,
|
| 819 |
+
"别名": join_sorted([v for v in chinese_values[1:] + alias_values if v and v != preferred_chinese], "、"),
|
| 820 |
+
"pinyin_name": preferred_pinyin,
|
| 821 |
+
"Latin_name": preferred_latin,
|
| 822 |
+
"中文名_variants": join_sorted(chinese_values, ";"),
|
| 823 |
+
"pinyin_variants": join_sorted(pinyin_values, ";"),
|
| 824 |
+
"Latin_variants": join_sorted(latin_values, ";"),
|
| 825 |
+
"来源数据库": "",
|
| 826 |
+
"source_record_count": 0,
|
| 827 |
+
"merged_from_old_ids": join_sorted(member_ids, ";"),
|
| 828 |
+
"review_status": "",
|
| 829 |
+
"review_reason": "",
|
| 830 |
+
}
|
| 831 |
+
)
|
| 832 |
+
|
| 833 |
+
canonical_df = pd.DataFrame(records).sort_values("Herb_id", key=lambda s: s.map(numeric_sort_key)).reset_index(drop=True)
|
| 834 |
+
|
| 835 |
+
review_rows = []
|
| 836 |
+
for chinese_key, rows in chinese_groups.items():
|
| 837 |
+
roots = sorted({old_to_new[row["Herb_id"]] for row in rows}, key=numeric_sort_key)
|
| 838 |
+
if len(roots) > 1:
|
| 839 |
+
review_rows.append(
|
| 840 |
+
{
|
| 841 |
+
"review_type": "same_chinese_multiple_ids",
|
| 842 |
+
"key": chinese_key,
|
| 843 |
+
"candidate_herb_ids": ";".join(roots),
|
| 844 |
+
"rows": json.dumps(
|
| 845 |
+
[
|
| 846 |
+
{
|
| 847 |
+
"Herb_id": row["Herb_id"],
|
| 848 |
+
"中文名": row["中文名"],
|
| 849 |
+
"pinyin_name": row["pinyin_name"],
|
| 850 |
+
"Latin_name": row["Latin_name"],
|
| 851 |
+
}
|
| 852 |
+
for row in rows
|
| 853 |
+
],
|
| 854 |
+
ensure_ascii=False,
|
| 855 |
+
),
|
| 856 |
+
}
|
| 857 |
+
)
|
| 858 |
+
|
| 859 |
+
return canonical_df, old_to_new, merge_rows, review_rows
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
def empty_herb_entry(herb_id: str) -> dict:
|
| 863 |
+
return {
|
| 864 |
+
"Herb_id": herb_id,
|
| 865 |
+
"中文名": "",
|
| 866 |
+
"别名": "",
|
| 867 |
+
"pinyin_name": "",
|
| 868 |
+
"Latin_name": "",
|
| 869 |
+
"中文名_variants": set(),
|
| 870 |
+
"别名_variants": set(),
|
| 871 |
+
"pinyin_variants": set(),
|
| 872 |
+
"Latin_variants": set(),
|
| 873 |
+
"来源数据库": set(),
|
| 874 |
+
"source_record_count": 0,
|
| 875 |
+
"merged_from_old_ids": set(),
|
| 876 |
+
"review_status": set(),
|
| 877 |
+
"review_reason": set(),
|
| 878 |
+
"source_codes": set(),
|
| 879 |
+
"source_records": [],
|
| 880 |
+
"latin_part_signatures": set(),
|
| 881 |
+
}
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
def is_pinyin_only_weak_herb(row: pd.Series | Mapping[str, object]) -> bool:
|
| 885 |
+
return bool(normalize_space(row.get("pinyin_name", ""))) and not any(
|
| 886 |
+
normalize_space(row.get(col, "")) for col in ["中文名", "别名", "Latin_name"]
|
| 887 |
+
)
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
def build_pinyin_manual_review_df(herb_df: pd.DataFrame, herb_resolution_df: pd.DataFrame) -> pd.DataFrame:
|
| 891 |
+
columns = [
|
| 892 |
+
"review_type",
|
| 893 |
+
"herb_id",
|
| 894 |
+
"pinyin_name",
|
| 895 |
+
"来源数据库",
|
| 896 |
+
"参考旧id",
|
| 897 |
+
"同拼音源记录数",
|
| 898 |
+
"同拼音来源数据库",
|
| 899 |
+
"同拼音中文名候选",
|
| 900 |
+
"同拼音别名候选",
|
| 901 |
+
"同拼音Latin候选",
|
| 902 |
+
"同拼音候选herb_id",
|
| 903 |
+
"同拼音源记录详情",
|
| 904 |
+
"人工复核建议",
|
| 905 |
+
]
|
| 906 |
+
if herb_df.empty:
|
| 907 |
+
return pd.DataFrame(columns=columns)
|
| 908 |
+
|
| 909 |
+
weak_df = herb_df[herb_df.apply(is_pinyin_only_weak_herb, axis=1)].copy()
|
| 910 |
+
if weak_df.empty:
|
| 911 |
+
return pd.DataFrame(columns=columns)
|
| 912 |
+
|
| 913 |
+
grouped_hints: dict[str, dict[str, object]] = {}
|
| 914 |
+
if not herb_resolution_df.empty:
|
| 915 |
+
resolution_df = herb_resolution_df.copy().fillna("")
|
| 916 |
+
resolution_df["pinyin_key"] = resolution_df["pinyin_name"].map(normalize_pinyin_for_compare)
|
| 917 |
+
known_info_mask = resolution_df.apply(
|
| 918 |
+
lambda row: any(normalize_space(row.get(col, "")) for col in ["中文名", "别名", "Latin_name"]),
|
| 919 |
+
axis=1,
|
| 920 |
+
)
|
| 921 |
+
resolution_df = resolution_df[(resolution_df["pinyin_key"] != "") & known_info_mask].copy()
|
| 922 |
+
for pinyin_key, sub in resolution_df.groupby("pinyin_key", sort=False):
|
| 923 |
+
details = []
|
| 924 |
+
for _, sub_row in sub.iterrows():
|
| 925 |
+
detail = " | ".join(
|
| 926 |
+
[
|
| 927 |
+
value
|
| 928 |
+
for value in [
|
| 929 |
+
normalize_space(sub_row.get("source_db", "")),
|
| 930 |
+
normalize_space(sub_row.get("source_kind", "")),
|
| 931 |
+
normalize_space(sub_row.get("source_code", "")),
|
| 932 |
+
normalize_space(sub_row.get("中文名", "")),
|
| 933 |
+
normalize_space(sub_row.get("别名", "")),
|
| 934 |
+
normalize_space(sub_row.get("Latin_name", "")),
|
| 935 |
+
normalize_space(sub_row.get("resolved_herb_id", "")),
|
| 936 |
+
]
|
| 937 |
+
if value
|
| 938 |
+
]
|
| 939 |
+
)
|
| 940 |
+
if detail:
|
| 941 |
+
details.append(detail)
|
| 942 |
+
grouped_hints[pinyin_key] = {
|
| 943 |
+
"同拼音源记录数": int(len(sub)),
|
| 944 |
+
"同拼音来源数据库": join_examples(sub["source_db"].tolist()),
|
| 945 |
+
"同拼音中文名候选": join_examples(sub["中文名"].tolist()),
|
| 946 |
+
"同拼音别名候选": join_examples(sub["别名"].tolist()),
|
| 947 |
+
"同拼音Latin候选": join_examples(sub["Latin_name"].tolist()),
|
| 948 |
+
"同拼音候选herb_id": join_examples(sub["resolved_herb_id"].tolist()),
|
| 949 |
+
"同拼音源记录详情": join_examples(details, limit=8),
|
| 950 |
+
}
|
| 951 |
+
|
| 952 |
+
rows = []
|
| 953 |
+
weak_df = weak_df.sort_values("Herb_id", key=lambda s: s.map(numeric_sort_key)).reset_index(drop=True)
|
| 954 |
+
for _, row in weak_df.iterrows():
|
| 955 |
+
pinyin_key = normalize_pinyin_for_compare(row["pinyin_name"])
|
| 956 |
+
hint = grouped_hints.get(pinyin_key, {})
|
| 957 |
+
has_exact_source_hit = bool(normalize_space(hint.get("同拼音候选herb_id", "")))
|
| 958 |
+
suggestion = (
|
| 959 |
+
"按同拼音源记录核对候选 herb_id;若确认是同一种中药,可并入候选 herb_id,并补全中文名/拉丁名。"
|
| 960 |
+
if has_exact_source_hit
|
| 961 |
+
else "源数据库未检到同拼音且带中文名/拉丁名的记录;建议回查原始数据库并人工更正拼音。"
|
| 962 |
+
)
|
| 963 |
+
rows.append(
|
| 964 |
+
{
|
| 965 |
+
"review_type": "pinyin_only_removed_from_final",
|
| 966 |
+
"herb_id": row["Herb_id"],
|
| 967 |
+
"pinyin_name": row["pinyin_name"],
|
| 968 |
+
"来源数据库": row.get("来源数据库", ""),
|
| 969 |
+
"参考旧id": row.get("参考旧id", ""),
|
| 970 |
+
"同拼音源记录数": hint.get("同拼音源记录数", 0),
|
| 971 |
+
"同拼音来源数据库": hint.get("同拼音来源数据库", ""),
|
| 972 |
+
"同拼音中文名候选": hint.get("同拼音中文名候选", ""),
|
| 973 |
+
"同拼音别名候选": hint.get("同拼音别名候选", ""),
|
| 974 |
+
"同拼音Latin候选": hint.get("同拼音Latin候选", ""),
|
| 975 |
+
"同拼音候选herb_id": hint.get("同拼音候选herb_id", ""),
|
| 976 |
+
"同拼音源记录详情": hint.get("同拼音源记录详情", ""),
|
| 977 |
+
"人工复核建议": suggestion,
|
| 978 |
+
}
|
| 979 |
+
)
|
| 980 |
+
|
| 981 |
+
return pd.DataFrame(rows, columns=columns)
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
class HerbLibrary:
|
| 985 |
+
def __init__(self, canonical_df: pd.DataFrame, old_to_new: dict[str, str]) -> None:
|
| 986 |
+
self.entries: dict[str, dict] = {}
|
| 987 |
+
self.reference_old_to_internal = old_to_new
|
| 988 |
+
self.ch_index: defaultdict[str, set[str]] = defaultdict(set)
|
| 989 |
+
self.pinyin_index: defaultdict[str, set[str]] = defaultdict(set)
|
| 990 |
+
self.source_pinyin_index: defaultdict[tuple[str, str], set[str]] = defaultdict(set)
|
| 991 |
+
self.latin_full_key_index: defaultdict[str, set[str]] = defaultdict(set)
|
| 992 |
+
self.latin_botanical_index: defaultdict[str, set[str]] = defaultdict(set)
|
| 993 |
+
self.stem_index: defaultdict[str, set[str]] = defaultdict(set)
|
| 994 |
+
self.next_num = next_id(canonical_df["Herb_id"].tolist(), "T", 6)
|
| 995 |
+
self.resolution_rows: list[dict] = []
|
| 996 |
+
self.review_rows: list[dict] = []
|
| 997 |
+
for row in canonical_df.to_dict("records"):
|
| 998 |
+
entry = empty_herb_entry(row["Herb_id"])
|
| 999 |
+
entry["中文名"] = row["中文名"]
|
| 1000 |
+
entry["别名"] = row["别名"]
|
| 1001 |
+
entry["pinyin_name"] = row["pinyin_name"]
|
| 1002 |
+
entry["Latin_name"] = row["Latin_name"]
|
| 1003 |
+
entry["中文名_variants"] = set(split_aliases(row["中文名_variants"])) if row["中文名_variants"] else set()
|
| 1004 |
+
if row["中文名"]:
|
| 1005 |
+
entry["中文名_variants"].add(row["中文名"])
|
| 1006 |
+
entry["别名_variants"] = set(split_aliases(row["别名"])) if row["别名"] else set()
|
| 1007 |
+
entry["pinyin_variants"] = set(split_aliases(row["pinyin_variants"])) if row["pinyin_variants"] else set()
|
| 1008 |
+
if row["pinyin_name"]:
|
| 1009 |
+
entry["pinyin_variants"].add(row["pinyin_name"])
|
| 1010 |
+
entry["Latin_variants"] = set(split_aliases(row["Latin_variants"])) if row["Latin_variants"] else set()
|
| 1011 |
+
if row["Latin_name"]:
|
| 1012 |
+
entry["Latin_variants"].add(row["Latin_name"])
|
| 1013 |
+
entry["merged_from_old_ids"] = set(split_aliases(row["merged_from_old_ids"])) if row["merged_from_old_ids"] else {row["Herb_id"]}
|
| 1014 |
+
entry["latin_part_signatures"] = latin_part_signatures(row["Latin_variants"])
|
| 1015 |
+
self.entries[row["Herb_id"]] = entry
|
| 1016 |
+
self.register_entry(row["Herb_id"])
|
| 1017 |
+
|
| 1018 |
+
def register_entry(self, herb_id: str) -> None:
|
| 1019 |
+
entry = self.entries[herb_id]
|
| 1020 |
+
chinese_candidates = set()
|
| 1021 |
+
for value in list(entry["中文名_variants"]) + list(entry["别名_variants"]) + [entry["中文名"], entry["别名"]]:
|
| 1022 |
+
chinese_candidates.update(normalize_chinese_candidate(value))
|
| 1023 |
+
for value in chinese_candidates:
|
| 1024 |
+
self.ch_index[value].add(herb_id)
|
| 1025 |
+
for value in list(entry["pinyin_variants"]) + [entry["pinyin_name"]]:
|
| 1026 |
+
key = normalize_pinyin_for_compare(value)
|
| 1027 |
+
if key:
|
| 1028 |
+
self.pinyin_index[key].add(herb_id)
|
| 1029 |
+
latin_values = list(entry["Latin_variants"]) + [entry["Latin_name"]]
|
| 1030 |
+
entry["latin_part_signatures"] = set()
|
| 1031 |
+
for value in latin_values:
|
| 1032 |
+
entry["latin_part_signatures"].update(latin_part_signatures(value))
|
| 1033 |
+
for key in latin_full_two_word_key_variants(value):
|
| 1034 |
+
self.latin_full_key_index[key].add(herb_id)
|
| 1035 |
+
for key in latin_botanical_two_word_key_variants(value):
|
| 1036 |
+
self.latin_botanical_index[key].add(herb_id)
|
| 1037 |
+
for stem in latin_stems_from_value(value):
|
| 1038 |
+
self.stem_index[stem].add(herb_id)
|
| 1039 |
+
|
| 1040 |
+
def new_herb_id(self) -> str:
|
| 1041 |
+
herb_id = f"T{self.next_num:06d}"
|
| 1042 |
+
self.next_num += 1
|
| 1043 |
+
return herb_id
|
| 1044 |
+
|
| 1045 |
+
def update_entry_from_source(self, herb_id: str, record: dict, review_reason: str = "") -> None:
|
| 1046 |
+
entry = self.entries[herb_id]
|
| 1047 |
+
chinese = normalize_space(record["中文名"])
|
| 1048 |
+
aliases = split_aliases(record["别名"])
|
| 1049 |
+
pinyin = normalize_space(record["pinyin_name"])
|
| 1050 |
+
latin = normalize_space(record["Latin_name"])
|
| 1051 |
+
if chinese:
|
| 1052 |
+
entry["中文名_variants"].add(chinese)
|
| 1053 |
+
if not entry["中文名"]:
|
| 1054 |
+
entry["中文名"] = chinese
|
| 1055 |
+
elif chinese != entry["中文名"]:
|
| 1056 |
+
entry["别名_variants"].add(chinese)
|
| 1057 |
+
for alias in aliases:
|
| 1058 |
+
if alias and alias != entry["中文名"]:
|
| 1059 |
+
entry["别名_variants"].add(alias)
|
| 1060 |
+
if pinyin:
|
| 1061 |
+
entry["pinyin_variants"].add(pinyin)
|
| 1062 |
+
if not entry["pinyin_name"]:
|
| 1063 |
+
entry["pinyin_name"] = pinyin
|
| 1064 |
+
if latin:
|
| 1065 |
+
entry["Latin_variants"].add(latin)
|
| 1066 |
+
if not entry["Latin_name"]:
|
| 1067 |
+
entry["Latin_name"] = latin
|
| 1068 |
+
if record["source_db"]:
|
| 1069 |
+
entry["来源数据库"].add(record["source_db"])
|
| 1070 |
+
pinyin_key = normalize_pinyin_for_compare(pinyin)
|
| 1071 |
+
if pinyin_key:
|
| 1072 |
+
self.source_pinyin_index[(record["source_db"], pinyin_key)].add(herb_id)
|
| 1073 |
+
if record["source_code"]:
|
| 1074 |
+
entry["source_codes"].add(f"{record['source_db']}:{record['source_code']}")
|
| 1075 |
+
entry["source_record_count"] += 1
|
| 1076 |
+
entry["source_records"].append(record["source_record_key"])
|
| 1077 |
+
if review_reason:
|
| 1078 |
+
entry["review_status"].add("needs_review")
|
| 1079 |
+
entry["review_reason"].add(review_reason)
|
| 1080 |
+
self.register_entry(herb_id)
|
| 1081 |
+
|
| 1082 |
+
def create_entry(self, record: dict, review_reason: str = "") -> str:
|
| 1083 |
+
herb_id = self.new_herb_id()
|
| 1084 |
+
entry = empty_herb_entry(herb_id)
|
| 1085 |
+
self.entries[herb_id] = entry
|
| 1086 |
+
return herb_id
|
| 1087 |
+
|
| 1088 |
+
def score_candidates(self, record: dict) -> tuple[list[tuple[str, int, list[str]]], dict[str, int]]:
|
| 1089 |
+
scores: Counter[str] = Counter()
|
| 1090 |
+
evidence: defaultdict[str, list[str]] = defaultdict(list)
|
| 1091 |
+
chinese_candidates = normalize_chinese_candidate(record["中文名"]) + normalize_chinese_candidate(record["别名"])
|
| 1092 |
+
seen_ch = set()
|
| 1093 |
+
for key in chinese_candidates:
|
| 1094 |
+
if not key or key in seen_ch:
|
| 1095 |
+
continue
|
| 1096 |
+
seen_ch.add(key)
|
| 1097 |
+
for herb_id in self.ch_index.get(key, set()):
|
| 1098 |
+
scores[herb_id] += 100
|
| 1099 |
+
evidence[herb_id].append(f"中文:{key}")
|
| 1100 |
+
pinyin_key = normalize_pinyin_for_compare(record["pinyin_name"])
|
| 1101 |
+
if pinyin_key:
|
| 1102 |
+
for herb_id in self.pinyin_index.get(pinyin_key, set()):
|
| 1103 |
+
scores[herb_id] += 20
|
| 1104 |
+
evidence[herb_id].append(f"拼音:{pinyin_key}")
|
| 1105 |
+
record_parts = latin_part_signatures(record["Latin_name"])
|
| 1106 |
+
for key in latin_full_two_word_key_variants(record["Latin_name"]):
|
| 1107 |
+
for herb_id in self.latin_full_key_index.get(key, set()):
|
| 1108 |
+
scores[herb_id] += 70
|
| 1109 |
+
evidence[herb_id].append(f"拉丁全键:{key}")
|
| 1110 |
+
for key in latin_botanical_two_word_key_variants(record["Latin_name"]):
|
| 1111 |
+
for herb_id in self.latin_botanical_index.get(key, set()):
|
| 1112 |
+
part_relation = latin_part_relation(record_parts, self.entries[herb_id].get("latin_part_signatures", {""}))
|
| 1113 |
+
if part_relation == "different":
|
| 1114 |
+
continue
|
| 1115 |
+
scores[herb_id] += 45 if part_relation == "same" else 20
|
| 1116 |
+
evidence[herb_id].append(f"拉丁植物键:{key}")
|
| 1117 |
+
stems = latin_stems_from_value(record["Latin_name"])
|
| 1118 |
+
for stem in stems:
|
| 1119 |
+
for herb_id in self.stem_index.get(stem, set()):
|
| 1120 |
+
part_relation = latin_part_relation(record_parts, self.entries[herb_id].get("latin_part_signatures", {""}))
|
| 1121 |
+
if part_relation == "different":
|
| 1122 |
+
continue
|
| 1123 |
+
scores[herb_id] += 5
|
| 1124 |
+
evidence[herb_id].append(f"词干:{stem}")
|
| 1125 |
+
ranked = [(herb_id, score, evidence[herb_id]) for herb_id, score in scores.items()]
|
| 1126 |
+
ranked.sort(key=lambda item: (-item[1], numeric_sort_key(item[0])))
|
| 1127 |
+
return ranked, scores
|
| 1128 |
+
|
| 1129 |
+
def resolve(self, record: dict) -> HerbResolution:
|
| 1130 |
+
pinyin_key = normalize_pinyin_for_compare(record["pinyin_name"])
|
| 1131 |
+
if not record["中文名"] and not record["Latin_name"] and pinyin_key:
|
| 1132 |
+
scoped_ids = self.source_pinyin_index.get((record["source_db"], pinyin_key), set())
|
| 1133 |
+
if len(scoped_ids) == 1:
|
| 1134 |
+
herb_id = next(iter(scoped_ids))
|
| 1135 |
+
return HerbResolution(herb_id, f"source_pinyin_exact:{record['source_db']}", "medium", "")
|
| 1136 |
+
|
| 1137 |
+
ranked, _ = self.score_candidates(record)
|
| 1138 |
+
if not ranked:
|
| 1139 |
+
review_reason = "new_from_source"
|
| 1140 |
+
if not record["中文名"] and not record["Latin_name"]:
|
| 1141 |
+
review_reason = "new_from_source_weak_name"
|
| 1142 |
+
herb_id = self.create_entry(record, review_reason if "weak" in review_reason else "")
|
| 1143 |
+
return HerbResolution(herb_id, "create_new", "new", review_reason)
|
| 1144 |
+
|
| 1145 |
+
top_id, top_score, top_evidence = ranked[0]
|
| 1146 |
+
second_score = ranked[1][1] if len(ranked) > 1 else 0
|
| 1147 |
+
if top_score >= 130 and top_score >= second_score + 20:
|
| 1148 |
+
return HerbResolution(top_id, "+".join(top_evidence), "high", "")
|
| 1149 |
+
if top_score >= 90 and top_score >= second_score + 25:
|
| 1150 |
+
return HerbResolution(top_id, "+".join(top_evidence), "medium", "")
|
| 1151 |
+
if top_score >= 60 and second_score == 0:
|
| 1152 |
+
return HerbResolution(top_id, "+".join(top_evidence), "low", "low_confidence_match")
|
| 1153 |
+
if top_score >= 100 and second_score < top_score and normalize_chinese_key(record["中文名"]):
|
| 1154 |
+
return HerbResolution(top_id, "+".join(top_evidence), "medium", "same_name_multiple_candidates")
|
| 1155 |
+
|
| 1156 |
+
candidate_ids = ";".join([item[0] for item in ranked[:5]])
|
| 1157 |
+
herb_id = self.create_entry(record, f"ambiguous_existing_candidates:{candidate_ids}")
|
| 1158 |
+
return HerbResolution(herb_id, "create_new_due_to_ambiguity", "new", f"ambiguous_existing_candidates:{candidate_ids}")
|
| 1159 |
+
|
| 1160 |
+
def match_only(self, record: dict) -> HerbResolution:
|
| 1161 |
+
pinyin_key = normalize_pinyin_for_compare(record["pinyin_name"])
|
| 1162 |
+
if not record["中文名"] and not record["Latin_name"] and pinyin_key:
|
| 1163 |
+
scoped_ids = self.source_pinyin_index.get((record["source_db"], pinyin_key), set())
|
| 1164 |
+
if len(scoped_ids) == 1:
|
| 1165 |
+
herb_id = next(iter(scoped_ids))
|
| 1166 |
+
return HerbResolution(herb_id, f"source_pinyin_exact:{record['source_db']}", "medium", "")
|
| 1167 |
+
|
| 1168 |
+
ranked, _ = self.score_candidates(record)
|
| 1169 |
+
if not ranked:
|
| 1170 |
+
return HerbResolution("", "unmatched", "", "unmatched_relation_herb")
|
| 1171 |
+
|
| 1172 |
+
top_id, top_score, top_evidence = ranked[0]
|
| 1173 |
+
second_score = ranked[1][1] if len(ranked) > 1 else 0
|
| 1174 |
+
if top_score >= 130 and top_score >= second_score + 20:
|
| 1175 |
+
return HerbResolution(top_id, "+".join(top_evidence), "high", "")
|
| 1176 |
+
if top_score >= 90 and top_score >= second_score + 25:
|
| 1177 |
+
return HerbResolution(top_id, "+".join(top_evidence), "medium", "")
|
| 1178 |
+
if top_score >= 60 and second_score == 0:
|
| 1179 |
+
return HerbResolution(top_id, "+".join(top_evidence), "low", "low_confidence_relation_match")
|
| 1180 |
+
if top_score >= 100 and second_score < top_score and normalize_chinese_key(record["中文名"]):
|
| 1181 |
+
return HerbResolution(top_id, "+".join(top_evidence), "medium", "same_name_multiple_candidates")
|
| 1182 |
+
candidate_ids = ";".join([item[0] for item in ranked[:5]])
|
| 1183 |
+
return HerbResolution("", "ambiguous", "", f"ambiguous_existing_candidates:{candidate_ids}")
|
| 1184 |
+
|
| 1185 |
+
def resolve_and_update(self, record: dict) -> HerbResolution:
|
| 1186 |
+
result = self.resolve(record)
|
| 1187 |
+
self.update_entry_from_source(result.herb_id, record, result.review_reason)
|
| 1188 |
+
self.resolution_rows.append(
|
| 1189 |
+
{
|
| 1190 |
+
"source_db": record["source_db"],
|
| 1191 |
+
"source_url": record.get("source_url", ""),
|
| 1192 |
+
"source_kind": record["source_kind"],
|
| 1193 |
+
"source_record_key": record["source_record_key"],
|
| 1194 |
+
"source_code": record["source_code"],
|
| 1195 |
+
"seed_herb_id": record["seed_herb_id"],
|
| 1196 |
+
"中文名": record["中文名"],
|
| 1197 |
+
"别名": record["别名"],
|
| 1198 |
+
"pinyin_name": record["pinyin_name"],
|
| 1199 |
+
"Latin_name": record["Latin_name"],
|
| 1200 |
+
"resolved_herb_id": result.herb_id,
|
| 1201 |
+
"method": result.method,
|
| 1202 |
+
"confidence": result.confidence,
|
| 1203 |
+
"review_reason": result.review_reason,
|
| 1204 |
+
}
|
| 1205 |
+
)
|
| 1206 |
+
if result.review_reason:
|
| 1207 |
+
self.review_rows.append(
|
| 1208 |
+
{
|
| 1209 |
+
"review_type": "source_herb_resolution",
|
| 1210 |
+
"source_db": record["source_db"],
|
| 1211 |
+
"source_url": record.get("source_url", ""),
|
| 1212 |
+
"source_kind": record["source_kind"],
|
| 1213 |
+
"source_record_key": record["source_record_key"],
|
| 1214 |
+
"source_code": record["source_code"],
|
| 1215 |
+
"resolved_herb_id": result.herb_id,
|
| 1216 |
+
"中文名": record["中文名"],
|
| 1217 |
+
"别名": record["别名"],
|
| 1218 |
+
"pinyin_name": record["pinyin_name"],
|
| 1219 |
+
"Latin_name": record["Latin_name"],
|
| 1220 |
+
"reason": result.review_reason,
|
| 1221 |
+
}
|
| 1222 |
+
)
|
| 1223 |
+
return result
|
| 1224 |
+
|
| 1225 |
+
def to_dataframe(self) -> pd.DataFrame:
|
| 1226 |
+
rows = []
|
| 1227 |
+
for herb_id in sorted(self.entries, key=numeric_sort_key):
|
| 1228 |
+
entry = self.entries[herb_id]
|
| 1229 |
+
chinese_variants = uniq_preserve([entry["中文名"]] + sorted(entry["中文名_variants"]))
|
| 1230 |
+
alias_values = sorted({value for value in entry["别名_variants"] if value and value != entry["中文名"]})
|
| 1231 |
+
rows.append(
|
| 1232 |
+
{
|
| 1233 |
+
"Herb_id": herb_id,
|
| 1234 |
+
"中文名": entry["中文名"],
|
| 1235 |
+
"别名": "、".join(alias_values),
|
| 1236 |
+
"pinyin_name": entry["pinyin_name"],
|
| 1237 |
+
"Latin_name": entry["Latin_name"],
|
| 1238 |
+
"中文名_variants": ";".join(chinese_variants),
|
| 1239 |
+
"pinyin_variants": ";".join(sorted(entry["pinyin_variants"])),
|
| 1240 |
+
"Latin_variants": ";".join(sorted(entry["Latin_variants"])),
|
| 1241 |
+
"来源数据库": ";".join(sorted(entry["来源数据库"])),
|
| 1242 |
+
"source_record_count": entry["source_record_count"],
|
| 1243 |
+
"merged_from_old_ids": ";".join(sorted(entry["merged_from_old_ids"], key=numeric_sort_key)),
|
| 1244 |
+
"source_codes": ";".join(sorted(entry["source_codes"])),
|
| 1245 |
+
"review_status": ";".join(sorted(entry["review_status"])),
|
| 1246 |
+
"review_reason": ";".join(sorted(entry["review_reason"])),
|
| 1247 |
+
}
|
| 1248 |
+
)
|
| 1249 |
+
return pd.DataFrame(rows)
|
| 1250 |
+
|
| 1251 |
+
def final_duplicate_reviews(self) -> list[dict]:
|
| 1252 |
+
rows = []
|
| 1253 |
+
df = self.to_dataframe()
|
| 1254 |
+
for column, review_type in [("中文名", "same_chinese_multiple_ids_final"), ("pinyin_name", "same_pinyin_multiple_ids_final"), ("Latin_name", "same_latin_multiple_ids_final")]:
|
| 1255 |
+
groups = df[df[column] != ""].groupby(column)["Herb_id"].apply(list)
|
| 1256 |
+
for key, herb_ids in groups.items():
|
| 1257 |
+
if len(herb_ids) > 1:
|
| 1258 |
+
rows.append(
|
| 1259 |
+
{
|
| 1260 |
+
"review_type": review_type,
|
| 1261 |
+
"key": key,
|
| 1262 |
+
"candidate_herb_ids": ";".join(sorted(herb_ids, key=numeric_sort_key)),
|
| 1263 |
+
}
|
| 1264 |
+
)
|
| 1265 |
+
return rows
|
| 1266 |
+
|
| 1267 |
+
|
| 1268 |
+
def standardize_herb_source_row(source_db: str, source_kind: str, row: pd.Series, config: dict, row_index: int) -> dict:
|
| 1269 |
+
return {
|
| 1270 |
+
"source_db": source_db,
|
| 1271 |
+
"source_url": SOURCE_URLS.get(source_db, ""),
|
| 1272 |
+
"source_kind": source_kind,
|
| 1273 |
+
"source_record_key": f"{source_kind}:{row_index}",
|
| 1274 |
+
"source_code": " | ".join([value for value in [first_nonempty(row, config.get("source_code", []))] if value]),
|
| 1275 |
+
"seed_herb_id": first_nonempty(row, config.get("seed_herb_id", [])),
|
| 1276 |
+
"中文名": first_nonempty(row, config.get("chinese", [])),
|
| 1277 |
+
"别名": first_nonempty(row, config.get("alias", [])),
|
| 1278 |
+
"pinyin_name": first_nonempty(row, config.get("pinyin", [])),
|
| 1279 |
+
"Latin_name": first_nonempty(row, config.get("latin", [])),
|
| 1280 |
+
}
|
| 1281 |
+
|
| 1282 |
+
|
| 1283 |
+
def collect_source_herb_records() -> list[dict]:
|
| 1284 |
+
records = []
|
| 1285 |
+
for source_db in SOURCE_ORDER:
|
| 1286 |
+
config = HERB_SOURCE_CONFIG[source_db]
|
| 1287 |
+
df = read_any_table(config["path"])
|
| 1288 |
+
for idx, row in df.iterrows():
|
| 1289 |
+
record = standardize_herb_source_row(source_db, "herb_table", row, config, idx)
|
| 1290 |
+
if any([record["中文名"], record["别名"], record["pinyin_name"], record["Latin_name"]]):
|
| 1291 |
+
records.append(record)
|
| 1292 |
+
|
| 1293 |
+
total_herbs = read_any_table(HERB_DIR / "总herbs.xlsx")
|
| 1294 |
+
for idx, row in total_herbs.iterrows():
|
| 1295 |
+
source_db = first_nonempty(row, ["来源"])
|
| 1296 |
+
record = {
|
| 1297 |
+
"source_db": source_db,
|
| 1298 |
+
"source_url": SOURCE_URLS.get(source_db, ""),
|
| 1299 |
+
"source_kind": "total_herbs",
|
| 1300 |
+
"source_record_key": f"total_herbs:{idx}",
|
| 1301 |
+
"source_code": "",
|
| 1302 |
+
"seed_herb_id": "",
|
| 1303 |
+
"中文名": first_nonempty(row, ["中文名"]),
|
| 1304 |
+
"别名": first_nonempty(row, ["别名"]),
|
| 1305 |
+
"pinyin_name": first_nonempty(row, ["pinyin_name"]),
|
| 1306 |
+
"Latin_name": first_nonempty(row, ["Latin_name"]),
|
| 1307 |
+
}
|
| 1308 |
+
if any([record["中文名"], record["别名"], record["pinyin_name"], record["Latin_name"]]):
|
| 1309 |
+
records.append(record)
|
| 1310 |
+
|
| 1311 |
+
for source_db in SOURCE_ORDER:
|
| 1312 |
+
config = RELATION_CONFIG[source_db]
|
| 1313 |
+
df = read_any_table(config["path"])
|
| 1314 |
+
unique_seen = set()
|
| 1315 |
+
for idx, row in df.iterrows():
|
| 1316 |
+
record = standardize_herb_source_row(source_db, "relation_herb_entity", row, config, idx)
|
| 1317 |
+
record["source_code"] = first_nonempty(row, config.get("source_herb_code", []))
|
| 1318 |
+
key = (
|
| 1319 |
+
record["source_db"],
|
| 1320 |
+
normalize_space(record["中文名"]),
|
| 1321 |
+
normalize_space(record["别名"]),
|
| 1322 |
+
normalize_space(record["pinyin_name"]),
|
| 1323 |
+
normalize_space(record["Latin_name"]),
|
| 1324 |
+
normalize_space(record["source_code"]),
|
| 1325 |
+
)
|
| 1326 |
+
if not any(key[2:6]) or key in unique_seen:
|
| 1327 |
+
continue
|
| 1328 |
+
unique_seen.add(key)
|
| 1329 |
+
records.append(record)
|
| 1330 |
+
|
| 1331 |
+
deduped = []
|
| 1332 |
+
seen = set()
|
| 1333 |
+
for record in records:
|
| 1334 |
+
key = (
|
| 1335 |
+
record["source_db"],
|
| 1336 |
+
record["source_kind"],
|
| 1337 |
+
normalize_space(record["中文名"]),
|
| 1338 |
+
normalize_space(record["别名"]),
|
| 1339 |
+
normalize_space(record["pinyin_name"]),
|
| 1340 |
+
normalize_space(record["Latin_name"]),
|
| 1341 |
+
normalize_space(record["source_code"]),
|
| 1342 |
+
)
|
| 1343 |
+
if key in seen:
|
| 1344 |
+
continue
|
| 1345 |
+
seen.add(key)
|
| 1346 |
+
deduped.append(record)
|
| 1347 |
+
|
| 1348 |
+
deduped.sort(
|
| 1349 |
+
key=lambda item: (
|
| 1350 |
+
0 if item["source_kind"] == "herb_table" else 1,
|
| 1351 |
+
0 if item["中文名"] else 1,
|
| 1352 |
+
0 if item["Latin_name"] else 1,
|
| 1353 |
+
0 if item["pinyin_name"] else 1,
|
| 1354 |
+
item["source_db"],
|
| 1355 |
+
item["source_kind"],
|
| 1356 |
+
)
|
| 1357 |
+
)
|
| 1358 |
+
return deduped
|
| 1359 |
+
|
| 1360 |
+
|
| 1361 |
+
class CompoundLibrary:
|
| 1362 |
+
def __init__(self, master_df: pd.DataFrame) -> None:
|
| 1363 |
+
self.entries: dict[str, dict] = {}
|
| 1364 |
+
self.inchi_index: defaultdict[str, set[str]] = defaultdict(set)
|
| 1365 |
+
self.std_inchikey_index: defaultdict[str, set[str]] = defaultdict(set)
|
| 1366 |
+
self.inchikey_index: defaultdict[str, set[str]] = defaultdict(set)
|
| 1367 |
+
self.pubchem_index: defaultdict[str, set[str]] = defaultdict(set)
|
| 1368 |
+
self.name_index: defaultdict[str, set[str]] = defaultdict(set)
|
| 1369 |
+
self.next_num = next_id(master_df["compound_id"].tolist(), "C", 6)
|
| 1370 |
+
self.review_rows: list[dict] = []
|
| 1371 |
+
self.resolution_rows: list[dict] = []
|
| 1372 |
+
|
| 1373 |
+
for row in master_df.to_dict("records"):
|
| 1374 |
+
entry = {
|
| 1375 |
+
"compound_id": row["compound_id"],
|
| 1376 |
+
"pubchem_cid": normalize_pubchem(row.get("pubchem_cid", "")),
|
| 1377 |
+
"name": normalize_space(row.get("name", "")),
|
| 1378 |
+
"molecular_formula": normalize_space(row.get("molecular_formula", "")),
|
| 1379 |
+
"smiles": normalize_space(row.get("smiles", "")),
|
| 1380 |
+
"average_weight": normalize_space(row.get("average_weight", "")),
|
| 1381 |
+
"inchi": normalize_inchi(row.get("inchi", "")),
|
| 1382 |
+
"inchikey": normalize_inchikey(row.get("inchikey", "")),
|
| 1383 |
+
"cas": normalize_space(row.get("cas", "")),
|
| 1384 |
+
"standard_inchikey": normalize_inchikey(row.get("standard_inchikey", "")) or normalize_inchikey(row.get("inchikey", "")),
|
| 1385 |
+
"skeleton_key": normalize_space(row.get("skeleton_key", "")),
|
| 1386 |
+
"is_duplicate": normalize_space(row.get("is_duplicate", "")) or "False",
|
| 1387 |
+
"来源数据库": set(),
|
| 1388 |
+
"source_record_count": 0,
|
| 1389 |
+
"is_new_from_source": False,
|
| 1390 |
+
"review_status": set(),
|
| 1391 |
+
"review_reason": set(),
|
| 1392 |
+
}
|
| 1393 |
+
if not entry["skeleton_key"] and entry["standard_inchikey"]:
|
| 1394 |
+
entry["skeleton_key"] = entry["standard_inchikey"].split("-")[0]
|
| 1395 |
+
self.entries[entry["compound_id"]] = entry
|
| 1396 |
+
self.register_entry(entry["compound_id"])
|
| 1397 |
+
|
| 1398 |
+
self.review_rows.extend(self.master_anomaly_reviews())
|
| 1399 |
+
|
| 1400 |
+
def register_entry(self, compound_id: str) -> None:
|
| 1401 |
+
entry = self.entries[compound_id]
|
| 1402 |
+
if entry["inchi"]:
|
| 1403 |
+
self.inchi_index[entry["inchi"]].add(compound_id)
|
| 1404 |
+
if entry["standard_inchikey"]:
|
| 1405 |
+
self.std_inchikey_index[entry["standard_inchikey"]].add(compound_id)
|
| 1406 |
+
if entry["inchikey"]:
|
| 1407 |
+
self.inchikey_index[entry["inchikey"]].add(compound_id)
|
| 1408 |
+
if entry["pubchem_cid"]:
|
| 1409 |
+
self.pubchem_index[entry["pubchem_cid"]].add(compound_id)
|
| 1410 |
+
name_key = standardize_text_key(entry["name"])
|
| 1411 |
+
if name_key:
|
| 1412 |
+
self.name_index[name_key].add(compound_id)
|
| 1413 |
+
|
| 1414 |
+
def new_compound_id(self) -> str:
|
| 1415 |
+
compound_id = f"C{self.next_num:06d}"
|
| 1416 |
+
self.next_num += 1
|
| 1417 |
+
return compound_id
|
| 1418 |
+
|
| 1419 |
+
def master_anomaly_reviews(self) -> list[dict]:
|
| 1420 |
+
rows = []
|
| 1421 |
+
for field_name, index in [("pubchem_cid", self.pubchem_index), ("inchikey", self.inchikey_index)]:
|
| 1422 |
+
for value, compound_ids in index.items():
|
| 1423 |
+
if value and len(compound_ids) > 1:
|
| 1424 |
+
rows.append(
|
| 1425 |
+
{
|
| 1426 |
+
"review_type": "master_duplicate_identifier",
|
| 1427 |
+
"field": field_name,
|
| 1428 |
+
"value": value,
|
| 1429 |
+
"compound_ids": ";".join(sorted(compound_ids, key=numeric_sort_key)),
|
| 1430 |
+
}
|
| 1431 |
+
)
|
| 1432 |
+
return rows
|
| 1433 |
+
|
| 1434 |
+
def candidate_from_identifier(self, identifier: str, index: defaultdict[str, set[str]]) -> str:
|
| 1435 |
+
ids = index.get(identifier, set())
|
| 1436 |
+
if len(ids) == 1:
|
| 1437 |
+
return next(iter(ids))
|
| 1438 |
+
return ""
|
| 1439 |
+
|
| 1440 |
+
def refine_by_name(self, ids: set[str], name: str) -> str:
|
| 1441 |
+
if not ids or not name:
|
| 1442 |
+
return ""
|
| 1443 |
+
name_key = standardize_text_key(name)
|
| 1444 |
+
matches = [compound_id for compound_id in ids if standardize_text_key(self.entries[compound_id]["name"]) == name_key]
|
| 1445 |
+
if len(matches) == 1:
|
| 1446 |
+
return matches[0]
|
| 1447 |
+
return ""
|
| 1448 |
+
|
| 1449 |
+
def update_entry_from_source(self, compound_id: str, info: dict, source_db: str, review_reason: str = "") -> None:
|
| 1450 |
+
entry = self.entries[compound_id]
|
| 1451 |
+
for field in ["pubchem_cid", "name", "molecular_formula", "smiles", "average_weight", "inchi", "inchikey", "cas", "standard_inchikey", "skeleton_key"]:
|
| 1452 |
+
if not entry.get(field) and info.get(field):
|
| 1453 |
+
entry[field] = info[field]
|
| 1454 |
+
if source_db:
|
| 1455 |
+
entry["来源数据库"].add(source_db)
|
| 1456 |
+
entry["source_record_count"] += 1
|
| 1457 |
+
if review_reason:
|
| 1458 |
+
entry["review_status"].add("needs_review")
|
| 1459 |
+
entry["review_reason"].add(review_reason)
|
| 1460 |
+
self.register_entry(compound_id)
|
| 1461 |
+
|
| 1462 |
+
def create_entry(self, info: dict, source_db: str, review_reason: str = "") -> str:
|
| 1463 |
+
compound_id = self.new_compound_id()
|
| 1464 |
+
entry = {
|
| 1465 |
+
"compound_id": compound_id,
|
| 1466 |
+
"pubchem_cid": info["pubchem_cid"],
|
| 1467 |
+
"name": info["name"],
|
| 1468 |
+
"molecular_formula": info["molecular_formula"],
|
| 1469 |
+
"smiles": info["smiles"],
|
| 1470 |
+
"average_weight": info["average_weight"],
|
| 1471 |
+
"inchi": info["inchi"],
|
| 1472 |
+
"inchikey": info["inchikey"],
|
| 1473 |
+
"cas": info["cas"],
|
| 1474 |
+
"standard_inchikey": info["standard_inchikey"],
|
| 1475 |
+
"skeleton_key": info["skeleton_key"],
|
| 1476 |
+
"is_duplicate": "False",
|
| 1477 |
+
"来源数据库": {source_db} if source_db else set(),
|
| 1478 |
+
"source_record_count": 1,
|
| 1479 |
+
"is_new_from_source": True,
|
| 1480 |
+
"review_status": {"needs_review"} if review_reason else set(),
|
| 1481 |
+
"review_reason": {review_reason} if review_reason else set(),
|
| 1482 |
+
}
|
| 1483 |
+
self.entries[compound_id] = entry
|
| 1484 |
+
self.register_entry(compound_id)
|
| 1485 |
+
return compound_id
|
| 1486 |
+
|
| 1487 |
+
def standardized_source_compound(self, row: pd.Series, config: dict) -> dict:
|
| 1488 |
+
raw_name = normalize_space(first_nonempty(row, config.get("name", [])))
|
| 1489 |
+
derived = derive_compound_fields_from_name(raw_name)
|
| 1490 |
+
inchikey = normalize_inchikey(first_nonempty(row, config.get("inchikey", [])) or derived.get("inchikey", ""))
|
| 1491 |
+
standard_inchikey = normalize_inchikey(derived.get("standard_inchikey", inchikey))
|
| 1492 |
+
info = {
|
| 1493 |
+
"compound_id": first_nonempty(row, config.get("compound_id", [])),
|
| 1494 |
+
"pubchem_cid": normalize_pubchem(first_nonempty(row, config.get("pubchem", []))),
|
| 1495 |
+
"name": raw_name,
|
| 1496 |
+
"molecular_formula": normalize_space(first_nonempty(row, config.get("formula", [])) or derived.get("molecular_formula", "")),
|
| 1497 |
+
"smiles": normalize_space(first_nonempty(row, config.get("smiles", [])) or derived.get("smiles", "")),
|
| 1498 |
+
"average_weight": normalize_space(first_nonempty(row, config.get("weight", [])) or derived.get("average_weight", "")),
|
| 1499 |
+
"inchi": normalize_inchi(first_nonempty(row, config.get("inchi", [])) or derived.get("inchi", "")),
|
| 1500 |
+
"inchikey": inchikey,
|
| 1501 |
+
"cas": normalize_cas(first_nonempty(row, config.get("cas", [])) or derived.get("cas", "")),
|
| 1502 |
+
"standard_inchikey": standard_inchikey,
|
| 1503 |
+
"skeleton_key": normalize_space(derived.get("skeleton_key", inchikey.split("-")[0] if inchikey else "")),
|
| 1504 |
+
"derived_from_name_type": derived.get("derived_from_name_type", ""),
|
| 1505 |
+
}
|
| 1506 |
+
return info
|
| 1507 |
+
|
| 1508 |
+
def resolve(self, info: dict, source_db: str) -> tuple[str, str, str]:
|
| 1509 |
+
explicit_id = normalize_space(info["compound_id"])
|
| 1510 |
+
if explicit_id and explicit_id in self.entries:
|
| 1511 |
+
self.update_entry_from_source(explicit_id, info, source_db)
|
| 1512 |
+
return explicit_id, "existing_compound_id", ""
|
| 1513 |
+
|
| 1514 |
+
if info["inchi"]:
|
| 1515 |
+
match_id = self.candidate_from_identifier(info["inchi"], self.inchi_index)
|
| 1516 |
+
if match_id:
|
| 1517 |
+
self.update_entry_from_source(match_id, info, source_db)
|
| 1518 |
+
return match_id, "inchi", ""
|
| 1519 |
+
if info["standard_inchikey"]:
|
| 1520 |
+
match_id = self.candidate_from_identifier(info["standard_inchikey"], self.std_inchikey_index)
|
| 1521 |
+
if match_id:
|
| 1522 |
+
self.update_entry_from_source(match_id, info, source_db)
|
| 1523 |
+
return match_id, "standard_inchikey", ""
|
| 1524 |
+
if info["inchikey"]:
|
| 1525 |
+
ids = self.inchikey_index.get(info["inchikey"], set())
|
| 1526 |
+
if len(ids) == 1:
|
| 1527 |
+
match_id = next(iter(ids))
|
| 1528 |
+
self.update_entry_from_source(match_id, info, source_db)
|
| 1529 |
+
return match_id, "inchikey", ""
|
| 1530 |
+
refined = self.refine_by_name(ids, info["name"])
|
| 1531 |
+
if refined:
|
| 1532 |
+
self.update_entry_from_source(refined, info, source_db)
|
| 1533 |
+
return refined, "inchikey+name", ""
|
| 1534 |
+
if len(ids) > 1 and not info["inchi"]:
|
| 1535 |
+
return "", "unresolved", "ambiguous_existing_inchikey"
|
| 1536 |
+
if info["pubchem_cid"]:
|
| 1537 |
+
ids = self.pubchem_index.get(info["pubchem_cid"], set())
|
| 1538 |
+
if len(ids) == 1:
|
| 1539 |
+
match_id = next(iter(ids))
|
| 1540 |
+
self.update_entry_from_source(match_id, info, source_db)
|
| 1541 |
+
return match_id, "pubchem_cid", ""
|
| 1542 |
+
refined = self.refine_by_name(ids, info["name"])
|
| 1543 |
+
if refined:
|
| 1544 |
+
self.update_entry_from_source(refined, info, source_db)
|
| 1545 |
+
return refined, "pubchem_cid+name", ""
|
| 1546 |
+
if len(ids) > 1 and not any([info["inchi"], info["standard_inchikey"], info["inchikey"]]):
|
| 1547 |
+
return "", "unresolved", "ambiguous_existing_pubchem"
|
| 1548 |
+
if info["name"]:
|
| 1549 |
+
ids = self.name_index.get(standardize_text_key(info["name"]), set())
|
| 1550 |
+
if len(ids) == 1:
|
| 1551 |
+
match_id = next(iter(ids))
|
| 1552 |
+
self.update_entry_from_source(match_id, info, source_db, "name_only_match")
|
| 1553 |
+
return match_id, "name_only", "name_only_match"
|
| 1554 |
+
|
| 1555 |
+
if any([info["inchi"], info["standard_inchikey"], info["inchikey"], info["pubchem_cid"]]):
|
| 1556 |
+
review_reason = ""
|
| 1557 |
+
new_id = self.create_entry(info, source_db, review_reason)
|
| 1558 |
+
return new_id, "create_new", review_reason
|
| 1559 |
+
if info["name"]:
|
| 1560 |
+
return "", "unresolved", "name_only_unmatched"
|
| 1561 |
+
|
| 1562 |
+
return "", "unresolved", "missing_compound_identifiers"
|
| 1563 |
+
|
| 1564 |
+
def to_dataframe(self) -> pd.DataFrame:
|
| 1565 |
+
rows = []
|
| 1566 |
+
for compound_id in sorted(self.entries, key=numeric_sort_key):
|
| 1567 |
+
entry = self.entries[compound_id]
|
| 1568 |
+
rows.append(
|
| 1569 |
+
{
|
| 1570 |
+
"compound_id": compound_id,
|
| 1571 |
+
"pubchem_cid": entry["pubchem_cid"],
|
| 1572 |
+
"name": entry["name"],
|
| 1573 |
+
"molecular_formula": entry["molecular_formula"],
|
| 1574 |
+
"smiles": entry["smiles"],
|
| 1575 |
+
"average_weight": entry["average_weight"],
|
| 1576 |
+
"inchi": entry["inchi"],
|
| 1577 |
+
"inchikey": entry["inchikey"],
|
| 1578 |
+
"cas": entry["cas"],
|
| 1579 |
+
"standard_inchikey": entry["standard_inchikey"],
|
| 1580 |
+
"skeleton_key": entry["skeleton_key"],
|
| 1581 |
+
"is_duplicate": entry["is_duplicate"],
|
| 1582 |
+
"来源数据库": ";".join(sorted(entry["来源数据库"])),
|
| 1583 |
+
"source_record_count": entry["source_record_count"],
|
| 1584 |
+
"is_new_from_source": entry["is_new_from_source"],
|
| 1585 |
+
"review_status": ";".join(sorted(entry["review_status"])),
|
| 1586 |
+
"review_reason": ";".join(sorted(entry["review_reason"])),
|
| 1587 |
+
}
|
| 1588 |
+
)
|
| 1589 |
+
return pd.DataFrame(rows)
|
| 1590 |
+
|
| 1591 |
+
|
| 1592 |
+
def resolve_relation_herb_id(row: pd.Series, source_db: str, library: HerbLibrary) -> tuple[str, str, str]:
|
| 1593 |
+
config = RELATION_CONFIG[source_db]
|
| 1594 |
+
record = standardize_herb_source_row(source_db, "relation_row", row, config, int(row.name))
|
| 1595 |
+
record["source_code"] = first_nonempty(row, config.get("source_herb_code", []))
|
| 1596 |
+
result = library.match_only(record)
|
| 1597 |
+
return result.herb_id, result.method, result.review_reason
|
| 1598 |
+
|
| 1599 |
+
|
| 1600 |
+
def build_relations_and_compounds(library: HerbLibrary) -> tuple[pd.DataFrame, CompoundLibrary, pd.DataFrame, pd.DataFrame]:
|
| 1601 |
+
master_compounds = read_any_table(BASE_DIR / "compounds_final.xlsx")
|
| 1602 |
+
compounds = CompoundLibrary(master_compounds)
|
| 1603 |
+
valid_compound_ids = set(compounds.entries)
|
| 1604 |
+
resolved_frames = []
|
| 1605 |
+
unresolved_frames = []
|
| 1606 |
+
source_summary = []
|
| 1607 |
+
|
| 1608 |
+
for source_db in SOURCE_ORDER:
|
| 1609 |
+
config = RELATION_CONFIG[source_db]
|
| 1610 |
+
df = read_any_table(config["path"])
|
| 1611 |
+
rel = pd.DataFrame(
|
| 1612 |
+
{
|
| 1613 |
+
"source_db": source_db,
|
| 1614 |
+
"source_url": SOURCE_URLS.get(source_db, ""),
|
| 1615 |
+
"source_row": df.index.astype(int),
|
| 1616 |
+
"seed_herb_id": coalesce_series(df, config.get("seed_herb_id", [])).map(normalize_herb_id),
|
| 1617 |
+
"source_中文名": coalesce_series(df, config.get("chinese", [])),
|
| 1618 |
+
"source_pinyin_name": coalesce_series(df, config.get("pinyin", [])),
|
| 1619 |
+
"source_Latin_name": coalesce_series(df, config.get("latin", [])),
|
| 1620 |
+
"compound_id_seed": coalesce_series(df, config.get("compound_id", [])),
|
| 1621 |
+
"source_compound_name": coalesce_series(df, config.get("name", [])),
|
| 1622 |
+
"pubchem_cid": coalesce_series(df, config.get("pubchem", [])).map(normalize_pubchem),
|
| 1623 |
+
"molecular_formula": coalesce_series(df, config.get("formula", [])),
|
| 1624 |
+
"smiles": coalesce_series(df, config.get("smiles", [])),
|
| 1625 |
+
"average_weight": coalesce_series(df, config.get("weight", [])),
|
| 1626 |
+
"inchi": coalesce_series(df, config.get("inchi", [])).map(normalize_inchi),
|
| 1627 |
+
"inchikey": coalesce_series(df, config.get("inchikey", [])).map(normalize_inchikey),
|
| 1628 |
+
"cas": coalesce_series(df, config.get("cas", [])),
|
| 1629 |
+
}
|
| 1630 |
+
)
|
| 1631 |
+
rel["Herb_id"] = rel["seed_herb_id"].map(lambda value: library.reference_old_to_internal.get(value, "") if value else "")
|
| 1632 |
+
rel["herb_method"] = rel["Herb_id"].map(lambda value: "seed_herb_id_reference_map" if value else "")
|
| 1633 |
+
rel["herb_review_reason"] = ""
|
| 1634 |
+
|
| 1635 |
+
unresolved_herb_mask = rel["Herb_id"] == ""
|
| 1636 |
+
if unresolved_herb_mask.any():
|
| 1637 |
+
herb_subset = rel.loc[unresolved_herb_mask, ["source_中文名", "source_pinyin_name", "source_Latin_name"]].drop_duplicates().copy()
|
| 1638 |
+
herb_subset["Herb_id"] = ""
|
| 1639 |
+
herb_subset["herb_method"] = ""
|
| 1640 |
+
herb_subset["herb_review_reason"] = ""
|
| 1641 |
+
for idx, herb_row in herb_subset.iterrows():
|
| 1642 |
+
result = library.match_only(
|
| 1643 |
+
{
|
| 1644 |
+
"source_db": source_db,
|
| 1645 |
+
"source_url": SOURCE_URLS.get(source_db, ""),
|
| 1646 |
+
"source_kind": "relation_row",
|
| 1647 |
+
"source_record_key": f"relation_row:{idx}",
|
| 1648 |
+
"source_code": "",
|
| 1649 |
+
"seed_herb_id": "",
|
| 1650 |
+
"中文名": herb_row["source_中文名"],
|
| 1651 |
+
"别名": "",
|
| 1652 |
+
"pinyin_name": herb_row["source_pinyin_name"],
|
| 1653 |
+
"Latin_name": herb_row["source_Latin_name"],
|
| 1654 |
+
}
|
| 1655 |
+
)
|
| 1656 |
+
herb_subset.at[idx, "Herb_id"] = result.herb_id
|
| 1657 |
+
herb_subset.at[idx, "herb_method"] = result.method
|
| 1658 |
+
herb_subset.at[idx, "herb_review_reason"] = result.review_reason
|
| 1659 |
+
rel = rel.merge(
|
| 1660 |
+
herb_subset,
|
| 1661 |
+
on=["source_中文名", "source_pinyin_name", "source_Latin_name"],
|
| 1662 |
+
how="left",
|
| 1663 |
+
suffixes=("", "_matched"),
|
| 1664 |
+
)
|
| 1665 |
+
rel.loc[unresolved_herb_mask, "Herb_id"] = rel.loc[unresolved_herb_mask, "Herb_id_matched"].fillna("")
|
| 1666 |
+
rel.loc[unresolved_herb_mask, "herb_method"] = rel.loc[unresolved_herb_mask, "herb_method_matched"].fillna("")
|
| 1667 |
+
rel.loc[unresolved_herb_mask, "herb_review_reason"] = rel.loc[unresolved_herb_mask, "herb_review_reason_matched"].fillna("")
|
| 1668 |
+
rel = rel.drop(columns=["Herb_id_matched", "herb_method_matched", "herb_review_reason_matched"])
|
| 1669 |
+
|
| 1670 |
+
rel["compound_id"] = rel["compound_id_seed"].where(rel["compound_id_seed"].isin(valid_compound_ids), "")
|
| 1671 |
+
rel["compound_method"] = rel["compound_id"].map(lambda value: "existing_compound_id" if value else "")
|
| 1672 |
+
rel["compound_review_reason"] = ""
|
| 1673 |
+
|
| 1674 |
+
unresolved_compound_mask = rel["compound_id"] == ""
|
| 1675 |
+
if unresolved_compound_mask.any():
|
| 1676 |
+
compound_cols = [
|
| 1677 |
+
"source_compound_name",
|
| 1678 |
+
"pubchem_cid",
|
| 1679 |
+
"molecular_formula",
|
| 1680 |
+
"smiles",
|
| 1681 |
+
"average_weight",
|
| 1682 |
+
"inchi",
|
| 1683 |
+
"inchikey",
|
| 1684 |
+
"cas",
|
| 1685 |
+
]
|
| 1686 |
+
compound_subset = rel.loc[unresolved_compound_mask, compound_cols].drop_duplicates().copy()
|
| 1687 |
+
compound_subset["compound_id"] = ""
|
| 1688 |
+
compound_subset["compound_method"] = ""
|
| 1689 |
+
compound_subset["compound_review_reason"] = ""
|
| 1690 |
+
for idx, cmp_row in compound_subset.iterrows():
|
| 1691 |
+
info = {
|
| 1692 |
+
"compound_id": "",
|
| 1693 |
+
"pubchem_cid": cmp_row["pubchem_cid"],
|
| 1694 |
+
"name": cmp_row["source_compound_name"],
|
| 1695 |
+
"molecular_formula": cmp_row["molecular_formula"],
|
| 1696 |
+
"smiles": cmp_row["smiles"],
|
| 1697 |
+
"average_weight": cmp_row["average_weight"],
|
| 1698 |
+
"inchi": cmp_row["inchi"],
|
| 1699 |
+
"inchikey": cmp_row["inchikey"],
|
| 1700 |
+
"cas": cmp_row["cas"],
|
| 1701 |
+
"standard_inchikey": cmp_row["inchikey"],
|
| 1702 |
+
"skeleton_key": cmp_row["inchikey"].split("-")[0] if cmp_row["inchikey"] else "",
|
| 1703 |
+
}
|
| 1704 |
+
compound_id, method, review_reason = compounds.resolve(info, source_db)
|
| 1705 |
+
compound_subset.at[idx, "compound_id"] = compound_id
|
| 1706 |
+
compound_subset.at[idx, "compound_method"] = method
|
| 1707 |
+
compound_subset.at[idx, "compound_review_reason"] = review_reason
|
| 1708 |
+
compounds.resolution_rows.append(
|
| 1709 |
+
{
|
| 1710 |
+
"source_db": source_db,
|
| 1711 |
+
"source_row": idx,
|
| 1712 |
+
"resolved_compound_id": compound_id,
|
| 1713 |
+
"method": method,
|
| 1714 |
+
"review_reason": review_reason,
|
| 1715 |
+
"derived_from_name_type": info.get("derived_from_name_type", ""),
|
| 1716 |
+
"pubchem_cid": info["pubchem_cid"],
|
| 1717 |
+
"name": info["name"],
|
| 1718 |
+
"inchi": info["inchi"],
|
| 1719 |
+
"inchikey": info["inchikey"],
|
| 1720 |
+
}
|
| 1721 |
+
)
|
| 1722 |
+
if compound_id:
|
| 1723 |
+
valid_compound_ids.add(compound_id)
|
| 1724 |
+
rel = rel.merge(compound_subset, on=compound_cols, how="left", suffixes=("", "_matched"))
|
| 1725 |
+
rel.loc[unresolved_compound_mask, "compound_id"] = rel.loc[unresolved_compound_mask, "compound_id_matched"].fillna("")
|
| 1726 |
+
rel.loc[unresolved_compound_mask, "compound_method"] = rel.loc[unresolved_compound_mask, "compound_method_matched"].fillna("")
|
| 1727 |
+
rel.loc[unresolved_compound_mask, "compound_review_reason"] = rel.loc[unresolved_compound_mask, "compound_review_reason_matched"].fillna("")
|
| 1728 |
+
rel = rel.drop(columns=["compound_id_matched", "compound_method_matched", "compound_review_reason_matched"])
|
| 1729 |
+
|
| 1730 |
+
resolved_mask = (rel["Herb_id"] != "") & (rel["compound_id"] != "")
|
| 1731 |
+
resolved_relation_count = int(resolved_mask.sum())
|
| 1732 |
+
unresolved_relation_count = int((~resolved_mask).sum())
|
| 1733 |
+
if resolved_relation_count:
|
| 1734 |
+
resolved_frames.append(
|
| 1735 |
+
rel.loc[
|
| 1736 |
+
resolved_mask,
|
| 1737 |
+
[
|
| 1738 |
+
"source_db",
|
| 1739 |
+
"source_url",
|
| 1740 |
+
"source_row",
|
| 1741 |
+
"Herb_id",
|
| 1742 |
+
"compound_id",
|
| 1743 |
+
"source_中文名",
|
| 1744 |
+
"source_pinyin_name",
|
| 1745 |
+
"source_Latin_name",
|
| 1746 |
+
"source_compound_name",
|
| 1747 |
+
"herb_method",
|
| 1748 |
+
"compound_method",
|
| 1749 |
+
],
|
| 1750 |
+
].copy()
|
| 1751 |
+
)
|
| 1752 |
+
if unresolved_relation_count:
|
| 1753 |
+
unresolved_frames.append(
|
| 1754 |
+
rel.loc[
|
| 1755 |
+
~resolved_mask,
|
| 1756 |
+
[
|
| 1757 |
+
"source_db",
|
| 1758 |
+
"source_url",
|
| 1759 |
+
"source_row",
|
| 1760 |
+
"seed_herb_id",
|
| 1761 |
+
"source_中文名",
|
| 1762 |
+
"source_pinyin_name",
|
| 1763 |
+
"source_Latin_name",
|
| 1764 |
+
"source_compound_name",
|
| 1765 |
+
"pubchem_cid",
|
| 1766 |
+
"inchi",
|
| 1767 |
+
"inchikey",
|
| 1768 |
+
"Herb_id",
|
| 1769 |
+
"compound_id",
|
| 1770 |
+
"herb_review_reason",
|
| 1771 |
+
"compound_review_reason",
|
| 1772 |
+
],
|
| 1773 |
+
].rename(columns={"Herb_id": "resolved_herb_id", "compound_id": "resolved_compound_id"}).copy()
|
| 1774 |
+
)
|
| 1775 |
+
source_summary.append(
|
| 1776 |
+
{
|
| 1777 |
+
"source_db": source_db,
|
| 1778 |
+
"source_url": SOURCE_URLS.get(source_db, ""),
|
| 1779 |
+
"relation_rows": len(df),
|
| 1780 |
+
"resolved_relation_rows": resolved_relation_count,
|
| 1781 |
+
"unresolved_relation_rows": unresolved_relation_count,
|
| 1782 |
+
}
|
| 1783 |
+
)
|
| 1784 |
+
|
| 1785 |
+
relation_df = pd.concat(resolved_frames, ignore_index=True) if resolved_frames else pd.DataFrame()
|
| 1786 |
+
unresolved_df = pd.concat(unresolved_frames, ignore_index=True) if unresolved_frames else pd.DataFrame()
|
| 1787 |
+
if relation_df.empty:
|
| 1788 |
+
return relation_df, compounds, unresolved_df, pd.DataFrame(source_summary)
|
| 1789 |
+
|
| 1790 |
+
for entry in compounds.entries.values():
|
| 1791 |
+
entry["来源数据库"] = set()
|
| 1792 |
+
entry["source_record_count"] = 0
|
| 1793 |
+
usage = relation_df.groupby("compound_id")["source_db"].agg(list)
|
| 1794 |
+
count_usage = relation_df.groupby("compound_id").size()
|
| 1795 |
+
for compound_id, dbs in usage.items():
|
| 1796 |
+
if compound_id in compounds.entries:
|
| 1797 |
+
compounds.entries[compound_id]["来源数据库"] = set(dbs)
|
| 1798 |
+
compounds.entries[compound_id]["source_record_count"] = int(count_usage[compound_id])
|
| 1799 |
+
|
| 1800 |
+
herb_df = library.to_dataframe().set_index("Herb_id")
|
| 1801 |
+
compound_df = compounds.to_dataframe().set_index("compound_id")
|
| 1802 |
+
|
| 1803 |
+
relation_unique = relation_df[["Herb_id", "compound_id", "source_db"]].drop_duplicates().copy()
|
| 1804 |
+
relation_unique["flag"] = CHECKMARK
|
| 1805 |
+
pivot = relation_unique.pivot_table(
|
| 1806 |
+
index=["Herb_id", "compound_id"],
|
| 1807 |
+
columns="source_db",
|
| 1808 |
+
values="flag",
|
| 1809 |
+
aggfunc="first",
|
| 1810 |
+
fill_value="",
|
| 1811 |
+
).reset_index()
|
| 1812 |
+
for source_name in SOURCE_ORDER:
|
| 1813 |
+
if source_name not in pivot.columns:
|
| 1814 |
+
pivot[source_name] = ""
|
| 1815 |
+
|
| 1816 |
+
pivot = pivot.merge(herb_df[["中文名", "pinyin_name", "Latin_name"]], left_on="Herb_id", right_index=True, how="left")
|
| 1817 |
+
pivot = pivot.merge(compound_df[["name", "pubchem_cid"]], left_on="compound_id", right_index=True, how="left")
|
| 1818 |
+
pivot = pivot.rename(columns={"name": "compound_name"})
|
| 1819 |
+
pivot["source_count"] = pivot[SOURCE_ORDER].eq(CHECKMARK).sum(axis=1)
|
| 1820 |
+
final_relation_df = pivot[
|
| 1821 |
+
["Herb_id", "中文名", "pinyin_name", "Latin_name", "compound_id", "compound_name", "pubchem_cid", *SOURCE_ORDER, "source_count"]
|
| 1822 |
+
].sort_values(["Herb_id", "compound_id"]).reset_index(drop=True)
|
| 1823 |
+
return final_relation_df, compounds, unresolved_df, pd.DataFrame(source_summary)
|
| 1824 |
+
|
| 1825 |
+
|
| 1826 |
+
def save_outputs(
|
| 1827 |
+
herb_library: HerbLibrary,
|
| 1828 |
+
herb_merge_rows: list[dict],
|
| 1829 |
+
herb_pre_reviews: list[dict],
|
| 1830 |
+
relation_df: pd.DataFrame,
|
| 1831 |
+
compounds: CompoundLibrary,
|
| 1832 |
+
unresolved_relations: pd.DataFrame,
|
| 1833 |
+
source_summary: pd.DataFrame,
|
| 1834 |
+
) -> None:
|
| 1835 |
+
OUT_DIR.mkdir(exist_ok=True)
|
| 1836 |
+
|
| 1837 |
+
herb_df = herb_library.to_dataframe()
|
| 1838 |
+
compound_df = compounds.to_dataframe()
|
| 1839 |
+
herb_review_df = pd.DataFrame(herb_pre_reviews + herb_library.review_rows + herb_library.final_duplicate_reviews()).drop_duplicates()
|
| 1840 |
+
herb_merge_df = pd.DataFrame(herb_merge_rows).drop_duplicates()
|
| 1841 |
+
herb_resolution_df = pd.DataFrame(herb_library.resolution_rows)
|
| 1842 |
+
compound_review_df = pd.DataFrame(compounds.review_rows).drop_duplicates()
|
| 1843 |
+
compound_resolution_df = pd.DataFrame(compounds.resolution_rows)
|
| 1844 |
+
|
| 1845 |
+
internal_ids = sorted(herb_df["Herb_id"].tolist(), key=numeric_sort_key)
|
| 1846 |
+
final_herb_id_map = {internal_id: f"H{idx:06d}" for idx, internal_id in enumerate(internal_ids, start=1)}
|
| 1847 |
+
compound_internal_ids = sorted(compound_df["compound_id"].tolist(), key=numeric_sort_key)
|
| 1848 |
+
final_compound_id_map = {internal_id: f"C{idx:06d}" for idx, internal_id in enumerate(compound_internal_ids, start=1)}
|
| 1849 |
+
|
| 1850 |
+
def map_single_herb_id(value: object) -> str:
|
| 1851 |
+
text = normalize_space(value)
|
| 1852 |
+
return final_herb_id_map.get(text, text) if text else ""
|
| 1853 |
+
|
| 1854 |
+
def map_single_compound_id(value: object) -> str:
|
| 1855 |
+
text = normalize_space(value)
|
| 1856 |
+
return final_compound_id_map.get(text, text) if text else ""
|
| 1857 |
+
|
| 1858 |
+
def map_multi_herb_ids(value: object) -> str:
|
| 1859 |
+
text = normalize_space(value)
|
| 1860 |
+
if not text:
|
| 1861 |
+
return ""
|
| 1862 |
+
return ";".join(map_single_herb_id(part) for part in text.split(";"))
|
| 1863 |
+
|
| 1864 |
+
def map_multi_compound_ids(value: object) -> str:
|
| 1865 |
+
text = normalize_space(value)
|
| 1866 |
+
if not text:
|
| 1867 |
+
return ""
|
| 1868 |
+
return ";".join(map_single_compound_id(part) for part in text.split(";"))
|
| 1869 |
+
|
| 1870 |
+
def map_ids_in_text(value: object) -> str:
|
| 1871 |
+
text = normalize_space(value)
|
| 1872 |
+
if not text:
|
| 1873 |
+
return ""
|
| 1874 |
+
return re.sub(r"T\d{6}", lambda m: final_herb_id_map.get(m.group(0), m.group(0)), text)
|
| 1875 |
+
|
| 1876 |
+
herb_df = herb_df.copy()
|
| 1877 |
+
herb_df.insert(0, "internal_herb_id", herb_df["Herb_id"])
|
| 1878 |
+
herb_df["Herb_id"] = herb_df["Herb_id"].map(map_single_herb_id)
|
| 1879 |
+
herb_df = herb_df.rename(columns={"merged_from_old_ids": "参考旧id"})
|
| 1880 |
+
|
| 1881 |
+
if not relation_df.empty:
|
| 1882 |
+
relation_df = relation_df.copy()
|
| 1883 |
+
relation_df["Herb_id"] = relation_df["Herb_id"].map(map_single_herb_id)
|
| 1884 |
+
|
| 1885 |
+
if not unresolved_relations.empty and "resolved_herb_id" in unresolved_relations.columns:
|
| 1886 |
+
unresolved_relations = unresolved_relations.copy()
|
| 1887 |
+
unresolved_relations["resolved_herb_id"] = unresolved_relations["resolved_herb_id"].map(map_single_herb_id)
|
| 1888 |
+
if "resolved_compound_id" in unresolved_relations.columns:
|
| 1889 |
+
unresolved_relations["resolved_compound_id"] = unresolved_relations["resolved_compound_id"].map(map_single_compound_id)
|
| 1890 |
+
|
| 1891 |
+
if not herb_resolution_df.empty:
|
| 1892 |
+
herb_resolution_df = herb_resolution_df.copy()
|
| 1893 |
+
herb_resolution_df["resolved_herb_id"] = herb_resolution_df["resolved_herb_id"].map(map_single_herb_id)
|
| 1894 |
+
if "review_reason" in herb_resolution_df.columns:
|
| 1895 |
+
herb_resolution_df["review_reason"] = herb_resolution_df["review_reason"].map(map_ids_in_text)
|
| 1896 |
+
|
| 1897 |
+
if not compound_resolution_df.empty:
|
| 1898 |
+
compound_resolution_df = compound_resolution_df.copy()
|
| 1899 |
+
if "resolved_compound_id" in compound_resolution_df.columns:
|
| 1900 |
+
compound_resolution_df["resolved_compound_id"] = compound_resolution_df["resolved_compound_id"].map(map_single_compound_id)
|
| 1901 |
+
|
| 1902 |
+
if not compound_review_df.empty:
|
| 1903 |
+
compound_review_df = compound_review_df.copy()
|
| 1904 |
+
if "compound_ids" in compound_review_df.columns:
|
| 1905 |
+
compound_review_df["compound_ids"] = compound_review_df["compound_ids"].map(map_multi_compound_ids)
|
| 1906 |
+
|
| 1907 |
+
if not herb_review_df.empty:
|
| 1908 |
+
herb_review_df = herb_review_df.copy()
|
| 1909 |
+
if "resolved_herb_id" in herb_review_df.columns:
|
| 1910 |
+
herb_review_df["resolved_herb_id"] = herb_review_df["resolved_herb_id"].map(map_single_herb_id)
|
| 1911 |
+
if "candidate_herb_ids" in herb_review_df.columns:
|
| 1912 |
+
herb_review_df["candidate_herb_ids"] = herb_review_df["candidate_herb_ids"].map(map_multi_herb_ids)
|
| 1913 |
+
if "reason" in herb_review_df.columns:
|
| 1914 |
+
herb_review_df["reason"] = herb_review_df["reason"].map(map_ids_in_text)
|
| 1915 |
+
|
| 1916 |
+
if not herb_merge_df.empty and "new_herb_id" in herb_merge_df.columns:
|
| 1917 |
+
herb_merge_df = herb_merge_df.copy()
|
| 1918 |
+
herb_merge_df["new_herb_id"] = herb_merge_df["new_herb_id"].map(map_single_herb_id)
|
| 1919 |
+
|
| 1920 |
+
herb_final_df = herb_df.copy()
|
| 1921 |
+
weak_herb_mask = herb_final_df.apply(is_pinyin_only_weak_herb, axis=1)
|
| 1922 |
+
herb_manual_review_df = build_pinyin_manual_review_df(herb_final_df, herb_resolution_df)
|
| 1923 |
+
herb_final_df = herb_final_df.loc[~weak_herb_mask].copy()
|
| 1924 |
+
herb_final_df = herb_final_df.rename(columns={"Herb_id": "herb_id"})
|
| 1925 |
+
herb_final_df = herb_final_df.drop(columns=["internal_herb_id"], errors="ignore")
|
| 1926 |
+
herb_keep_cols = [
|
| 1927 |
+
"herb_id",
|
| 1928 |
+
"中文名",
|
| 1929 |
+
"别名",
|
| 1930 |
+
"pinyin_name",
|
| 1931 |
+
"Latin_name",
|
| 1932 |
+
"来源数据库",
|
| 1933 |
+
]
|
| 1934 |
+
herb_keep_cols = [col for col in herb_keep_cols if col in herb_final_df.columns]
|
| 1935 |
+
herb_final_df = (
|
| 1936 |
+
herb_final_df[herb_keep_cols]
|
| 1937 |
+
.drop_duplicates()
|
| 1938 |
+
.sort_values("herb_id", key=lambda s: s.map(numeric_sort_key))
|
| 1939 |
+
.reset_index(drop=True)
|
| 1940 |
+
)
|
| 1941 |
+
|
| 1942 |
+
compound_final_df = compound_df.copy()
|
| 1943 |
+
compound_final_df["compound_id"] = compound_final_df["compound_id"].map(map_single_compound_id)
|
| 1944 |
+
compound_keep_cols = [
|
| 1945 |
+
"compound_id",
|
| 1946 |
+
"name",
|
| 1947 |
+
"pubchem_cid",
|
| 1948 |
+
"molecular_formula",
|
| 1949 |
+
"smiles",
|
| 1950 |
+
"average_weight",
|
| 1951 |
+
"inchi",
|
| 1952 |
+
"inchikey",
|
| 1953 |
+
"cas",
|
| 1954 |
+
"来源数据库",
|
| 1955 |
+
]
|
| 1956 |
+
compound_keep_cols = [col for col in compound_keep_cols if col in compound_final_df.columns]
|
| 1957 |
+
compound_final_df = (
|
| 1958 |
+
compound_final_df[compound_keep_cols]
|
| 1959 |
+
.drop_duplicates()
|
| 1960 |
+
.sort_values("compound_id", key=lambda s: s.map(numeric_sort_key))
|
| 1961 |
+
.reset_index(drop=True)
|
| 1962 |
+
)
|
| 1963 |
+
|
| 1964 |
+
relation_final_df = relation_df.copy()
|
| 1965 |
+
relation_final_df["Herb_id"] = relation_final_df["Herb_id"].map(map_single_herb_id)
|
| 1966 |
+
relation_final_df["compound_id"] = relation_final_df["compound_id"].map(map_single_compound_id)
|
| 1967 |
+
relation_final_df = relation_final_df.rename(columns={"Herb_id": "herb_id"})
|
| 1968 |
+
valid_h_ids = set(herb_final_df["herb_id"].tolist())
|
| 1969 |
+
valid_c_ids = set(compound_final_df["compound_id"].tolist())
|
| 1970 |
+
relation_final_df = relation_final_df[
|
| 1971 |
+
relation_final_df["herb_id"].isin(valid_h_ids) & relation_final_df["compound_id"].isin(valid_c_ids)
|
| 1972 |
+
].copy()
|
| 1973 |
+
|
| 1974 |
+
relation_rows = []
|
| 1975 |
+
for source_name in SOURCE_ORDER:
|
| 1976 |
+
if source_name not in relation_final_df.columns:
|
| 1977 |
+
continue
|
| 1978 |
+
marked = relation_final_df[relation_final_df[source_name] == CHECKMARK][["herb_id", "compound_id"]].copy()
|
| 1979 |
+
if marked.empty:
|
| 1980 |
+
continue
|
| 1981 |
+
marked["source_db"] = source_name
|
| 1982 |
+
relation_rows.append(marked)
|
| 1983 |
+
relation_final_df = (
|
| 1984 |
+
pd.concat(relation_rows, ignore_index=True)
|
| 1985 |
+
if relation_rows
|
| 1986 |
+
else pd.DataFrame(columns=["herb_id", "compound_id", "source_db"])
|
| 1987 |
+
)
|
| 1988 |
+
relation_final_df = (
|
| 1989 |
+
relation_final_df[["herb_id", "compound_id", "source_db"]]
|
| 1990 |
+
.drop_duplicates()
|
| 1991 |
+
.sort_values(["herb_id", "compound_id", "source_db"])
|
| 1992 |
+
.reset_index(drop=True)
|
| 1993 |
+
)
|
| 1994 |
+
|
| 1995 |
+
herb_final_df.to_excel(OUT_DIR / "中药库_final.xlsx", index=False, engine="openpyxl")
|
| 1996 |
+
compound_final_df.to_excel(OUT_DIR / "化合物库_final.xlsx", index=False, engine="openpyxl")
|
| 1997 |
+
relation_final_df.to_excel(OUT_DIR / "中药_化合物关系表.xlsx", index=False, engine="openpyxl")
|
| 1998 |
+
|
| 1999 |
+
with pd.ExcelWriter(OUT_DIR / "中药审核与映射.xlsx", engine="openpyxl") as writer:
|
| 2000 |
+
herb_manual_review_df.to_excel(writer, index=False, sheet_name="manual_review")
|
| 2001 |
+
herb_review_df.to_excel(writer, index=False, sheet_name="herb_review")
|
| 2002 |
+
herb_merge_df.to_excel(writer, index=False, sheet_name="herb_merge_map")
|
| 2003 |
+
herb_resolution_df.to_excel(writer, index=False, sheet_name="source_resolution")
|
| 2004 |
+
|
| 2005 |
+
with pd.ExcelWriter(OUT_DIR / "化合物审核与映射.xlsx", engine="openpyxl") as writer:
|
| 2006 |
+
compound_review_df.to_excel(writer, index=False, sheet_name="compound_review")
|
| 2007 |
+
compound_resolution_df.to_excel(writer, index=False, sheet_name="source_resolution")
|
| 2008 |
+
|
| 2009 |
+
with pd.ExcelWriter(OUT_DIR / "整理汇总.xlsx", engine="openpyxl") as writer:
|
| 2010 |
+
source_summary.to_excel(writer, index=False, sheet_name="source_summary")
|
| 2011 |
+
unresolved_relations.to_excel(writer, index=False, sheet_name="unresolved_relations")
|
| 2012 |
+
pd.DataFrame(
|
| 2013 |
+
[
|
| 2014 |
+
{"metric": "herb_library_rows", "value": len(herb_final_df)},
|
| 2015 |
+
{"metric": "compound_library_rows", "value": len(compound_final_df)},
|
| 2016 |
+
{"metric": "relation_rows", "value": len(relation_final_df)},
|
| 2017 |
+
{"metric": "herb_review_rows", "value": len(herb_review_df)},
|
| 2018 |
+
{"metric": "compound_review_rows", "value": len(compound_review_df)},
|
| 2019 |
+
{"metric": "unresolved_relation_rows", "value": len(unresolved_relations)},
|
| 2020 |
+
]
|
| 2021 |
+
).to_excel(writer, index=False, sheet_name="overview")
|
| 2022 |
+
|
| 2023 |
+
|
| 2024 |
+
def main() -> None:
|
| 2025 |
+
print("阶段 1/3: 构建中药参考库...")
|
| 2026 |
+
canonical_df, old_to_new, herb_merge_rows, herb_pre_reviews = load_reference_herbs()
|
| 2027 |
+
herb_library = HerbLibrary(canonical_df, old_to_new)
|
| 2028 |
+
|
| 2029 |
+
for record in collect_source_herb_records():
|
| 2030 |
+
herb_library.resolve_and_update(record)
|
| 2031 |
+
print(f" 中药库完成: {len(herb_library.to_dataframe())} 行")
|
| 2032 |
+
|
| 2033 |
+
print("阶段 2/3: 整理关系并校验化合物库...")
|
| 2034 |
+
relation_df, compounds, unresolved_relations, source_summary = build_relations_and_compounds(herb_library)
|
| 2035 |
+
print(f" 化合物库当前: {len(compounds.to_dataframe())} 行")
|
| 2036 |
+
print(f" 关系表当前: {len(relation_df)} 行")
|
| 2037 |
+
print(f" 未解析关系: {len(unresolved_relations)} 行")
|
| 2038 |
+
|
| 2039 |
+
print("阶段 3/3: 保存输出文件...")
|
| 2040 |
+
save_outputs(
|
| 2041 |
+
herb_library=herb_library,
|
| 2042 |
+
herb_merge_rows=herb_merge_rows,
|
| 2043 |
+
herb_pre_reviews=herb_pre_reviews,
|
| 2044 |
+
relation_df=relation_df,
|
| 2045 |
+
compounds=compounds,
|
| 2046 |
+
unresolved_relations=unresolved_relations,
|
| 2047 |
+
source_summary=source_summary,
|
| 2048 |
+
)
|
| 2049 |
+
|
| 2050 |
+
print("输出目录:", OUT_DIR)
|
| 2051 |
+
print("中药库行数:", len(herb_library.to_dataframe()))
|
| 2052 |
+
print("化合物库行数:", len(compounds.to_dataframe()))
|
| 2053 |
+
print("关系表行数:", len(relation_df))
|
| 2054 |
+
print("未解析关系行数:", len(unresolved_relations))
|
| 2055 |
+
|
| 2056 |
+
|
| 2057 |
+
if __name__ == "__main__":
|
| 2058 |
+
main()
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/data/export_compound_enrichment_tasks.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""用于导出后续化合物富集或扩展分析所需的任务清单。"""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
BASE_DIR = Path("/mnt/disk1/yanganqi/YJT/data")
|
| 12 |
+
OUT_DIR = BASE_DIR / "整理输出"
|
| 13 |
+
SUMMARY_XLSX = OUT_DIR / "整理汇总.xlsx"
|
| 14 |
+
|
| 15 |
+
SOURCE_URLS = {
|
| 16 |
+
"BATMAN-TCM": "http://bionet.ncpsb.org.cn/batman-tcm/#/home",
|
| 17 |
+
"DCABM-TCM": "http://bionet.ncpsb.org.cn/dcabm-tcm/#/Home",
|
| 18 |
+
"ETCM2": "http://www.tcmip.cn/ETCM2/front/#/browse/herb",
|
| 19 |
+
"HERB2": "http://47.92.70.12/FAQ/",
|
| 20 |
+
"SymMap": "http://www.symmap.org/",
|
| 21 |
+
"TCMIO": "http://tcmio.xielab.net/browse/tcms",
|
| 22 |
+
"TM-MC": "https://tm-mc.kr/index.jsp",
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def normalize_space(value: object) -> str:
|
| 27 |
+
if value is None:
|
| 28 |
+
return ""
|
| 29 |
+
text = str(value).strip()
|
| 30 |
+
text = re.sub(r"\s+", " ", text)
|
| 31 |
+
return "" if text.lower() == "nan" else text
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def standardize_name_key(value: object) -> str:
|
| 35 |
+
text = normalize_space(value).lower()
|
| 36 |
+
text = re.sub(r"\s+", " ", text)
|
| 37 |
+
return text
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def guess_name_type(value: object) -> str:
|
| 41 |
+
text = normalize_space(value)
|
| 42 |
+
if not text:
|
| 43 |
+
return "blank"
|
| 44 |
+
if re.fullmatch(r"[A-Z][a-z]?\d+(?:[A-Z][a-z]?\d+)*", text):
|
| 45 |
+
return "molecular_formula"
|
| 46 |
+
if re.fullmatch(r"[A-Za-z0-9@+\-\[\]\(\)=#$\\/%.]+", text) and any(ch in text for ch in "[]()=#@\\/"):
|
| 47 |
+
return "smiles_like"
|
| 48 |
+
if re.fullmatch(r"(SCHEMBL|CHEMBL|CID|CAS|INCHIKEY|HMDB|DB)\S*", text, flags=re.I):
|
| 49 |
+
return "registry_or_db_id"
|
| 50 |
+
if re.fullmatch(r"[A-Za-z0-9'\", .+\-]+", text):
|
| 51 |
+
return "chemical_name"
|
| 52 |
+
return "mixed_text"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def join_examples(values: pd.Series, limit: int = 5) -> str:
|
| 56 |
+
out = []
|
| 57 |
+
seen = set()
|
| 58 |
+
for value in values:
|
| 59 |
+
value = normalize_space(value)
|
| 60 |
+
if not value or value in seen:
|
| 61 |
+
continue
|
| 62 |
+
seen.add(value)
|
| 63 |
+
out.append(value)
|
| 64 |
+
if len(out) >= limit:
|
| 65 |
+
break
|
| 66 |
+
return ";".join(out)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def summarize_group(df: pd.DataFrame, group_cols: list[str]) -> pd.DataFrame:
|
| 70 |
+
grouped = []
|
| 71 |
+
for keys, sub in df.groupby(group_cols, dropna=False):
|
| 72 |
+
if not isinstance(keys, tuple):
|
| 73 |
+
keys = (keys,)
|
| 74 |
+
row = {col: key for col, key in zip(group_cols, keys)}
|
| 75 |
+
row["row_count"] = len(sub)
|
| 76 |
+
row["unique_herb_count"] = sub["resolved_herb_id"].replace("", pd.NA).dropna().nunique()
|
| 77 |
+
row["example_herb_ids"] = join_examples(sub["resolved_herb_id"])
|
| 78 |
+
row["example_herb_cn"] = join_examples(sub["source_中文名"])
|
| 79 |
+
row["example_herb_pinyin"] = join_examples(sub["source_pinyin_name"])
|
| 80 |
+
row["example_herb_latin"] = join_examples(sub["source_Latin_name"])
|
| 81 |
+
row["example_source_rows"] = join_examples(sub["source_row"].astype(str))
|
| 82 |
+
grouped.append(row)
|
| 83 |
+
return pd.DataFrame(grouped)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def main() -> None:
|
| 87 |
+
unresolved = pd.read_excel(SUMMARY_XLSX, sheet_name="unresolved_relations", dtype=str, engine="openpyxl").fillna("")
|
| 88 |
+
unresolved["source_url"] = unresolved["source_db"].map(SOURCE_URLS).fillna("")
|
| 89 |
+
unresolved["name_key"] = unresolved["source_compound_name"].map(standardize_name_key)
|
| 90 |
+
unresolved["name_type_guess"] = unresolved["source_compound_name"].map(guess_name_type)
|
| 91 |
+
|
| 92 |
+
name_only = unresolved[unresolved["compound_review_reason"] == "name_only_unmatched"].copy()
|
| 93 |
+
missing_all = unresolved[unresolved["compound_review_reason"] == "missing_compound_identifiers"].copy()
|
| 94 |
+
|
| 95 |
+
name_only_grouped = summarize_group(
|
| 96 |
+
name_only,
|
| 97 |
+
["source_db", "source_url", "source_compound_name", "name_key", "name_type_guess"],
|
| 98 |
+
).sort_values(["source_db", "row_count", "source_compound_name"], ascending=[True, False, True])
|
| 99 |
+
|
| 100 |
+
missing_grouped = summarize_group(
|
| 101 |
+
missing_all,
|
| 102 |
+
["source_db", "source_url", "source_compound_name", "name_key", "name_type_guess"],
|
| 103 |
+
).sort_values(["source_db", "row_count", "source_compound_name"], ascending=[True, False, True])
|
| 104 |
+
|
| 105 |
+
db_overview_rows = []
|
| 106 |
+
for db, sub in unresolved.groupby("source_db"):
|
| 107 |
+
db_overview_rows.append(
|
| 108 |
+
{
|
| 109 |
+
"source_db": db,
|
| 110 |
+
"source_url": SOURCE_URLS.get(db, ""),
|
| 111 |
+
"unresolved_rows": len(sub),
|
| 112 |
+
"name_only_unmatched_rows": int((sub["compound_review_reason"] == "name_only_unmatched").sum()),
|
| 113 |
+
"missing_compound_identifiers_rows": int((sub["compound_review_reason"] == "missing_compound_identifiers").sum()),
|
| 114 |
+
"unique_name_only_names": sub.loc[sub["compound_review_reason"] == "name_only_unmatched", "name_key"].replace("", pd.NA).dropna().nunique(),
|
| 115 |
+
"unique_missing_rows_names": sub.loc[sub["compound_review_reason"] == "missing_compound_identifiers", "name_key"].replace("", pd.NA).dropna().nunique(),
|
| 116 |
+
}
|
| 117 |
+
)
|
| 118 |
+
db_overview = pd.DataFrame(db_overview_rows).sort_values("unresolved_rows", ascending=False)
|
| 119 |
+
|
| 120 |
+
out_file = OUT_DIR / "化合物源数据库补全任务.xlsx"
|
| 121 |
+
with pd.ExcelWriter(out_file, engine="openpyxl") as writer:
|
| 122 |
+
db_overview.to_excel(writer, index=False, sheet_name="db_overview")
|
| 123 |
+
name_only_grouped.to_excel(writer, index=False, sheet_name="name_only_grouped")
|
| 124 |
+
missing_grouped.to_excel(writer, index=False, sheet_name="missing_id_grouped")
|
| 125 |
+
name_only.to_excel(writer, index=False, sheet_name="name_only_raw")
|
| 126 |
+
missing_all.to_excel(writer, index=False, sheet_name="missing_id_raw")
|
| 127 |
+
|
| 128 |
+
for db in sorted(name_only["source_db"].unique()):
|
| 129 |
+
sub = name_only_grouped[name_only_grouped["source_db"] == db].copy()
|
| 130 |
+
if sub.empty:
|
| 131 |
+
continue
|
| 132 |
+
sheet = re.sub(r"[^A-Za-z0-9_]+", "_", db)[:31]
|
| 133 |
+
sub.to_excel(writer, index=False, sheet_name=sheet)
|
| 134 |
+
|
| 135 |
+
print("输出文件:", out_file)
|
| 136 |
+
print("name_only_unmatched rows:", len(name_only))
|
| 137 |
+
print("missing_compound_identifiers rows:", len(missing_all))
|
| 138 |
+
if not db_overview.empty:
|
| 139 |
+
print(db_overview.to_dict(orient="records"))
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
if __name__ == "__main__":
|
| 143 |
+
main()
|
recovery_20261030/github_modified_2026-07-10/yanganqi_workspace/YJT/TCM/docs/legacy_tcm_repo_readme.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🌿 TCM Scripts Collection
|
| 2 |
+
本项目汇总了多个中药数据库(如 BATMAN-TCM、TCMIO、DCABM-TCM、ETCM、HERB、SymMap、TM-MC 等)的数据处理脚本,主要用于中药与化合物的映射、化合物结构标准化(PubChem)、基因靶点提取(SymMap)、文献计量分析(PubMed)等工作,适用于中药系统药理学与数据挖掘研究场景。
|
| 3 |
+
|
| 4 |
+
---
|
| 5 |
+
|
| 6 |
+
## 📁 目录结构
|
| 7 |
+
Projects/
|
| 8 |
+
└── TCM/
|
| 9 |
+
├── README.md
|
| 10 |
+
└── Scripts/
|
| 11 |
+
├── BATMAN/
|
| 12 |
+
│ ├── fetch_pubchem_info_by_cid.py
|
| 13 |
+
│ └── split_batman_herb_ingredients.py
|
| 14 |
+
├── DCABM-TCM/
|
| 15 |
+
│ ├── fetch_pubchem_dcabm.py
|
| 16 |
+
│ └── split_herb_compounds.py
|
| 17 |
+
├── ETCM/
|
| 18 |
+
│ └── crawl_etcm_herb_table.py
|
| 19 |
+
├── HERB/
|
| 20 |
+
│ └── fetch_herb2_compound.py
|
| 21 |
+
├── PubChem/
|
| 22 |
+
│ └── fetch_pubchem_cid_by_inchikey.py
|
| 23 |
+
├── PubMed/
|
| 24 |
+
│ └── query_pubmed_by_gene.py
|
| 25 |
+
├── SymMap/
|
| 26 |
+
│ ├── fetch_symmap_ingredients.py
|
| 27 |
+
│ └── fetch_symmap_targets.py
|
| 28 |
+
├── TCMIO/
|
| 29 |
+
│ ├── fetch_pubchem_tcmio.py
|
| 30 |
+
│ └── split_herb_compounds.py
|
| 31 |
+
├── TM-MC/
|
| 32 |
+
│ ├── fetch_pubchem_info_by_compounds.py
|
| 33 |
+
│ └── split_herb_compounds.py
|
| 34 |
+
|
| 35 |
+
---
|
| 36 |
+
|
| 37 |
+
## 🧭 各模块功能概述
|
| 38 |
+
|
| 39 |
+
### BATMAN/
|
| 40 |
+
- `fetch_pubchem_info_by_cid.py`: 通过 CID 抓取 PubChem 化合物结构信息
|
| 41 |
+
- `split_batman_herb_ingredients.py`: 将中药-化合物信息拆分并按药物导出
|
| 42 |
+
|
| 43 |
+
### DCABM-TCM/
|
| 44 |
+
- `fetch_pubchem_dcabm.py`: 抓取 DCABM 数据中的化合物 PubChem 结构
|
| 45 |
+
- `split_herb_compounds.py`: 拆分血中成分字段并构建 CID 映射表
|
| 46 |
+
|
| 47 |
+
### ETCM/
|
| 48 |
+
- `crawl_etcm_herb_table.py`: 爬取 ETCM2.0 官网中药信息表格
|
| 49 |
+
|
| 50 |
+
### HERB/
|
| 51 |
+
- `fetch_herb2_compound.py`: 提取 HERB v2 数据集中药与成分的对应关系
|
| 52 |
+
|
| 53 |
+
### PubChem/
|
| 54 |
+
- `fetch_pubchem_cid_by_inchikey.py`: 通过 InChIKey 查询 CID 与结构信息
|
| 55 |
+
|
| 56 |
+
### PubMed/
|
| 57 |
+
- `query_pubmed_by_gene.py`: 查询基因在指定疾病中的 PubMed 关联文献数
|
| 58 |
+
|
| 59 |
+
### SymMap/
|
| 60 |
+
- `fetch_symmap_ingredients.py`: 获取中药在 SymMap 中的成分信息
|
| 61 |
+
- `fetch_symmap_targets.py`: 提取 SymMap 中药相关的靶点基因
|
| 62 |
+
|
| 63 |
+
### TCMIO/
|
| 64 |
+
- `fetch_pubchem_tcmio.py`: 抓取 TCMIO 数据中的化合物结构信息
|
| 65 |
+
- `split_herb_compounds.py`: 合并中药、化合物与关系表,并按中药拆表导出
|
| 66 |
+
|
| 67 |
+
### TM-MC/
|
| 68 |
+
- `fetch_pubchem_info_by_compounds.py`: 标准化 TM-MC 数据集中化合物结构信息
|
| 69 |
+
- `split_herb_compounds.py`: 拆分 TM-MC 中药-化合物对应关系
|
| 70 |
+
|
| 71 |
+
---
|
| 72 |
+
|
| 73 |
+
## 🛠️ 依赖安装
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
pip install pandas requests tqdm openpyxl pubchempy biopython
|
| 77 |
+
|
| 78 |
+
- - -
|
| 79 |
+
|
| 80 |
+
## 🚀 使用方式示例
|
| 81 |
+
|
| 82 |
+
cd Scripts/TCMIO
|
| 83 |
+
python fetch_pubchem_tcmio.py
|
| 84 |
+
python split_herb_compounds.py
|
| 85 |
+
|
| 86 |
+
- - -
|
| 87 |
+
|
| 88 |
+
## 📦 输出说明
|
| 89 |
+
大多数 split_*.py 脚本将中药与化合物信息按中药名称导出 Excel 文件:
|
| 90 |
+
输出文件结构示例:
|
| 91 |
+
├── 当归_Angelica.xlsx
|
| 92 |
+
├── 黄芪_Astragalus.xlsx
|
| 93 |
+
└── ...
|
| 94 |
+
|
| 95 |
+
- - -
|
| 96 |
+
|
| 97 |
+
## 📮 联系方式
|
| 98 |
+
项目作者:君诩
|
| 99 |
+
邮箱:nh96452@163.com
|
| 100 |
+
欢迎任何合作建议或反馈!
|
| 101 |
+
|
| 102 |
+
---
|
| 103 |
+
|
| 104 |
+
## 📄 许可协议
|
| 105 |
+
本项目为学习与研究目的,默认为 MIT 或 CC BY 协议。请在使用脚本时注明出处。
|
recovery_20261030/zip_preserved_scripts/111药精图模型/herbs.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
recovery_20261030/zip_preserved_scripts/111药精图模型/别名拼音.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
from pypinyin import pinyin, Style
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import re
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
INPUT_PATH = r"D:\2\111数据库\中药表格\herbs.xlsx"
|
| 8 |
+
OUTPUT_PATH = r"D:\2\111数据库\中药表格\herbs_pinyin_updated.xlsx"
|
| 9 |
+
|
| 10 |
+
def get_pinyin_for_text(chinese_text):
|
| 11 |
+
"""
|
| 12 |
+
将一段文本(通常是单个别名)转为拼音,音节之间用空格分隔,返回大写字符串。
|
| 13 |
+
如果输入为空或 NaN,返回空字符串。
|
| 14 |
+
"""
|
| 15 |
+
if pd.isna(chinese_text):
|
| 16 |
+
return ''
|
| 17 |
+
s = str(chinese_text).strip()
|
| 18 |
+
if s == '':
|
| 19 |
+
return ''
|
| 20 |
+
# pinyin 对中文效果最佳;对拉丁字母(例如 LATIN)会原样返回字符块,所以也能处理 E jiao 这种情况
|
| 21 |
+
py_list = pinyin(s, style=Style.NORMAL, heteronym=False)
|
| 22 |
+
# py_list 是 [['e'], ['jiao']] 之类,连接为 'e jiao'
|
| 23 |
+
joined = ' '.join([item[0] for item in py_list]).strip()
|
| 24 |
+
return joined.upper()
|
| 25 |
+
|
| 26 |
+
def normalize_split_aliases(alias_cell):
|
| 27 |
+
"""
|
| 28 |
+
将别名单元格切分为多个别名字符串列表,支持分隔符:、 , ; ; | /
|
| 29 |
+
并去除空项和前后空白。
|
| 30 |
+
"""
|
| 31 |
+
if pd.isna(alias_cell):
|
| 32 |
+
return []
|
| 33 |
+
s = str(alias_cell).strip()
|
| 34 |
+
if s == '':
|
| 35 |
+
return []
|
| 36 |
+
parts = re.split(r'[、,;;\|/]', s)
|
| 37 |
+
parts = [p.strip() for p in parts if p.strip() != '']
|
| 38 |
+
return parts
|
| 39 |
+
|
| 40 |
+
def normalize_existing_pinyin_cell(cell):
|
| 41 |
+
"""
|
| 42 |
+
将已存在的 pinyin_name 单元格解析为列表(用 '、' 分隔),去重并标准化空格。
|
| 43 |
+
返回列表(每项为大写、音节间单空格)。
|
| 44 |
+
"""
|
| 45 |
+
if pd.isna(cell):
|
| 46 |
+
return []
|
| 47 |
+
s = str(cell).strip()
|
| 48 |
+
if s == '':
|
| 49 |
+
return []
|
| 50 |
+
parts = re.split(r'[、,;;\|/]', s)
|
| 51 |
+
out = []
|
| 52 |
+
for p in parts:
|
| 53 |
+
p2 = ' '.join(p.split()) # 压缩多空格
|
| 54 |
+
if p2 != '':
|
| 55 |
+
out.append(p2.upper())
|
| 56 |
+
# 保持原顺序去重
|
| 57 |
+
seen = set()
|
| 58 |
+
uniq = []
|
| 59 |
+
for item in out:
|
| 60 |
+
if item not in seen:
|
| 61 |
+
uniq.append(item)
|
| 62 |
+
seen.add(item)
|
| 63 |
+
return uniq
|
| 64 |
+
|
| 65 |
+
def main():
|
| 66 |
+
if not os.path.exists(INPUT_PATH):
|
| 67 |
+
raise FileNotFoundError(f"输入文件不存在: {INPUT_PATH}")
|
| 68 |
+
|
| 69 |
+
df = pd.read_excel(INPUT_PATH, dtype=object) # dtype=object 保持原样
|
| 70 |
+
|
| 71 |
+
# 确保列存在(如果列名不同,请修改这里)
|
| 72 |
+
required_cols = ['Herb_id', '中文名', '别名', 'pinyin_name', 'Latin_name']
|
| 73 |
+
# 允许输入表格缺少 pinyin_name 列,若无则创建空列
|
| 74 |
+
for col in ['pinyin_name']:
|
| 75 |
+
if col not in df.columns:
|
| 76 |
+
df[col] = ''
|
| 77 |
+
|
| 78 |
+
# 逐行处理
|
| 79 |
+
new_pinyin_counts = 0
|
| 80 |
+
for idx, row in df.iterrows():
|
| 81 |
+
alias_cell = row.get('别名', None)
|
| 82 |
+
existing_cell = row.get('pinyin_name', None)
|
| 83 |
+
|
| 84 |
+
alias_list = normalize_split_aliases(alias_cell) # 原始别名列表
|
| 85 |
+
existing_list = normalize_existing_pinyin_cell(existing_cell) # 现有拼音列表
|
| 86 |
+
|
| 87 |
+
# 生成别名对应的拼音列表(保持顺序)
|
| 88 |
+
alias_pinyin_list = []
|
| 89 |
+
for alias in alias_list:
|
| 90 |
+
py = get_pinyin_for_text(alias)
|
| 91 |
+
if py != '':
|
| 92 |
+
# 进一步规范化空格(避免多空格)
|
| 93 |
+
py = ' '.join(py.split())
|
| 94 |
+
alias_pinyin_list.append(py)
|
| 95 |
+
|
| 96 |
+
# 移除与现有重复的项(基于完全匹配的拼音字符串)
|
| 97 |
+
to_add = []
|
| 98 |
+
existing_set = set(existing_list)
|
| 99 |
+
for py in alias_pinyin_list:
|
| 100 |
+
if py not in existing_set and py not in to_add:
|
| 101 |
+
to_add.append(py)
|
| 102 |
+
|
| 103 |
+
if to_add:
|
| 104 |
+
# 将新项追加到现有项后面,用顿号分隔
|
| 105 |
+
combined = existing_list + to_add
|
| 106 |
+
df.at[idx, 'pinyin_name'] = '、'.join(combined)
|
| 107 |
+
new_pinyin_counts += len(to_add)
|
| 108 |
+
else:
|
| 109 |
+
# 如果没有新增但现有为空且没有别名生成的拼音,保持原样(空或原值)
|
| 110 |
+
# 若现有为空但别名也为空,则保持空字符串
|
| 111 |
+
if (not existing_list) and alias_pinyin_list:
|
| 112 |
+
# 这种情况 alias_pinyin_list 可能都与 existing 重复后为空,上面不会进入
|
| 113 |
+
df.at[idx, 'pinyin_name'] = '、'.join(alias_pinyin_list)
|
| 114 |
+
|
| 115 |
+
# 保存输出
|
| 116 |
+
df.to_excel(OUTPUT_PATH, index=False)
|
| 117 |
+
print(f"处理完成!共新增拼音条目:{new_pinyin_counts},输出文件:{OUTPUT_PATH}")
|
| 118 |
+
|
| 119 |
+
if __name__ == '__main__':
|
| 120 |
+
main()
|
recovery_20261030/zip_preserved_scripts/111药精图模型/加拼音.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pypinyin import pinyin, Style
|
| 2 |
+
import pandas as pd
|
| 3 |
+
|
| 4 |
+
def get_pinyin(chinese_text):
|
| 5 |
+
# 检查是否为空值或非字符串
|
| 6 |
+
if pd.isna(chinese_text):
|
| 7 |
+
return ''
|
| 8 |
+
# 确保输入是字符串
|
| 9 |
+
chinese_text = str(chinese_text)
|
| 10 |
+
# 将汉字转换为拼音,并用空格连接
|
| 11 |
+
py = pinyin(chinese_text, style=Style.NORMAL)
|
| 12 |
+
return ' '.join([item[0] for item in py])
|
| 13 |
+
|
| 14 |
+
# 读取Excel文件
|
| 15 |
+
df = pd.read_excel(r"D:\2\111数据库\药典.xlsx")
|
| 16 |
+
|
| 17 |
+
# 添加拼音列
|
| 18 |
+
df['pinyin'] = df['cn'].apply(get_pinyin)
|
| 19 |
+
|
| 20 |
+
# 保存到新的Excel文件
|
| 21 |
+
df.to_excel('药典_带拼音.xlsx', index=False)
|
| 22 |
+
|
| 23 |
+
print("处理完成!")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/BATMAN/batman.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
BATMAN 汇总脚本 — 精确匹配规则版
|
| 4 |
+
规则:
|
| 5 |
+
- 文件名同时含拼音和拉丁:必须同时匹配 pn_norm AND ln_norm
|
| 6 |
+
- 只有拼音:按 pn_norm 匹配
|
| 7 |
+
- 只有拉丁:按 ln_norm 匹配
|
| 8 |
+
- 无匹配仍保留记录
|
| 9 |
+
输出:
|
| 10 |
+
- 合并 CSV(OUTPUT_CSV)
|
| 11 |
+
- 未匹配文件清单(UNMATCHED_LIST_CSV)
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
import re
|
| 16 |
+
import pandas as pd
|
| 17 |
+
|
| 18 |
+
# ========== 用户配置 ==========
|
| 19 |
+
HERB_PATH = r"D:\2\111数据库\中药表格\BATMAN-TCM.xlsx"
|
| 20 |
+
COMPOUND_INFO_DIR = r"D:\2\111数据库\数据库-化合物\BATMAN-TCM_Info"
|
| 21 |
+
OUTPUT_DIR = r"D:\2\111数据库\汇总\BATMAN"
|
| 22 |
+
OUTPUT_CSV = os.path.join(OUTPUT_DIR, "BATMAN-TCM_Info_汇总.csv")
|
| 23 |
+
UNMATCHED_LIST_CSV = os.path.join(OUTPUT_DIR, "BATMAN-TCM_unmatched_files.csv")
|
| 24 |
+
# ==============================
|
| 25 |
+
|
| 26 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 27 |
+
|
| 28 |
+
# === 标准化函数 ===
|
| 29 |
+
def normalize(s):
|
| 30 |
+
if pd.isna(s) or s is None:
|
| 31 |
+
return ""
|
| 32 |
+
return re.sub(r'\s+|[^a-zA-Z0-9]', '', str(s).lower())
|
| 33 |
+
|
| 34 |
+
def parse_herb_from_filename(filename):
|
| 35 |
+
"""
|
| 36 |
+
解析文件名。支持带编号的重复名:
|
| 37 |
+
pinyin__latin.xlsx
|
| 38 |
+
pinyin__latin__2.xlsx
|
| 39 |
+
如果解析失败,会把整个 basename 当作 pinyin(latin 为空)
|
| 40 |
+
"""
|
| 41 |
+
base = os.path.splitext(os.path.basename(filename))[0]
|
| 42 |
+
# 先尝试常见形式 pinyin__latin (可能带重复后缀 __2)
|
| 43 |
+
m = re.match(r"^(.+?)__([^_]+)(?:__\d+)?$", base)
|
| 44 |
+
if m:
|
| 45 |
+
pinyin_name, latin_name = m.groups()
|
| 46 |
+
return pinyin_name.strip(), latin_name.strip()
|
| 47 |
+
# 其它情况尽量拆第一个 __ 之前作为拼音,后面全部作为拉丁(防止拉丁里有下划线)
|
| 48 |
+
if "__" in base:
|
| 49 |
+
parts = base.split("__", 1)
|
| 50 |
+
return parts[0].strip(), parts[1].strip()
|
| 51 |
+
# 如果连 __ 都没有,就把全名当拼音,latin 为空
|
| 52 |
+
return base.strip(), ""
|
| 53 |
+
|
| 54 |
+
# === 读取中药表并构建标准化索引 ===
|
| 55 |
+
print("📘 读取中药原始表...")
|
| 56 |
+
herb_df = pd.read_excel(HERB_PATH)
|
| 57 |
+
# 强化容错:若没有这些列,提醒并退出
|
| 58 |
+
required_cols = ["Pinyin.Name", "Chinese.Name", "Latin.Name"]
|
| 59 |
+
for c in required_cols:
|
| 60 |
+
if c not in herb_df.columns:
|
| 61 |
+
raise ValueError(f"中药表缺少列:{c},请检查 {HERB_PATH}")
|
| 62 |
+
|
| 63 |
+
herb_df["pn_norm"] = herb_df["Pinyin.Name"].apply(normalize)
|
| 64 |
+
herb_df["ln_norm"] = herb_df["Latin.Name"].apply(normalize)
|
| 65 |
+
|
| 66 |
+
# === 开始遍历并合并 ===
|
| 67 |
+
print("🧩 遍历化合物信息文件夹并合并所有文件...")
|
| 68 |
+
files = sorted([f for f in os.listdir(COMPOUND_INFO_DIR) if f.lower().endswith(".xlsx")])
|
| 69 |
+
print(f"发现 {len(files)} 个 .xlsx 文件。")
|
| 70 |
+
|
| 71 |
+
all_dfs = []
|
| 72 |
+
unmatched_list = [] # 记录未匹配文件信息:文件名、pinyin、latin、原因
|
| 73 |
+
|
| 74 |
+
for idx, fname in enumerate(files, 1):
|
| 75 |
+
fpath = os.path.join(COMPOUND_INFO_DIR, fname)
|
| 76 |
+
pinyin_name, latin_name = parse_herb_from_filename(fname)
|
| 77 |
+
pn_norm = normalize(pinyin_name)
|
| 78 |
+
ln_norm = normalize(latin_name)
|
| 79 |
+
|
| 80 |
+
# 决定匹配策略
|
| 81 |
+
use_pn = bool(pn_norm)
|
| 82 |
+
use_ln = bool(ln_norm)
|
| 83 |
+
|
| 84 |
+
# 读取子表(谨慎读取)
|
| 85 |
+
try:
|
| 86 |
+
df = pd.read_excel(fpath)
|
| 87 |
+
except Exception as e:
|
| 88 |
+
print(f"❌ 无法读取文件(跳过) {fname}: {e}")
|
| 89 |
+
unmatched_list.append({
|
| 90 |
+
"file": fname,
|
| 91 |
+
"pinyin": pinyin_name,
|
| 92 |
+
"latin": latin_name,
|
| 93 |
+
"reason": f"读取失败: {e}"
|
| 94 |
+
})
|
| 95 |
+
continue
|
| 96 |
+
|
| 97 |
+
# 如果文件内容为空,也要保留(但不会添加中药表信息)
|
| 98 |
+
if df.empty:
|
| 99 |
+
# 仍插入三列,保证格式统一
|
| 100 |
+
df.insert(0, "Pinyin.Name", pinyin_name)
|
| 101 |
+
df.insert(1, "Chinese.Name", "")
|
| 102 |
+
df.insert(2, "Latin.Name", latin_name)
|
| 103 |
+
df["__source_file__"] = fname
|
| 104 |
+
all_dfs.append(df)
|
| 105 |
+
print(f"({idx}/{len(files)}) 空文件,已保留:{fname}")
|
| 106 |
+
continue
|
| 107 |
+
|
| 108 |
+
# 执行匹配(严格按你的规则)
|
| 109 |
+
matched_row = None
|
| 110 |
+
reason = ""
|
| 111 |
+
if use_pn and use_ln:
|
| 112 |
+
# 同时匹配 pn_norm AND ln_norm
|
| 113 |
+
matched = herb_df[(herb_df["pn_norm"] == pn_norm) & (herb_df["ln_norm"] == ln_norm)]
|
| 114 |
+
if not matched.empty:
|
| 115 |
+
matched_row = matched.iloc[0]
|
| 116 |
+
reason = "pn+ln 匹配成功"
|
| 117 |
+
else:
|
| 118 |
+
reason = "pn+ln 无匹配"
|
| 119 |
+
elif use_pn:
|
| 120 |
+
# 仅拼音匹配
|
| 121 |
+
matched = herb_df[herb_df["pn_norm"] == pn_norm]
|
| 122 |
+
if not matched.empty:
|
| 123 |
+
matched_row = matched.iloc[0]
|
| 124 |
+
reason = "仅 pn 匹配成功"
|
| 125 |
+
else:
|
| 126 |
+
reason = "仅 pn 无匹配"
|
| 127 |
+
elif use_ln:
|
| 128 |
+
# 仅拉丁匹配
|
| 129 |
+
matched = herb_df[herb_df["ln_norm"] == ln_norm]
|
| 130 |
+
if not matched.empty:
|
| 131 |
+
matched_row = matched.iloc[0]
|
| 132 |
+
reason = "仅 ln 匹配成功"
|
| 133 |
+
else:
|
| 134 |
+
reason = "仅 ln 无匹配"
|
| 135 |
+
else:
|
| 136 |
+
reason = "文件名无有效 pn/ln"
|
| 137 |
+
|
| 138 |
+
if matched_row is None:
|
| 139 |
+
# 未匹配到中药库表,但我们**仍然要保留该文件的所有记录**
|
| 140 |
+
chinese_name_val = ""
|
| 141 |
+
pinyin_write = pinyin_name
|
| 142 |
+
latin_write = latin_name
|
| 143 |
+
# 记录未匹配的文件,方便后续检查
|
| 144 |
+
unmatched_list.append({
|
| 145 |
+
"file": fname,
|
| 146 |
+
"pinyin": pinyin_name,
|
| 147 |
+
"latin": latin_name,
|
| 148 |
+
"reason": reason
|
| 149 |
+
})
|
| 150 |
+
else:
|
| 151 |
+
chinese_name_val = matched_row.get("Chinese.Name", "")
|
| 152 |
+
pinyin_write = matched_row.get("Pinyin.Name", pinyin_name)
|
| 153 |
+
latin_write = matched_row.get("Latin.Name", latin_name)
|
| 154 |
+
|
| 155 |
+
# 在每个 df 最前面插入中药信息列(保持原列顺序不变)
|
| 156 |
+
# 如果已有这些列名,为避免重复,先删除(大小写敏感)
|
| 157 |
+
for c in ["Pinyin.Name", "Chinese.Name", "Latin.Name"]:
|
| 158 |
+
if c in df.columns:
|
| 159 |
+
# 不覆盖已有列,改写列名保存原列
|
| 160 |
+
df.rename(columns={c: c + "_orig"}, inplace=True)
|
| 161 |
+
|
| 162 |
+
# 以统一顺序插入三列
|
| 163 |
+
df.insert(0, "Pinyin.Name", pinyin_write)
|
| 164 |
+
df.insert(1, "Chinese.Name", chinese_name_val)
|
| 165 |
+
df.insert(2, "Latin.Name", latin_write)
|
| 166 |
+
# 记录来源文件
|
| 167 |
+
df["__source_file__"] = fname
|
| 168 |
+
df["__match_reason__"] = reason
|
| 169 |
+
|
| 170 |
+
all_dfs.append(df)
|
| 171 |
+
|
| 172 |
+
if idx % 500 == 0 or idx == len(files):
|
| 173 |
+
print(f"({idx}/{len(files)}) 处理完成:{fname} ({reason})")
|
| 174 |
+
|
| 175 |
+
# === 合并所有 DataFrame ===
|
| 176 |
+
if not all_dfs:
|
| 177 |
+
print("⚠️ 未读取到任何有效数据,退出。")
|
| 178 |
+
raise SystemExit(1)
|
| 179 |
+
|
| 180 |
+
merged = pd.concat(all_dfs, ignore_index=True)
|
| 181 |
+
|
| 182 |
+
# === (可选)去重:用户要求保留所有内容,因此不去重 ====
|
| 183 |
+
# merged = merged.drop_duplicates()
|
| 184 |
+
|
| 185 |
+
# === 保存合并结果 ===
|
| 186 |
+
merged.to_csv(OUTPUT_CSV, index=False, encoding="utf-8-sig")
|
| 187 |
+
print(f"✅ 合并完成,共 {len(merged)} 条记录,已保存到:{OUTPUT_CSV}")
|
| 188 |
+
|
| 189 |
+
# === 保存未匹配文件清单(方便你审查) ===
|
| 190 |
+
um_df = pd.DataFrame(unmatched_list)
|
| 191 |
+
um_df.to_csv(UNMATCHED_LIST_CSV, index=False, encoding="utf-8-sig")
|
| 192 |
+
print(f"🔎 未匹配文件数:{len(unmatched_list)},列表已保存:{UNMATCHED_LIST_CSV}")
|
| 193 |
+
|
| 194 |
+
# 额外:打印少量示例帮助快速检查
|
| 195 |
+
print("\n示例未匹配(最多 10 条):")
|
| 196 |
+
print(um_df.head(10).to_string(index=False))
|
recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/DCABM/dcabm.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import os
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
def merge_excels_to_csv(input_dir, output_csv):
|
| 6 |
+
"""
|
| 7 |
+
汇总指定文件夹下所有xlsx表格为一个csv文件。
|
| 8 |
+
每个表格添加一列“Source”以标明来源文件名。
|
| 9 |
+
"""
|
| 10 |
+
all_dfs = []
|
| 11 |
+
files = sorted([f for f in os.listdir(input_dir) if f.endswith('.xlsx')])
|
| 12 |
+
print(f"📁 检测到 {len(files)} 个文件待合并")
|
| 13 |
+
|
| 14 |
+
for file in files:
|
| 15 |
+
file_path = os.path.join(input_dir, file)
|
| 16 |
+
try:
|
| 17 |
+
df = pd.read_excel(file_path, dtype=object)
|
| 18 |
+
if df.empty:
|
| 19 |
+
print(f"⚠️ {file} 是空表,跳过")
|
| 20 |
+
continue
|
| 21 |
+
df["Source"] = os.path.splitext(file)[0] # 添加来源列
|
| 22 |
+
all_dfs.append(df)
|
| 23 |
+
print(f"✅ 已加载:{file}({len(df)} 行)")
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(f"❌ 读取失败 {file}:{e}")
|
| 26 |
+
|
| 27 |
+
if not all_dfs:
|
| 28 |
+
print("❗ 未找到有效数据,未生成汇总表")
|
| 29 |
+
return
|
| 30 |
+
|
| 31 |
+
merged_df = pd.concat(all_dfs, ignore_index=True)
|
| 32 |
+
merged_df.to_csv(output_csv, index=False, encoding="utf-8-sig")
|
| 33 |
+
print(f"\n🎉 汇总完成,共 {len(merged_df)} 行数据,已保存至:\n{output_csv}")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if __name__ == "__main__":
|
| 37 |
+
input_dir = r"D:\2\111数据库\数据库-化合物\DCABM-TCM_Info" # 修改为你的结果文件夹
|
| 38 |
+
output_csv = r"D:\2\111数据库\汇总\DCABM\DCABM-TCM_Info_汇总.csv"
|
| 39 |
+
|
| 40 |
+
merge_excels_to_csv(input_dir, output_csv)
|
recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/ETCM2/etcm.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
ETCM2 汇总脚本 — 按拼音名精确匹配
|
| 4 |
+
规则:
|
| 5 |
+
- 文件名为拼音名(如 AnYe.xlsx)
|
| 6 |
+
- 按 pn_norm 精确匹配中药表中的“拼音名”
|
| 7 |
+
- 未匹配仍保留所有记录
|
| 8 |
+
输出:
|
| 9 |
+
- 合并 CSV(OUTPUT_CSV)
|
| 10 |
+
- 未匹配文件清单(UNMATCHED_LIST_CSV)
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import os
|
| 14 |
+
import re
|
| 15 |
+
import pandas as pd
|
| 16 |
+
|
| 17 |
+
# ========== 用户配置 ==========
|
| 18 |
+
HERB_PATH = r"D:\2\111数据库\中药表格\ETCM2.xlsx"
|
| 19 |
+
COMPOUND_INFO_DIR = r"D:\2\111数据库\数据库-化合物\ETCM2_Info"
|
| 20 |
+
OUTPUT_DIR = r"D:\2\111数据库\汇总\ETCM2"
|
| 21 |
+
OUTPUT_CSV = os.path.join(OUTPUT_DIR, "ETCM2_Info_汇总.csv")
|
| 22 |
+
UNMATCHED_LIST_CSV = os.path.join(OUTPUT_DIR, "ETCM2_unmatched_files.csv")
|
| 23 |
+
# ==============================
|
| 24 |
+
|
| 25 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 26 |
+
|
| 27 |
+
# === 标准化函数 ===
|
| 28 |
+
def normalize(s):
|
| 29 |
+
if pd.isna(s) or s is None:
|
| 30 |
+
return ""
|
| 31 |
+
return re.sub(r'\s+|[^a-zA-Z0-9]', '', str(s).lower())
|
| 32 |
+
|
| 33 |
+
# === 读取中药表并构建索引 ===
|
| 34 |
+
print("📘 读取中药原始表...")
|
| 35 |
+
herb_df = pd.read_excel(HERB_PATH, dtype=str)
|
| 36 |
+
if "拼音名" not in herb_df.columns:
|
| 37 |
+
raise ValueError(f"❌ 中药表缺少列 '拼音名',请检查 {HERB_PATH}")
|
| 38 |
+
|
| 39 |
+
herb_df["pn_norm"] = herb_df["拼音名"].apply(normalize)
|
| 40 |
+
print(f"✅ 中药表加载完成,共 {len(herb_df)} 条记录")
|
| 41 |
+
|
| 42 |
+
# === 遍历化合物文件夹 ===
|
| 43 |
+
print("🧩 开始合并 ETCM2 化合物信息...")
|
| 44 |
+
files = sorted([f for f in os.listdir(COMPOUND_INFO_DIR) if f.lower().endswith(".xlsx")])
|
| 45 |
+
print(f"发现 {len(files)} 个化合物表格文件。")
|
| 46 |
+
|
| 47 |
+
all_dfs = []
|
| 48 |
+
unmatched_list = []
|
| 49 |
+
|
| 50 |
+
for idx, fname in enumerate(files, 1):
|
| 51 |
+
fpath = os.path.join(COMPOUND_INFO_DIR, fname)
|
| 52 |
+
pinyin_name = os.path.splitext(fname)[0].strip()
|
| 53 |
+
pn_norm = normalize(pinyin_name)
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
df = pd.read_excel(fpath, dtype=object)
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print(f"❌ 无法读取文件 {fname}:{e}")
|
| 59 |
+
unmatched_list.append({
|
| 60 |
+
"file": fname,
|
| 61 |
+
"pinyin": pinyin_name,
|
| 62 |
+
"reason": f"读取失败:{e}"
|
| 63 |
+
})
|
| 64 |
+
continue
|
| 65 |
+
|
| 66 |
+
if df.empty:
|
| 67 |
+
print(f"⚠️ 空文件,已保留:{fname}")
|
| 68 |
+
df.insert(0, "Pinyin.Name", pinyin_name)
|
| 69 |
+
df.insert(1, "Chinese.Name", "")
|
| 70 |
+
df["__source_file__"] = fname
|
| 71 |
+
all_dfs.append(df)
|
| 72 |
+
continue
|
| 73 |
+
|
| 74 |
+
# 匹配中药表
|
| 75 |
+
matched_row = herb_df[herb_df["pn_norm"] == pn_norm]
|
| 76 |
+
if not matched_row.empty:
|
| 77 |
+
matched_row = matched_row.iloc[0]
|
| 78 |
+
chinese_name_val = matched_row.get("中文名", "")
|
| 79 |
+
match_reason = "pn 匹配成功"
|
| 80 |
+
else:
|
| 81 |
+
chinese_name_val = ""
|
| 82 |
+
match_reason = "pn 无匹配"
|
| 83 |
+
unmatched_list.append({
|
| 84 |
+
"file": fname,
|
| 85 |
+
"pinyin": pinyin_name,
|
| 86 |
+
"reason": match_reason
|
| 87 |
+
})
|
| 88 |
+
|
| 89 |
+
# 插入中药信息列
|
| 90 |
+
if "Pinyin.Name" in df.columns:
|
| 91 |
+
df.rename(columns={"Pinyin.Name": "Pinyin.Name_orig"}, inplace=True)
|
| 92 |
+
if "Chinese.Name" in df.columns:
|
| 93 |
+
df.rename(columns={"Chinese.Name": "Chinese.Name_orig"}, inplace=True)
|
| 94 |
+
|
| 95 |
+
df.insert(0, "Pinyin.Name", pinyin_name)
|
| 96 |
+
df.insert(1, "Chinese.Name", chinese_name_val)
|
| 97 |
+
df["__source_file__"] = fname
|
| 98 |
+
df["__match_reason__"] = match_reason
|
| 99 |
+
all_dfs.append(df)
|
| 100 |
+
|
| 101 |
+
if idx % 200 == 0 or idx == len(files):
|
| 102 |
+
print(f"({idx}/{len(files)}) 已处理:{fname} ({match_reason})")
|
| 103 |
+
|
| 104 |
+
# === 汇总保存 ===
|
| 105 |
+
if not all_dfs:
|
| 106 |
+
print("⚠️ 未读取到任何有效数据,退出。")
|
| 107 |
+
raise SystemExit(1)
|
| 108 |
+
|
| 109 |
+
merged = pd.concat(all_dfs, ignore_index=True)
|
| 110 |
+
merged.to_csv(OUTPUT_CSV, index=False, encoding="utf-8-sig")
|
| 111 |
+
print(f"\n🎉 汇总完成,共 {len(merged)} 条记录,已保存至:{OUTPUT_CSV}")
|
| 112 |
+
|
| 113 |
+
# === 输出未匹配文件清单 ===
|
| 114 |
+
um_df = pd.DataFrame(unmatched_list)
|
| 115 |
+
um_df.to_csv(UNMATCHED_LIST_CSV, index=False, encoding="utf-8-sig")
|
| 116 |
+
print(f"🔎 未匹配文件数:{len(unmatched_list)},清单已保存:{UNMATCHED_LIST_CSV}")
|
| 117 |
+
|
| 118 |
+
if len(unmatched_list) > 0:
|
| 119 |
+
print("\n📋 示例未匹配文件(前 10 条):")
|
| 120 |
+
print(um_df.head(10).to_string(index=False))
|
recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/HERB2/herb.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
HERB2 汇总脚本(升级版)— 先按数据库ID匹配,匹配不上再按中文名匹配
|
| 4 |
+
文件命名格式:中文名_HERB004754_info.xlsx
|
| 5 |
+
"""
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
# ========== 用户配置 ==========
|
| 11 |
+
HERB_PATH = r"D:\2\111数据库\中药表格\HERB2.xlsx"
|
| 12 |
+
COMPOUND_INFO_DIR = r"D:\2\111数据库\数据库-化合物\HERB2_Info"
|
| 13 |
+
OUTPUT_DIR = r"D:\2\111数据库\汇总\HERB2"
|
| 14 |
+
OUTPUT_CSV = os.path.join(OUTPUT_DIR, "HERB2_Info_汇总.csv")
|
| 15 |
+
UNMATCHED_LIST_CSV = os.path.join(OUTPUT_DIR, "HERB2_unmatched_files.csv")
|
| 16 |
+
# ==============================
|
| 17 |
+
|
| 18 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 19 |
+
|
| 20 |
+
def normalize_cn(s):
|
| 21 |
+
"""去除空格、标点符号"""
|
| 22 |
+
if pd.isna(s) or s is None:
|
| 23 |
+
return ""
|
| 24 |
+
return re.sub(r"[\s·、,。;:‘’“”《》()()【】\[】『』]", "", str(s).strip())
|
| 25 |
+
|
| 26 |
+
def parse_filename(fname):
|
| 27 |
+
"""
|
| 28 |
+
从文件名提取中文名与数据库ID
|
| 29 |
+
三叉凤尾蕨_HERB004754_info.xlsx → ("三叉凤尾蕨", "HERB004754")
|
| 30 |
+
"""
|
| 31 |
+
name = os.path.splitext(fname)[0]
|
| 32 |
+
parts = name.split("_")
|
| 33 |
+
if len(parts) >= 2:
|
| 34 |
+
cn_name = parts[0]
|
| 35 |
+
db_id = parts[1]
|
| 36 |
+
return cn_name, db_id
|
| 37 |
+
return None, None
|
| 38 |
+
|
| 39 |
+
def is_special_batch_filename(fname):
|
| 40 |
+
"""判断是否为批量命名文件"""
|
| 41 |
+
low = fname.lower()
|
| 42 |
+
if 'ingredient' in low and re.search(r'\d{4}[_-]\d{1,2}[_-]\d{1,2}', low):
|
| 43 |
+
return True
|
| 44 |
+
base = os.path.splitext(low)[0]
|
| 45 |
+
if base.endswith('_info'):
|
| 46 |
+
return False
|
| 47 |
+
if '_info' in base and (base.count('_') >= 3 or re.search(r'\d', base)):
|
| 48 |
+
return True
|
| 49 |
+
return False
|
| 50 |
+
|
| 51 |
+
# === 读取中药表 ===
|
| 52 |
+
print("📘 读取中药表...")
|
| 53 |
+
herb_df = pd.read_excel(HERB_PATH, dtype=str)
|
| 54 |
+
herb_df.columns = herb_df.columns.str.strip()
|
| 55 |
+
required_cols = ["Herb_id", "Herb_pinyin_name", "Herb_cn_name", "Herb_latin_name"]
|
| 56 |
+
for col in required_cols:
|
| 57 |
+
if col not in herb_df.columns:
|
| 58 |
+
raise ValueError(f"❌ 缺少列:{col}")
|
| 59 |
+
|
| 60 |
+
herb_df["cn_norm"] = herb_df["Herb_cn_name"].apply(normalize_cn)
|
| 61 |
+
print(f"✅ 中药表加载成功,共 {len(herb_df)} 条记录")
|
| 62 |
+
|
| 63 |
+
# === 遍历化合物表 ===
|
| 64 |
+
print("🧩 开始遍历化合物文件夹...")
|
| 65 |
+
files = sorted([f for f in os.listdir(COMPOUND_INFO_DIR) if f.lower().endswith(".xlsx")])
|
| 66 |
+
print(f"检测到 {len(files)} 个文件")
|
| 67 |
+
|
| 68 |
+
all_dfs = []
|
| 69 |
+
unmatched_list = []
|
| 70 |
+
|
| 71 |
+
for idx, fname in enumerate(files, 1):
|
| 72 |
+
fpath = os.path.join(COMPOUND_INFO_DIR, fname)
|
| 73 |
+
if is_special_batch_filename(fname):
|
| 74 |
+
unmatched_list.append({"file": fname, "reason": "跳过 - 批量命名"})
|
| 75 |
+
print(f"({idx}/{len(files)}) 跳过批量命名文件:{fname}")
|
| 76 |
+
continue
|
| 77 |
+
|
| 78 |
+
cn_name, db_id = parse_filename(fname)
|
| 79 |
+
if not cn_name:
|
| 80 |
+
unmatched_list.append({"file": fname, "reason": "文件名无法解析中文名"})
|
| 81 |
+
print(f"({idx}/{len(files)}) 无法解析中文名:{fname}")
|
| 82 |
+
continue
|
| 83 |
+
|
| 84 |
+
cn_norm = normalize_cn(cn_name)
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
df = pd.read_excel(fpath, dtype=object)
|
| 88 |
+
except Exception as e:
|
| 89 |
+
unmatched_list.append({"file": fname, "reason": f"读取失败: {e}"})
|
| 90 |
+
print(f"({idx}/{len(files)}) ❌ 读取失败:{fname}")
|
| 91 |
+
continue
|
| 92 |
+
|
| 93 |
+
if df.empty:
|
| 94 |
+
unmatched_list.append({"file": fname, "reason": "空表"})
|
| 95 |
+
print(f"({idx}/{len(files)}) ⚠️ 空表:{fname}")
|
| 96 |
+
continue
|
| 97 |
+
|
| 98 |
+
# ===== ① 按数据库ID匹配 =====
|
| 99 |
+
matched = herb_df[herb_df["Herb_id"].str.lower() == str(db_id).lower()] if db_id else pd.DataFrame()
|
| 100 |
+
|
| 101 |
+
# ===== ② 若未匹配,再按中文名匹配 =====
|
| 102 |
+
if matched.empty:
|
| 103 |
+
matched = herb_df[herb_df["cn_norm"] == cn_norm]
|
| 104 |
+
match_method = "中文名匹配"
|
| 105 |
+
else:
|
| 106 |
+
match_method = "ID匹配"
|
| 107 |
+
|
| 108 |
+
# ===== ③ 若仍未匹配,记录未匹配文件 =====
|
| 109 |
+
if matched.empty:
|
| 110 |
+
unmatched_list.append({"file": fname, "reason": f"未匹配(ID={db_id}, 中文名={cn_name})"})
|
| 111 |
+
print(f"({idx}/{len(files)}) 未匹配:{fname} ({cn_name})")
|
| 112 |
+
continue
|
| 113 |
+
|
| 114 |
+
matched_row = matched.iloc[0]
|
| 115 |
+
herb_id = matched_row["Herb_id"]
|
| 116 |
+
herb_py = matched_row["Herb_pinyin_name"]
|
| 117 |
+
herb_cn = matched_row["Herb_cn_name"]
|
| 118 |
+
herb_latin = matched_row["Herb_latin_name"]
|
| 119 |
+
|
| 120 |
+
# 插入信息列
|
| 121 |
+
for col in ["Herb_id", "Herb_pinyin_name", "Herb_cn_name", "Herb_latin_name"]:
|
| 122 |
+
if col in df.columns:
|
| 123 |
+
df.rename(columns={col: col + "_orig"}, inplace=True)
|
| 124 |
+
|
| 125 |
+
df.insert(0, "Herb_id", herb_id)
|
| 126 |
+
df.insert(1, "Herb_pinyin_name", herb_py)
|
| 127 |
+
df.insert(2, "Herb_cn_name", herb_cn)
|
| 128 |
+
df.insert(3, "Herb_latin_name", herb_latin)
|
| 129 |
+
df["__source_file__"] = fname
|
| 130 |
+
df["__match_reason__"] = match_method
|
| 131 |
+
|
| 132 |
+
all_dfs.append(df)
|
| 133 |
+
print(f"({idx}/{len(files)}) ✅ 匹配成功[{match_method}]:{fname} -> {herb_cn} ({herb_py})")
|
| 134 |
+
|
| 135 |
+
# === 汇总输出 ===
|
| 136 |
+
if all_dfs:
|
| 137 |
+
merged = pd.concat(all_dfs, ignore_index=True)
|
| 138 |
+
merged.to_csv(OUTPUT_CSV, index=False, encoding="utf-8-sig")
|
| 139 |
+
print(f"\n🎉 汇总完成,共 {len(merged)} 行,来自 {len(all_dfs)} 个文件")
|
| 140 |
+
print(f"📁 输出文件:{OUTPUT_CSV}")
|
| 141 |
+
else:
|
| 142 |
+
print("\n⚠️ 无任何文件被汇总,请检查文件命名或匹配逻辑")
|
| 143 |
+
|
| 144 |
+
# === 输出未匹配清单 ===
|
| 145 |
+
if unmatched_list:
|
| 146 |
+
um_df = pd.DataFrame(unmatched_list)
|
| 147 |
+
um_df.to_csv(UNMATCHED_LIST_CSV, index=False, encoding="utf-8-sig")
|
| 148 |
+
print(f"🔎 未匹配/跳过文件:{len(unmatched_list)} 个,清单已保存:{UNMATCHED_LIST_CSV}")
|
| 149 |
+
else:
|
| 150 |
+
print("✅ 所有文件均成功匹配")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/SymMap/symmap.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
SymMap 汇总脚本 — 按中文名匹配
|
| 4 |
+
文件命名格式:中文名+Ingredient.xlsx
|
| 5 |
+
"""
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
# ========== 用户配置 ==========
|
| 11 |
+
HERB_PATH = r"D:\2\111数据库\中药表格\SymMap.xlsx"
|
| 12 |
+
COMPOUND_INFO_DIR = r"D:\2\111数据库\数据库-化合物\SymMap_Info"
|
| 13 |
+
OUTPUT_DIR = r"D:\2\111数据库\汇总\SymMap"
|
| 14 |
+
OUTPUT_CSV = os.path.join(OUTPUT_DIR, "SymMap_Info_汇总.csv")
|
| 15 |
+
UNMATCHED_LIST_CSV = os.path.join(OUTPUT_DIR, "SymMap_unmatched_files.csv")
|
| 16 |
+
# ==============================
|
| 17 |
+
|
| 18 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 19 |
+
|
| 20 |
+
def normalize_cn(s):
|
| 21 |
+
"""去除空格、标点符号"""
|
| 22 |
+
if pd.isna(s) or s is None:
|
| 23 |
+
return ""
|
| 24 |
+
return re.sub(r"[\s·、,。;:‘’“”《》()()【】\[】『』+]", "", str(s).strip())
|
| 25 |
+
|
| 26 |
+
def parse_filename(fname):
|
| 27 |
+
"""
|
| 28 |
+
从文件名提取中文名(例如:阿胶+Ingredient.xlsx → 阿胶)
|
| 29 |
+
"""
|
| 30 |
+
name = os.path.splitext(fname)[0]
|
| 31 |
+
# 去掉 +Ingredient 或 _Ingredient 等后缀
|
| 32 |
+
cn_name = re.split(r'[\+_]+ingredient', name, flags=re.IGNORECASE)[0]
|
| 33 |
+
return cn_name.strip()
|
| 34 |
+
|
| 35 |
+
# === 读取中药表 ===
|
| 36 |
+
print("📘 读取中药表...")
|
| 37 |
+
herb_df = pd.read_excel(HERB_PATH, dtype=str)
|
| 38 |
+
herb_df.columns = herb_df.columns.str.strip()
|
| 39 |
+
|
| 40 |
+
required_cols = ["Chinese_name", "Pinyin_name", "Latin_name"]
|
| 41 |
+
for col in required_cols:
|
| 42 |
+
if col not in herb_df.columns:
|
| 43 |
+
raise ValueError(f"❌ 缺少列:{col}")
|
| 44 |
+
|
| 45 |
+
herb_df["cn_norm"] = herb_df["Chinese_name"].apply(normalize_cn)
|
| 46 |
+
print(f"✅ 中药表加载成功,共 {len(herb_df)} 条记录")
|
| 47 |
+
|
| 48 |
+
# === 遍历化合物表 ===
|
| 49 |
+
print("🧩 开始遍历化合物文件夹...")
|
| 50 |
+
files = sorted([f for f in os.listdir(COMPOUND_INFO_DIR) if f.lower().endswith(".xlsx")])
|
| 51 |
+
print(f"检测到 {len(files)} 个文件")
|
| 52 |
+
|
| 53 |
+
all_dfs = []
|
| 54 |
+
unmatched_list = []
|
| 55 |
+
|
| 56 |
+
for idx, fname in enumerate(files, 1):
|
| 57 |
+
fpath = os.path.join(COMPOUND_INFO_DIR, fname)
|
| 58 |
+
cn_name = parse_filename(fname)
|
| 59 |
+
if not cn_name:
|
| 60 |
+
unmatched_list.append({"file": fname, "reason": "无法解析中文名"})
|
| 61 |
+
print(f"({idx}/{len(files)}) 无法解析中文名:{fname}")
|
| 62 |
+
continue
|
| 63 |
+
|
| 64 |
+
cn_norm = normalize_cn(cn_name)
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
df = pd.read_excel(fpath, dtype=object)
|
| 68 |
+
except Exception as e:
|
| 69 |
+
unmatched_list.append({"file": fname, "reason": f"读取失败: {e}"})
|
| 70 |
+
print(f"({idx}/{len(files)}) ❌ 读取失败:{fname}")
|
| 71 |
+
continue
|
| 72 |
+
|
| 73 |
+
if df.empty:
|
| 74 |
+
unmatched_list.append({"file": fname, "reason": "空表"})
|
| 75 |
+
print(f"({idx}/{len(files)}) ⚠️ 空表:{fname}")
|
| 76 |
+
continue
|
| 77 |
+
|
| 78 |
+
# ===== 按中文名匹配 =====
|
| 79 |
+
matched = herb_df[herb_df["cn_norm"] == cn_norm]
|
| 80 |
+
|
| 81 |
+
if matched.empty:
|
| 82 |
+
unmatched_list.append({"file": fname, "reason": f"未匹配(中文名={cn_name})"})
|
| 83 |
+
print(f"({idx}/{len(files)}) 未匹配:{fname} ({cn_name})")
|
| 84 |
+
continue
|
| 85 |
+
|
| 86 |
+
matched_row = matched.iloc[0]
|
| 87 |
+
herb_cn = matched_row["Chinese_name"]
|
| 88 |
+
herb_py = matched_row["Pinyin_name"]
|
| 89 |
+
herb_latin = matched_row["Latin_name"]
|
| 90 |
+
|
| 91 |
+
# 插入三列
|
| 92 |
+
for col in ["Chinese_name", "Pinyin_name", "Latin_name"]:
|
| 93 |
+
if col in df.columns:
|
| 94 |
+
df.rename(columns={col: col + "_orig"}, inplace=True)
|
| 95 |
+
|
| 96 |
+
df.insert(0, "Chinese_name", herb_cn)
|
| 97 |
+
df.insert(1, "Pinyin_name", herb_py)
|
| 98 |
+
df.insert(2, "Latin_name", herb_latin)
|
| 99 |
+
df["__source_file__"] = fname
|
| 100 |
+
df["__match_reason__"] = "中文名匹配"
|
| 101 |
+
|
| 102 |
+
all_dfs.append(df)
|
| 103 |
+
print(f"({idx}/{len(files)}) ✅ 匹配成功:{fname} -> {herb_cn} ({herb_py})")
|
| 104 |
+
|
| 105 |
+
# === 汇总输出 ===
|
| 106 |
+
if all_dfs:
|
| 107 |
+
merged = pd.concat(all_dfs, ignore_index=True)
|
| 108 |
+
merged.to_csv(OUTPUT_CSV, index=False, encoding="utf-8-sig")
|
| 109 |
+
print(f"\n🎉 汇总完成,共 {len(merged)} 行,来自 {len(all_dfs)} 个文件")
|
| 110 |
+
print(f"📁 输出文件:{OUTPUT_CSV}")
|
| 111 |
+
else:
|
| 112 |
+
print("\n⚠️ 无任何文件被汇总,请检查文件命名或匹配逻辑")
|
| 113 |
+
|
| 114 |
+
# === 输出未匹配清单 ===
|
| 115 |
+
if unmatched_list:
|
| 116 |
+
um_df = pd.DataFrame(unmatched_list)
|
| 117 |
+
um_df.to_csv(UNMATCHED_LIST_CSV, index=False, encoding="utf-8-sig")
|
| 118 |
+
print(f"🔎 未匹配/跳过文件:{len(unmatched_list)} 个,清单已保存:{UNMATCHED_LIST_CSV}")
|
| 119 |
+
else:
|
| 120 |
+
print("✅ 所有文件均成功匹配")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/TCMIO/tcmio.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
TCMIO 汇总脚本 — 按中文名匹配
|
| 4 |
+
文件命名格式:中文名_数据库id.xlsx,例如:
|
| 5 |
+
阿魏_278.xlsx
|
| 6 |
+
_鲜_地黄_123.xlsx ← 对应中药名为 (鲜)地黄
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import pandas as pd
|
| 12 |
+
|
| 13 |
+
# ========== 用户配置 ==========
|
| 14 |
+
HERB_PATH = r"D:\2\111数据库\中药表格\TCMIO.xlsx"
|
| 15 |
+
COMPOUND_INFO_DIR = r"D:\2\111数据库\数据库-化合物\TCMIO_Info"
|
| 16 |
+
OUTPUT_DIR = r"D:\2\111数据库\汇总\TCMIO"
|
| 17 |
+
OUTPUT_CSV = os.path.join(OUTPUT_DIR, "TCMIO_Info_汇总.csv")
|
| 18 |
+
UNMATCHED_LIST_CSV = os.path.join(OUTPUT_DIR, "TCMIO_unmatched_files.csv")
|
| 19 |
+
# ==============================
|
| 20 |
+
|
| 21 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 22 |
+
|
| 23 |
+
def normalize_cn(s):
|
| 24 |
+
"""去除空格、标点符号"""
|
| 25 |
+
if pd.isna(s) or s is None:
|
| 26 |
+
return ""
|
| 27 |
+
return re.sub(r"[\s·、,。;:‘’“”《》()()【】\[】『』+]", "", str(s).strip())
|
| 28 |
+
|
| 29 |
+
def parse_filename(fname):
|
| 30 |
+
"""
|
| 31 |
+
从文件名提取中文名:
|
| 32 |
+
- 例如:阿魏_278.xlsx → 阿魏
|
| 33 |
+
- 例如:_鲜_地黄_278.xlsx → (鲜)地黄
|
| 34 |
+
"""
|
| 35 |
+
name = os.path.splitext(fname)[0]
|
| 36 |
+
# 去掉末尾的数据库ID
|
| 37 |
+
parts = name.split("_")
|
| 38 |
+
# 去除空的分隔符
|
| 39 |
+
parts = [p for p in parts if p]
|
| 40 |
+
if not parts:
|
| 41 |
+
return ""
|
| 42 |
+
# 特殊情况处理:文件名含“鲜”作为修饰词时
|
| 43 |
+
if len(parts) >= 2 and parts[0] == "鲜":
|
| 44 |
+
cn_name = f"(鲜){parts[1]}"
|
| 45 |
+
elif len(parts) >= 3 and parts[1] == "鲜":
|
| 46 |
+
cn_name = f"(鲜){parts[2]}"
|
| 47 |
+
else:
|
| 48 |
+
cn_name = parts[0]
|
| 49 |
+
return cn_name.strip()
|
| 50 |
+
|
| 51 |
+
# === 读取中药表 ===
|
| 52 |
+
print("📘 读取中药表...")
|
| 53 |
+
herb_df = pd.read_excel(HERB_PATH, dtype=str)
|
| 54 |
+
herb_df.columns = herb_df.columns.str.strip()
|
| 55 |
+
|
| 56 |
+
required_cols = ["id", "chinese_name", "pinyin_name"]
|
| 57 |
+
for col in required_cols:
|
| 58 |
+
if col not in herb_df.columns:
|
| 59 |
+
raise ValueError(f"❌ 缺少列:{col}")
|
| 60 |
+
|
| 61 |
+
herb_df["cn_norm"] = herb_df["chinese_name"].apply(normalize_cn)
|
| 62 |
+
print(f"✅ 中药表加载成功,共 {len(herb_df)} 条记录")
|
| 63 |
+
|
| 64 |
+
# === 遍历化合物表 ===
|
| 65 |
+
print("🧩 开始遍历化合物文件夹...")
|
| 66 |
+
files = sorted([f for f in os.listdir(COMPOUND_INFO_DIR) if f.lower().endswith(".xlsx")])
|
| 67 |
+
print(f"检测到 {len(files)} 个文件")
|
| 68 |
+
|
| 69 |
+
all_dfs = []
|
| 70 |
+
unmatched_list = []
|
| 71 |
+
|
| 72 |
+
for idx, fname in enumerate(files, 1):
|
| 73 |
+
fpath = os.path.join(COMPOUND_INFO_DIR, fname)
|
| 74 |
+
cn_name = parse_filename(fname)
|
| 75 |
+
if not cn_name:
|
| 76 |
+
unmatched_list.append({"file": fname, "reason": "无法解析中文名"})
|
| 77 |
+
print(f"({idx}/{len(files)}) 无法解析中文名:{fname}")
|
| 78 |
+
continue
|
| 79 |
+
|
| 80 |
+
cn_norm = normalize_cn(cn_name)
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
df = pd.read_excel(fpath, dtype=object)
|
| 84 |
+
except Exception as e:
|
| 85 |
+
unmatched_list.append({"file": fname, "reason": f"读取失败: {e}"})
|
| 86 |
+
print(f"({idx}/{len(files)}) ❌ 读取失败:{fname}")
|
| 87 |
+
continue
|
| 88 |
+
|
| 89 |
+
if df.empty:
|
| 90 |
+
unmatched_list.append({"file": fname, "reason": "空表"})
|
| 91 |
+
print(f"({idx}/{len(files)}) ⚠️ 空表:{fname}")
|
| 92 |
+
continue
|
| 93 |
+
|
| 94 |
+
# ===== 按中文名匹配 =====
|
| 95 |
+
matched = herb_df[herb_df["cn_norm"] == cn_norm]
|
| 96 |
+
|
| 97 |
+
if matched.empty:
|
| 98 |
+
unmatched_list.append({"file": fname, "reason": f"未匹配(中文名={cn_name})"})
|
| 99 |
+
print(f"({idx}/{len(files)}) 未匹配:{fname} ({cn_name})")
|
| 100 |
+
continue
|
| 101 |
+
|
| 102 |
+
matched_row = matched.iloc[0]
|
| 103 |
+
herb_id = matched_row["id"]
|
| 104 |
+
herb_cn = matched_row["chinese_name"]
|
| 105 |
+
herb_py = matched_row["pinyin_name"]
|
| 106 |
+
|
| 107 |
+
# 插入三列
|
| 108 |
+
for col in ["id", "chinese_name", "pinyin_name"]:
|
| 109 |
+
if col in df.columns:
|
| 110 |
+
df.rename(columns={col: col + "_orig"}, inplace=True)
|
| 111 |
+
|
| 112 |
+
df.insert(0, "id", herb_id)
|
| 113 |
+
df.insert(1, "chinese_name", herb_cn)
|
| 114 |
+
df.insert(2, "pinyin_name", herb_py)
|
| 115 |
+
df["__source_file__"] = fname
|
| 116 |
+
df["__match_reason__"] = "中文名匹配"
|
| 117 |
+
|
| 118 |
+
all_dfs.append(df)
|
| 119 |
+
print(f"({idx}/{len(files)}) ✅ 匹配成功:{fname} -> {herb_cn} ({herb_py})")
|
| 120 |
+
|
| 121 |
+
# === 汇总输出 ===
|
| 122 |
+
if all_dfs:
|
| 123 |
+
merged = pd.concat(all_dfs, ignore_index=True)
|
| 124 |
+
merged.to_csv(OUTPUT_CSV, index=False, encoding="utf-8-sig")
|
| 125 |
+
print(f"\n🎉 汇总完成,共 {len(merged)} 行,来自 {len(all_dfs)} 个文件")
|
| 126 |
+
print(f"📁 输出文件:{OUTPUT_CSV}")
|
| 127 |
+
else:
|
| 128 |
+
print("\n⚠️ 无任何文件被汇总,请检查文件命名或匹配逻辑")
|
| 129 |
+
|
| 130 |
+
# === 输出未匹配清单 ===
|
| 131 |
+
if unmatched_list:
|
| 132 |
+
um_df = pd.DataFrame(unmatched_list)
|
| 133 |
+
um_df.to_csv(UNMATCHED_LIST_CSV, index=False, encoding="utf-8-sig")
|
| 134 |
+
print(f"🔎 未匹配/跳过文件:{len(unmatched_list)} 个,清单已保存:{UNMATCHED_LIST_CSV}")
|
| 135 |
+
else:
|
| 136 |
+
print("✅ 所有文件均成功匹配")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/TM-MC/tmmc.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
TM-MC 汇总脚本 — 先按拉丁名匹配,再按中文名匹配
|
| 4 |
+
文件命名格式:中文名_拉丁名.xlsx,例如:
|
| 5 |
+
龙胆_Gentianae Scabrae Radix et Rhizoma.xlsx
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import re
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
# ========== 用户配置 ==========
|
| 13 |
+
HERB_PATH = r"D:\2\111数据库\中药表格\TM-MC.xlsx"
|
| 14 |
+
COMPOUND_INFO_DIR = r"D:\2\111数据库\数据库-化合物\TM-MC_Info"
|
| 15 |
+
OUTPUT_DIR = r"D:\2\111数据库\汇总\TM-MC"
|
| 16 |
+
OUTPUT_CSV = os.path.join(OUTPUT_DIR, "TM-MC_Info_汇总.csv")
|
| 17 |
+
UNMATCHED_LIST_CSV = os.path.join(OUTPUT_DIR, "TM-MC_unmatched_files.csv")
|
| 18 |
+
# ==============================
|
| 19 |
+
|
| 20 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 21 |
+
|
| 22 |
+
def normalize_cn(s):
|
| 23 |
+
"""去除空格、标点符号"""
|
| 24 |
+
if pd.isna(s) or s is None:
|
| 25 |
+
return ""
|
| 26 |
+
return re.sub(r"[\s·、,。;:‘’“”《》()()【】\[】『』+]", "", str(s).strip())
|
| 27 |
+
|
| 28 |
+
def normalize_latin(s):
|
| 29 |
+
"""标准化拉丁名:去除多余空格、大小写不敏感"""
|
| 30 |
+
if pd.isna(s) or s is None:
|
| 31 |
+
return ""
|
| 32 |
+
return re.sub(r"\s+", " ", str(s).strip().lower())
|
| 33 |
+
|
| 34 |
+
def parse_filename(fname):
|
| 35 |
+
"""
|
| 36 |
+
从文件名提取中文名和拉丁名:
|
| 37 |
+
- 例如:龙胆_Gentianae Scabrae Radix et Rhizoma.xlsx → (龙胆, Gentianae Scabrae Radix et Rhizoma)
|
| 38 |
+
"""
|
| 39 |
+
name = os.path.splitext(fname)[0]
|
| 40 |
+
parts = name.split("_", 1)
|
| 41 |
+
if len(parts) == 2:
|
| 42 |
+
cn_name = parts[0].strip()
|
| 43 |
+
latin_name = parts[1].strip()
|
| 44 |
+
else:
|
| 45 |
+
cn_name = name.strip()
|
| 46 |
+
latin_name = ""
|
| 47 |
+
return cn_name, latin_name
|
| 48 |
+
|
| 49 |
+
# === 读取中药表 ===
|
| 50 |
+
print("📘 读取中药表...")
|
| 51 |
+
herb_df = pd.read_excel(HERB_PATH, dtype=str)
|
| 52 |
+
herb_df.columns = herb_df.columns.str.strip().str.upper()
|
| 53 |
+
|
| 54 |
+
required_cols = ["LATIN", "CHINESE", "PINYIN"]
|
| 55 |
+
for col in required_cols:
|
| 56 |
+
if col not in herb_df.columns:
|
| 57 |
+
raise ValueError(f"❌ 缺少列:{col}")
|
| 58 |
+
|
| 59 |
+
# 预处理
|
| 60 |
+
herb_df["LATIN_NORM"] = herb_df["LATIN"].apply(normalize_latin)
|
| 61 |
+
herb_df["CN_NORM"] = herb_df["CHINESE"].apply(normalize_cn)
|
| 62 |
+
|
| 63 |
+
print(f"✅ 中药表加载成功,共 {len(herb_df)} 条记录")
|
| 64 |
+
|
| 65 |
+
# === 遍历化合物表 ===
|
| 66 |
+
print("🧩 开始遍历化合物文件夹...")
|
| 67 |
+
files = sorted([f for f in os.listdir(COMPOUND_INFO_DIR) if f.lower().endswith(".xlsx")])
|
| 68 |
+
print(f"检测到 {len(files)} 个文件")
|
| 69 |
+
|
| 70 |
+
all_dfs = []
|
| 71 |
+
unmatched_list = []
|
| 72 |
+
|
| 73 |
+
for idx, fname in enumerate(files, 1):
|
| 74 |
+
fpath = os.path.join(COMPOUND_INFO_DIR, fname)
|
| 75 |
+
cn_name, latin_name = parse_filename(fname)
|
| 76 |
+
cn_norm = normalize_cn(cn_name)
|
| 77 |
+
latin_norm = normalize_latin(latin_name)
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
df = pd.read_excel(fpath, dtype=object)
|
| 81 |
+
except Exception as e:
|
| 82 |
+
unmatched_list.append({"file": fname, "reason": f"读取失败: {e}"})
|
| 83 |
+
print(f"({idx}/{len(files)}) ❌ 读取失败:{fname}")
|
| 84 |
+
continue
|
| 85 |
+
|
| 86 |
+
if df.empty:
|
| 87 |
+
unmatched_list.append({"file": fname, "reason": "空表"})
|
| 88 |
+
print(f"({idx}/{len(files)}) ⚠️ 空表:{fname}")
|
| 89 |
+
continue
|
| 90 |
+
|
| 91 |
+
# ===== 优先按拉丁名匹配 =====
|
| 92 |
+
matched = herb_df[herb_df["LATIN_NORM"] == latin_norm]
|
| 93 |
+
match_reason = "拉丁名匹配"
|
| 94 |
+
|
| 95 |
+
# 若拉丁名匹配不到,再按中文名匹配
|
| 96 |
+
if matched.empty and cn_norm:
|
| 97 |
+
matched = herb_df[herb_df["CN_NORM"] == cn_norm]
|
| 98 |
+
match_reason = "中文名匹配"
|
| 99 |
+
|
| 100 |
+
if matched.empty:
|
| 101 |
+
unmatched_list.append({"file": fname, "reason": f"未匹配(中文名={cn_name}, 拉丁名={latin_name})"})
|
| 102 |
+
print(f"({idx}/{len(files)}) 未匹配:{fname} ({cn_name}, {latin_name})")
|
| 103 |
+
continue
|
| 104 |
+
|
| 105 |
+
matched_row = matched.iloc[0]
|
| 106 |
+
herb_latin = matched_row["LATIN"]
|
| 107 |
+
herb_cn = matched_row["CHINESE"]
|
| 108 |
+
herb_py = matched_row["PINYIN"]
|
| 109 |
+
|
| 110 |
+
# 插入三列(若重复则改名)
|
| 111 |
+
for col in ["LATIN", "CHINESE", "PINYIN"]:
|
| 112 |
+
if col in df.columns:
|
| 113 |
+
df.rename(columns={col: col + "_orig"}, inplace=True)
|
| 114 |
+
|
| 115 |
+
df.insert(0, "LATIN", herb_latin)
|
| 116 |
+
df.insert(1, "CHINESE", herb_cn)
|
| 117 |
+
df.insert(2, "PINYIN", herb_py)
|
| 118 |
+
df["__source_file__"] = fname
|
| 119 |
+
df["__match_reason__"] = match_reason
|
| 120 |
+
|
| 121 |
+
all_dfs.append(df)
|
| 122 |
+
print(f"({idx}/{len(files)}) ✅ {match_reason}:{fname} -> {herb_cn} ({herb_py})")
|
| 123 |
+
|
| 124 |
+
# === 汇总输出 ===
|
| 125 |
+
if all_dfs:
|
| 126 |
+
merged = pd.concat(all_dfs, ignore_index=True)
|
| 127 |
+
merged.to_csv(OUTPUT_CSV, index=False, encoding="utf-8-sig")
|
| 128 |
+
print(f"\n🎉 汇总完成,共 {len(merged)} 行,来自 {len(all_dfs)} 个文件")
|
| 129 |
+
print(f"📁 输出文件:{OUTPUT_CSV}")
|
| 130 |
+
else:
|
| 131 |
+
print("\n⚠️ 无任何文件被汇总,请检查文件命名或匹配逻辑")
|
| 132 |
+
|
| 133 |
+
# === 输出未匹配清单 ===
|
| 134 |
+
if unmatched_list:
|
| 135 |
+
um_df = pd.DataFrame(unmatched_list)
|
| 136 |
+
um_df.to_csv(UNMATCHED_LIST_CSV, index=False, encoding="utf-8-sig")
|
| 137 |
+
print(f"🔎 未匹配/跳过文件:{len(unmatched_list)} 个,清单已保存:{UNMATCHED_LIST_CSV}")
|
| 138 |
+
else:
|
| 139 |
+
print("✅ 所有文件均成功匹配")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/herb_id.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
herb_id_interactive.py - 版本:沿革(词干)匹配优先,忽略汇总表原有herb_id
|
| 4 |
+
- 默认路径写在脚本顶部(修改为你本地路径后保存)
|
| 5 |
+
- 运行时交互式提示:粘贴汇总表列头(中文名、拉丁名、拼音名)
|
| 6 |
+
- 输出:{DBNAME}_id.csv 与 {DBNAME}_unmatched.xlsx
|
| 7 |
+
依赖:pandas, openpyxl
|
| 8 |
+
"""
|
| 9 |
+
import re, sys, time
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import pandas as pd
|
| 12 |
+
from collections import defaultdict, Counter
|
| 13 |
+
|
| 14 |
+
# ========== 默认路径(请按需修改) ==========
|
| 15 |
+
SUMMARY_FILE = r"D:\2\111数据库\原始数据汇总\BATMAN\BATMAN-TCM_Info_汇总_with_herbid_with_cid.xlsx"
|
| 16 |
+
HERB_DB_FILE = r"D:\2\111数据库\中药表格\herbs.xlsx"
|
| 17 |
+
|
| 18 |
+
# ========== 配置(可调) ==========
|
| 19 |
+
ALIAS_SEPARATORS = r"[、;,/|\n\r]"
|
| 20 |
+
LATIN_NAME_SEP = r"[;|/]"
|
| 21 |
+
LATIN_PART_WORDS = {
|
| 22 |
+
"radix","rhizoma","fructus","folium","cortex","semen","flos","herba","caulis","ramulus",
|
| 23 |
+
"pericarpium","tuber","bulbus","resina","spora","succus","gummi","oleum",
|
| 24 |
+
"rad.","rhiz.","fol.","fruct.","fl.", "cort."
|
| 25 |
+
}
|
| 26 |
+
LATIN_SUFFIXES = ["orum","arum","ius","ius","ius","us","a","um","is","ii","ae","e","os","es","i"]
|
| 27 |
+
# 沿革(词干)最低接受阈值(>=2 为高置信自动接受;==1 标注低置信)
|
| 28 |
+
STEM_ACCEPT_THRESHOLD_HIGH = 2
|
| 29 |
+
STEM_ACCEPT_THRESHOLD_LOW = 1
|
| 30 |
+
|
| 31 |
+
# ========== I/O ==========
|
| 32 |
+
def read_any_table(path):
|
| 33 |
+
p = Path(path)
|
| 34 |
+
if not p.exists():
|
| 35 |
+
raise FileNotFoundError(f"文件不存在:{path}")
|
| 36 |
+
if p.suffix.lower() in (".xls", ".xlsx"):
|
| 37 |
+
return pd.read_excel(path, dtype=str, engine="openpyxl").fillna("")
|
| 38 |
+
else:
|
| 39 |
+
try:
|
| 40 |
+
return pd.read_csv(path, dtype=str, encoding="utf-8").fillna("")
|
| 41 |
+
except Exception:
|
| 42 |
+
return pd.read_csv(path, dtype=str, encoding="gbk").fillna("")
|
| 43 |
+
|
| 44 |
+
def safe_save_csv(df, path):
|
| 45 |
+
try:
|
| 46 |
+
df.to_csv(path, index=False, encoding="utf-8-sig")
|
| 47 |
+
return path
|
| 48 |
+
except PermissionError:
|
| 49 |
+
base = str(Path(path).with_suffix(""))
|
| 50 |
+
new_path = base + "_v2.csv"
|
| 51 |
+
df.to_csv(new_path, index=False, encoding="utf-8-sig")
|
| 52 |
+
return new_path
|
| 53 |
+
|
| 54 |
+
def safe_save_xlsx(df, path):
|
| 55 |
+
try:
|
| 56 |
+
df.to_excel(path, index=False, engine="openpyxl")
|
| 57 |
+
return path
|
| 58 |
+
except PermissionError:
|
| 59 |
+
base = str(Path(path).with_suffix(""))
|
| 60 |
+
new_path = base + "_v2.xlsx"
|
| 61 |
+
df.to_excel(new_path, index=False, engine="openpyxl")
|
| 62 |
+
return new_path
|
| 63 |
+
|
| 64 |
+
# ========== 文本处理函数 ==========
|
| 65 |
+
def keep_toluan80(s):
|
| 66 |
+
if s is None:
|
| 67 |
+
return ""
|
| 68 |
+
s = str(s)
|
| 69 |
+
s = re.sub(r'(?i)(吐温\s*80)', "__TWW80__", s)
|
| 70 |
+
s = re.sub(r'\d+', '', s)
|
| 71 |
+
return s.replace("__TWW80__", "吐温80")
|
| 72 |
+
|
| 73 |
+
def remove_brackets_content(s):
|
| 74 |
+
if s is None:
|
| 75 |
+
return ""
|
| 76 |
+
return re.sub(r'\(.*?\)|\(.*?\)|\[.*?\]|<.*?>', '', str(s)).strip()
|
| 77 |
+
|
| 78 |
+
def split_bracket_inner_and_outer(s):
|
| 79 |
+
if s is None:
|
| 80 |
+
return []
|
| 81 |
+
s = str(s).strip()
|
| 82 |
+
inners = re.findall(r'\((.*?)\)|\((.*?)\)|\[(.*?)\]|<(.*?)>', s)
|
| 83 |
+
values = []
|
| 84 |
+
if inners:
|
| 85 |
+
for t in inners:
|
| 86 |
+
for v in t:
|
| 87 |
+
if v:
|
| 88 |
+
values.append(v.strip())
|
| 89 |
+
outer = remove_brackets_content(s)
|
| 90 |
+
if outer:
|
| 91 |
+
values.insert(0, outer)
|
| 92 |
+
seen = set(); out = []
|
| 93 |
+
for v in values:
|
| 94 |
+
if v and v not in seen:
|
| 95 |
+
seen.add(v); out.append(v)
|
| 96 |
+
return out
|
| 97 |
+
|
| 98 |
+
def strip_english_and_punct(s):
|
| 99 |
+
if s is None:
|
| 100 |
+
return ""
|
| 101 |
+
s = str(s)
|
| 102 |
+
s = re.sub(r'[A-Za-z\u0041-\u007A0-9\(\)\[\]<>/\\@#\$%&\*\-—_+=~`:,.;?"!%]', ' ', s)
|
| 103 |
+
s = re.sub(r'\s+', ' ', s).strip()
|
| 104 |
+
return s
|
| 105 |
+
|
| 106 |
+
def normalize_chinese_candidate(s):
|
| 107 |
+
"""返回若干候选中文 key(去标点空格数字)"""
|
| 108 |
+
if s is None or str(s).strip() == "":
|
| 109 |
+
return []
|
| 110 |
+
s0 = str(s).strip()
|
| 111 |
+
s1 = keep_toluan80(s0)
|
| 112 |
+
outer = remove_brackets_content(s1)
|
| 113 |
+
outer = strip_english_and_punct(outer)
|
| 114 |
+
candidates = []
|
| 115 |
+
if outer:
|
| 116 |
+
candidates.append(re.sub(r'[\s\W_0-9]+','', outer))
|
| 117 |
+
b_parts = split_bracket_inner_and_outer(s1)
|
| 118 |
+
for part in b_parts:
|
| 119 |
+
p = strip_english_and_punct(part)
|
| 120 |
+
p_clean = re.sub(r'[\s\W_0-9]+','', p)
|
| 121 |
+
if p_clean and p_clean not in candidates:
|
| 122 |
+
candidates.append(p_clean)
|
| 123 |
+
base2 = re.sub(r'[\s\W_0-9]+','', strip_english_and_punct(s0))
|
| 124 |
+
if base2 and base2 not in candidates:
|
| 125 |
+
candidates.append(base2)
|
| 126 |
+
return candidates
|
| 127 |
+
|
| 128 |
+
def split_aliases(cell):
|
| 129 |
+
if cell is None or str(cell).strip() == "":
|
| 130 |
+
return []
|
| 131 |
+
parts = re.split(ALIAS_SEPARATORS, str(cell))
|
| 132 |
+
parts = [p.strip() for p in parts if p.strip()]
|
| 133 |
+
return parts
|
| 134 |
+
|
| 135 |
+
def normalize_latin_name(s):
|
| 136 |
+
if s is None or str(s).strip() == "":
|
| 137 |
+
return ""
|
| 138 |
+
s = str(s)
|
| 139 |
+
s = re.sub(r'[^A-Za-z\s]', ' ', s)
|
| 140 |
+
s = re.sub(r'\s+', ' ', s).strip().lower()
|
| 141 |
+
return s
|
| 142 |
+
|
| 143 |
+
def latin_first_two_words(s):
|
| 144 |
+
n = normalize_latin_name(s)
|
| 145 |
+
words = n.split()
|
| 146 |
+
return " ".join(words[:2]) if words else ""
|
| 147 |
+
|
| 148 |
+
def remove_latin_part_words(s):
|
| 149 |
+
n = normalize_latin_name(s)
|
| 150 |
+
words = [w for w in n.split() if w not in LATIN_PART_WORDS]
|
| 151 |
+
return " ".join(words)
|
| 152 |
+
|
| 153 |
+
def latin_word_stem(w):
|
| 154 |
+
if not w:
|
| 155 |
+
return w
|
| 156 |
+
w0 = w.lower()
|
| 157 |
+
for suf in sorted(LATIN_SUFFIXES, key=len, reverse=True):
|
| 158 |
+
if w0.endswith(suf) and len(w0) - len(suf) >= 3:
|
| 159 |
+
return w0[:-len(suf)]
|
| 160 |
+
return w0
|
| 161 |
+
|
| 162 |
+
def latin_two_word_key_variants(s):
|
| 163 |
+
keys = set()
|
| 164 |
+
raw = latin_first_two_words(s)
|
| 165 |
+
if raw: keys.add(raw)
|
| 166 |
+
removed = latin_first_two_words(remove_latin_part_words(s))
|
| 167 |
+
if removed: keys.add(removed)
|
| 168 |
+
for k in list(keys):
|
| 169 |
+
ws = k.split()
|
| 170 |
+
stems = [latin_word_stem(w) for w in ws]
|
| 171 |
+
keys.add(" ".join(stems))
|
| 172 |
+
return keys
|
| 173 |
+
|
| 174 |
+
def latin_names_from_cell(cell):
|
| 175 |
+
if cell is None or str(cell).strip() == "":
|
| 176 |
+
return []
|
| 177 |
+
parts = re.split(LATIN_NAME_SEP, str(cell))
|
| 178 |
+
results = []
|
| 179 |
+
for p in parts:
|
| 180 |
+
p = p.strip()
|
| 181 |
+
if not p: continue
|
| 182 |
+
normalized = normalize_latin_name(p)
|
| 183 |
+
if normalized:
|
| 184 |
+
results.append((p, normalized))
|
| 185 |
+
return results
|
| 186 |
+
|
| 187 |
+
def normalize_pinyin_for_compare(s):
|
| 188 |
+
if s is None or str(s).strip() == "":
|
| 189 |
+
return ""
|
| 190 |
+
s = str(s)
|
| 191 |
+
s = re.sub(r'[\d]', '', s)
|
| 192 |
+
s = re.sub(r'[^\w\s]', '', s)
|
| 193 |
+
s = re.sub(r'\s+', '', s)
|
| 194 |
+
return s.lower()
|
| 195 |
+
|
| 196 |
+
# ========== 交互 ==========
|
| 197 |
+
def ask_column_name(prompt, df):
|
| 198 |
+
print("\n汇总表当前的表头如下(逐行显示,直接复制表头并粘贴):")
|
| 199 |
+
for c in df.columns:
|
| 200 |
+
print(" -", c)
|
| 201 |
+
val = input(f"\n{prompt}(直接粘贴表头文字,留空表示没有该列):").strip()
|
| 202 |
+
return val if val else None
|
| 203 |
+
|
| 204 |
+
# ========== 索引构建(加速匹配) ==========
|
| 205 |
+
def build_indices(herb_df):
|
| 206 |
+
# 自动检测 herb 表列名
|
| 207 |
+
def find(cols):
|
| 208 |
+
for c in cols:
|
| 209 |
+
if c in herb_df.columns:
|
| 210 |
+
return c
|
| 211 |
+
return None
|
| 212 |
+
idc = find(["Herb_id","herb_id","HerbID","herbid","ID","id"])
|
| 213 |
+
ch = find(["中文名","chinese","name","Name"])
|
| 214 |
+
alias = find(["别名","alias","aliases","other_names","别名/异名"])
|
| 215 |
+
latin = find(["Latin_name","latinname","latin_name","latin"])
|
| 216 |
+
pinyin = find(["pinyin_name","pinyin","pinyinname","pinyinnorm"])
|
| 217 |
+
|
| 218 |
+
ch_index = defaultdict(list) # chinese key -> [herb_id...]
|
| 219 |
+
latin_key_index = defaultdict(list) # latin two-word key -> [herb_id...]
|
| 220 |
+
stem_index = defaultdict(set) # stem_token -> set(herb_id)
|
| 221 |
+
pinyin_index = defaultdict(list) # pinyin_key -> [herb_id...]
|
| 222 |
+
herb_meta = {} # herb_id -> original row
|
| 223 |
+
|
| 224 |
+
for idx, r in herb_df.iterrows():
|
| 225 |
+
hid = str(r[idc]) if idc and r[idc] != "" else ""
|
| 226 |
+
if not hid:
|
| 227 |
+
continue
|
| 228 |
+
herb_meta[hid] = r.to_dict()
|
| 229 |
+
# chinese keys
|
| 230 |
+
if ch and r[ch] != "":
|
| 231 |
+
k = re.sub(r'[\s\W_0-9]+','', strip_english_and_punct(r[ch]))
|
| 232 |
+
if k:
|
| 233 |
+
ch_index[k].append(hid)
|
| 234 |
+
if alias and r[alias] != "":
|
| 235 |
+
for a in split_aliases(r[alias]):
|
| 236 |
+
a_clean = re.sub(r'[\s\W_0-9]+','', strip_english_and_punct(a))
|
| 237 |
+
if a_clean:
|
| 238 |
+
ch_index[a_clean].append(hid)
|
| 239 |
+
# pinyin
|
| 240 |
+
if pinyin and r[pinyin] != "":
|
| 241 |
+
pk = normalize_pinyin_for_compare(r[pinyin])
|
| 242 |
+
if pk:
|
| 243 |
+
pinyin_index[pk].append(hid)
|
| 244 |
+
# latin list -> keys + stem tokens
|
| 245 |
+
if latin and r[latin] != "":
|
| 246 |
+
llist = latin_names_from_cell(r[latin])
|
| 247 |
+
for orig, norm in llist:
|
| 248 |
+
for key in latin_two_word_key_variants(norm):
|
| 249 |
+
latin_key_index[key].append(hid)
|
| 250 |
+
# stem tokens
|
| 251 |
+
for w in norm.split():
|
| 252 |
+
st = latin_word_stem(w)
|
| 253 |
+
if st:
|
| 254 |
+
stem_index[st].add(hid)
|
| 255 |
+
|
| 256 |
+
cols = {'idc': idc, 'ch': ch, 'alias': alias, 'latin': latin, 'pinyin': pinyin}
|
| 257 |
+
return {'ch_index': ch_index, 'latin_key_index': latin_key_index,
|
| 258 |
+
'stem_index': stem_index, 'pinyin_index': pinyin_index,
|
| 259 |
+
'herb_meta': herb_meta, 'cols': cols}
|
| 260 |
+
|
| 261 |
+
# ========== 匹配逻辑(使用索引) ==========
|
| 262 |
+
def match_row(row, CHINESE_SUM, LATIN_SUM, PINYIN_SUM, indices):
|
| 263 |
+
ch_index = indices['ch_index']
|
| 264 |
+
latin_key_index = indices['latin_key_index']
|
| 265 |
+
stem_index = indices['stem_index']
|
| 266 |
+
pinyin_index = indices['pinyin_index']
|
| 267 |
+
|
| 268 |
+
# 1) 中文匹配(严格)
|
| 269 |
+
ch_cell = row.get(CHINESE_SUM, "")
|
| 270 |
+
ch_cands = normalize_chinese_candidate(ch_cell)
|
| 271 |
+
for c in ch_cands:
|
| 272 |
+
if c and c in ch_index:
|
| 273 |
+
# 取第一个匹配,若需要可改为按优先级排序
|
| 274 |
+
return ch_index[c][0], f"中文匹配({c})"
|
| 275 |
+
|
| 276 |
+
# 2) 拉丁直接匹配(多变体 key)
|
| 277 |
+
latin_cell = row.get(LATIN_SUM, "")
|
| 278 |
+
latin_cands = latin_names_from_cell(latin_cell)
|
| 279 |
+
summary_latin_keys = set()
|
| 280 |
+
for orig, norm in latin_cands:
|
| 281 |
+
summary_latin_keys.update(latin_two_word_key_variants(norm))
|
| 282 |
+
for key in summary_latin_keys:
|
| 283 |
+
if key in latin_key_index and latin_key_index[key]:
|
| 284 |
+
return latin_key_index[key][0], f"拉丁直接({key})"
|
| 285 |
+
|
| 286 |
+
# 3) 拉丁沿革/词干倒排评分(快速)
|
| 287 |
+
stem_tokens = set()
|
| 288 |
+
for _, norm in latin_cands:
|
| 289 |
+
for w in norm.split():
|
| 290 |
+
st = latin_word_stem(w)
|
| 291 |
+
if st:
|
| 292 |
+
stem_tokens.add(st)
|
| 293 |
+
if stem_tokens:
|
| 294 |
+
counter = Counter()
|
| 295 |
+
for st in stem_tokens:
|
| 296 |
+
if st in stem_index:
|
| 297 |
+
for hid in stem_index[st]:
|
| 298 |
+
counter[hid] += 1
|
| 299 |
+
if counter:
|
| 300 |
+
best_hid, best_score = max(counter.items(), key=lambda x: (x[1], x[0]))
|
| 301 |
+
if best_score >= STEM_ACCEPT_THRESHOLD_HIGH:
|
| 302 |
+
return best_hid, f"沿革高置信(score={best_score})"
|
| 303 |
+
elif best_score >= STEM_ACCEPT_THRESHOLD_LOW:
|
| 304 |
+
return best_hid, f"沿革低置信(score={best_score})"
|
| 305 |
+
|
| 306 |
+
# 4) 拼音严格匹配
|
| 307 |
+
pinyin_cell = row.get(PINYIN_SUM, "")
|
| 308 |
+
pkey = normalize_pinyin_for_compare(pinyin_cell)
|
| 309 |
+
if pkey and pkey in pinyin_index:
|
| 310 |
+
return pinyin_index[pkey][0], "拼音匹配"
|
| 311 |
+
|
| 312 |
+
# 未匹配
|
| 313 |
+
return "", "未匹配"
|
| 314 |
+
|
| 315 |
+
# ========== 主流程 ==========
|
| 316 |
+
def main():
|
| 317 |
+
print("📘 读取文件(默认路径写在脚本顶部)...")
|
| 318 |
+
try:
|
| 319 |
+
summary = read_any_table(SUMMARY_FILE)
|
| 320 |
+
herb_db = read_any_table(HERB_DB_FILE)
|
| 321 |
+
except Exception as e:
|
| 322 |
+
print("读取失败:", e); sys.exit(1)
|
| 323 |
+
|
| 324 |
+
summary.columns = [c.strip() for c in summary.columns]
|
| 325 |
+
herb_db.columns = [c.strip() for c in herb_db.columns]
|
| 326 |
+
|
| 327 |
+
# 交互:只询问汇总表列名(你以前要求这样)
|
| 328 |
+
CHINESE_SUM = ask_column_name("请粘贴【汇总表】中表示中文名的列名", summary)
|
| 329 |
+
LATIN_SUM = ask_column_name("请粘贴【汇总表】中表示拉丁名的列名(若无回车跳过)", summary)
|
| 330 |
+
PINYIN_SUM = ask_column_name("请粘贴【汇总表】中表示拼音名的列名(若无回车跳过)", summary)
|
| 331 |
+
|
| 332 |
+
print("\n开始构建索引(中文/拉丁key/拉丁词干/pinyin)...")
|
| 333 |
+
t0 = time.time()
|
| 334 |
+
indices = build_indices(herb_db)
|
| 335 |
+
print(f"索引构建完成,耗时 {time.time()-t0:.1f}s。")
|
| 336 |
+
|
| 337 |
+
# 逐行匹配(忽略汇总已有herb_id)
|
| 338 |
+
results = []
|
| 339 |
+
reasons = []
|
| 340 |
+
unmatched_idxs = []
|
| 341 |
+
|
| 342 |
+
total = len(summary)
|
| 343 |
+
print(f"\n开始逐行匹配,共 {total} 行(中文 -> 拉丁直接 -> 拉丁沿革/词干评分 -> 拼音)...")
|
| 344 |
+
t1 = time.time()
|
| 345 |
+
for i, row in summary.iterrows():
|
| 346 |
+
hid, reason = match_row(row, CHINESE_SUM, LATIN_SUM, PINYIN_SUM, indices)
|
| 347 |
+
results.append(hid)
|
| 348 |
+
reasons.append(reason)
|
| 349 |
+
if not hid:
|
| 350 |
+
unmatched_idxs.append(i)
|
| 351 |
+
# 进度简单打印(每 5000 行)
|
| 352 |
+
if (i+1) % 5000 == 0:
|
| 353 |
+
print(f" 已处理 {i+1}/{total} 行,未匹配 {len(unmatched_idxs)} 行,耗时 {time.time()-t1:.1f}s")
|
| 354 |
+
|
| 355 |
+
print(f"匹配完成,总耗时 {time.time()-t1:.1f}s。匹配上 {total - len(unmatched_idxs)} / {total} 行。")
|
| 356 |
+
|
| 357 |
+
# 输出文件名规则
|
| 358 |
+
sname = Path(SUMMARY_FILE).stem
|
| 359 |
+
if "_" in sname:
|
| 360 |
+
dbname = sname.split("_", 1)[0]
|
| 361 |
+
else:
|
| 362 |
+
dbname = sname
|
| 363 |
+
out_csv = Path(SUMMARY_FILE).with_name(f"{dbname}_id.csv")
|
| 364 |
+
out_unmatched = Path(SUMMARY_FILE).with_name(f"{dbname}_unmatched.xlsx")
|
| 365 |
+
|
| 366 |
+
# 写回结果
|
| 367 |
+
summary["herb_id"] = results
|
| 368 |
+
summary["匹配说明"] = reasons
|
| 369 |
+
|
| 370 |
+
print("\n正在保存结果...")
|
| 371 |
+
csv_saved = safe_save_csv(summary, str(out_csv))
|
| 372 |
+
print("✅ 已保存更新后的汇总(CSV):", csv_saved)
|
| 373 |
+
if unmatched_idxs:
|
| 374 |
+
unmatched_df = summary.loc[unmatched_idxs].copy()
|
| 375 |
+
xlsx_saved = safe_save_xlsx(unmatched_df, str(out_unmatched))
|
| 376 |
+
print("✅ 已保存未匹配记录(XLSX):", xlsx_saved, f",共 {len(unmatched_idxs)} 条")
|
| 377 |
+
else:
|
| 378 |
+
print("🎉 所有条目均已匹配(0 未匹配)。")
|
| 379 |
+
|
| 380 |
+
if __name__ == "__main__":
|
| 381 |
+
main()
|
recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/metch_id.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import re
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
# ======== 配置 ========
|
| 7 |
+
INPUT_FILE = r"D:\2\111数据库\汇总\TM-MC\TM-MC_Info_汇总_with_herbid.csv" # 需要匹配的化合物文件
|
| 8 |
+
REF_DB_FILE = r"D:\2\111数据库\compounds.xlsx" # 参考数据库文件(含标准ID)
|
| 9 |
+
OUTPUT_FILE = os.path.splitext(INPUT_FILE)[0] + "_with_cid.xlsx"
|
| 10 |
+
REPORT_FILE = os.path.splitext(INPUT_FILE)[0] + "_compound_unmatched.csv"
|
| 11 |
+
|
| 12 |
+
# ======== 工具函数 ========
|
| 13 |
+
def normalize_header(colname: str) -> str:
|
| 14 |
+
"""去除空格、下划线、统一小写(用于表头)"""
|
| 15 |
+
if not isinstance(colname, str):
|
| 16 |
+
return colname
|
| 17 |
+
return re.sub(r'[\s_]+', '', colname.strip().lower())
|
| 18 |
+
|
| 19 |
+
def normalize_str(s: str) -> str:
|
| 20 |
+
"""标准化字符串以便精确比较(保留为空字符串而非 None)"""
|
| 21 |
+
if pd.isna(s):
|
| 22 |
+
return ""
|
| 23 |
+
return str(s).strip()
|
| 24 |
+
|
| 25 |
+
# ======== 智能读取 ========
|
| 26 |
+
def smart_read(file_path):
|
| 27 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 28 |
+
if ext in [".xlsx", ".xls"]:
|
| 29 |
+
try:
|
| 30 |
+
return pd.read_excel(file_path, dtype=str, engine="openpyxl").fillna("")
|
| 31 |
+
except Exception as e:
|
| 32 |
+
print(f"⚠️ Excel 读取失败,尝试以 CSV 模式读取:{e}")
|
| 33 |
+
for enc in ["utf-8-sig", "utf-8", "gbk"]:
|
| 34 |
+
try:
|
| 35 |
+
return pd.read_csv(file_path, dtype=str, encoding=enc).fillna("")
|
| 36 |
+
except Exception:
|
| 37 |
+
continue
|
| 38 |
+
raise ValueError(f"❌ 无法读取文件,请检查格式或编码:{file_path}")
|
| 39 |
+
|
| 40 |
+
# ======== 读取文件 ========
|
| 41 |
+
print("📘 正在读取数据...")
|
| 42 |
+
df = smart_read(INPUT_FILE)
|
| 43 |
+
ref = smart_read(REF_DB_FILE)
|
| 44 |
+
|
| 45 |
+
# ======== 标准化表头 ========
|
| 46 |
+
df.columns = [normalize_header(c) for c in df.columns]
|
| 47 |
+
ref.columns = [normalize_header(c) for c in ref.columns]
|
| 48 |
+
|
| 49 |
+
# ======== 检查可用字段 ========
|
| 50 |
+
priority_fields = ["pubchemid", "inchikey", "inchi", "name"]
|
| 51 |
+
available_fields = [f for f in priority_fields if f in df.columns and f in ref.columns]
|
| 52 |
+
if not available_fields:
|
| 53 |
+
raise ValueError(f"❌ 未找到匹配字段,请检查两表头是否包含任意一个:{priority_fields}")
|
| 54 |
+
|
| 55 |
+
print(f"✅ 可用于匹配的字段(优先顺序):{available_fields}")
|
| 56 |
+
|
| 57 |
+
# ======== 确定参考ID列 ========
|
| 58 |
+
ref_id_col = None
|
| 59 |
+
for c in ref.columns:
|
| 60 |
+
if re.search(r'\b(id|compoundid|cid)\b', c.lower()):
|
| 61 |
+
ref_id_col = c
|
| 62 |
+
break
|
| 63 |
+
if not ref_id_col:
|
| 64 |
+
raise ValueError("❌ 参考表中未找到化合物 ID 列(列名应包含 'id' 或 'cid')")
|
| 65 |
+
|
| 66 |
+
# ======== 初始化匹配列 ========
|
| 67 |
+
df["compound_id"] = ""
|
| 68 |
+
df["match_source"] = ""
|
| 69 |
+
|
| 70 |
+
matched_count = 0
|
| 71 |
+
|
| 72 |
+
# ======== 匹配逻辑(仅匹配非空值) ========
|
| 73 |
+
for field in available_fields:
|
| 74 |
+
print(f"🔍 按 {field} 精确匹配中...")
|
| 75 |
+
|
| 76 |
+
# 参考表去重并且剔除空键(避免把空串当匹配键)
|
| 77 |
+
ref_subset = ref[[field, ref_id_col]].drop_duplicates(subset=[field])
|
| 78 |
+
ref_subset[field] = ref_subset[field].apply(normalize_str)
|
| 79 |
+
ref_subset = ref_subset[ref_subset[field] != ""] # 只保留有值的参考键
|
| 80 |
+
|
| 81 |
+
# 找出还未匹配的行(compound_id 仍为空)
|
| 82 |
+
mask_unmatched = df["compound_id"] == ""
|
| 83 |
+
if mask_unmatched.sum() == 0:
|
| 84 |
+
print(" -> 已全部匹配完成,跳出。")
|
| 85 |
+
break
|
| 86 |
+
|
| 87 |
+
df_unmatched = df.loc[mask_unmatched].copy()
|
| 88 |
+
df_unmatched[field] = df_unmatched[field].apply(normalize_str)
|
| 89 |
+
|
| 90 |
+
# 只对在 df_unmatched 中该字段非空的行进行匹配
|
| 91 |
+
mask_nonempty = df_unmatched[field] != ""
|
| 92 |
+
if mask_nonempty.sum() == 0:
|
| 93 |
+
print(f" -> 本轮没有包含有效 {field} 的未匹配行,跳过此字段。")
|
| 94 |
+
continue
|
| 95 |
+
|
| 96 |
+
to_match = df_unmatched.loc[mask_nonempty].copy()
|
| 97 |
+
to_match["_orig_idx"] = to_match.index # 保存原始索引以便回写
|
| 98 |
+
|
| 99 |
+
# 合并匹配(只匹配非空键)
|
| 100 |
+
merged = pd.merge(
|
| 101 |
+
to_match,
|
| 102 |
+
ref_subset,
|
| 103 |
+
on=field,
|
| 104 |
+
how="left",
|
| 105 |
+
suffixes=("", "_ref")
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# 只取匹配成功的行(参考表有 id)
|
| 109 |
+
matched_rows = merged[merged[ref_id_col].notna()].copy()
|
| 110 |
+
n_match = len(matched_rows)
|
| 111 |
+
matched_count += n_match
|
| 112 |
+
|
| 113 |
+
if n_match > 0:
|
| 114 |
+
# 使用原始索引把 compound_id 和 match_source 精确写回主表
|
| 115 |
+
df.loc[matched_rows["_orig_idx"], "compound_id"] = matched_rows[ref_id_col].values
|
| 116 |
+
df.loc[matched_rows["_orig_idx"], "match_source"] = field
|
| 117 |
+
|
| 118 |
+
print(f" ✅ {field} 匹配成功 {n_match} 条(仅对非空值匹配)")
|
| 119 |
+
|
| 120 |
+
# ======== 输出结果 ========
|
| 121 |
+
# 保存主表(Excel)
|
| 122 |
+
df.to_excel(OUTPUT_FILE, index=False)
|
| 123 |
+
|
| 124 |
+
# 未匹配报告(compound_id 仍为空)
|
| 125 |
+
df_unmatched_final = df[df["compound_id"] == ""]
|
| 126 |
+
df_unmatched_final.to_csv(REPORT_FILE, index=False, encoding="utf-8-sig")
|
| 127 |
+
|
| 128 |
+
print(f"🎯 匹配完成,共匹配到 {matched_count} 条记录。")
|
| 129 |
+
print(f"📘 结果已保存至:{OUTPUT_FILE}")
|
| 130 |
+
print(f"📝 ���匹配报告:{REPORT_FILE}")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/原始数据汇总/诊断.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
diagnose_fast.py
|
| 4 |
+
优化版诊断脚本(用倒排索引加速拉丁词干模糊匹配)
|
| 5 |
+
用法示例:
|
| 6 |
+
python diagnose_fast.py --unmatched "D:\2\111数据库\汇总\BATMAN\BATMAN-TCM_unmatched.xlsx" \
|
| 7 |
+
--herbdb "D:\2\111数据库\中药表格\herbs.xlsx" \
|
| 8 |
+
--out "D:\2\诊断结果_fast.csv" --n 200
|
| 9 |
+
注意:--n 控制终端打印条数,输出 CSV 会包含所有处理过的行(若你想只处理前 K 条,可在脚本中使用 --limit)
|
| 10 |
+
"""
|
| 11 |
+
import argparse, re, sys, time
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import pandas as pd
|
| 14 |
+
from collections import defaultdict, Counter
|
| 15 |
+
|
| 16 |
+
# ---------- 配置/函数(与原脚本保持一致或兼容) ----------
|
| 17 |
+
ALIAS_SEPARATORS = r"[、;,/|\n]"
|
| 18 |
+
LATIN_NAME_SEP = r"[;|/]"
|
| 19 |
+
LATIN_PART_WORDS = {
|
| 20 |
+
"radix","rhizoma","fructus","folium","cortex","semen","flos","herba","caulis","ramulus",
|
| 21 |
+
"pericarpium","tuber","bulbus","resina","spora","succus","gummi","oleum",
|
| 22 |
+
"rad.","rhiz.","fol.","fruct.","fl.", "cort."
|
| 23 |
+
}
|
| 24 |
+
LATIN_SUFFIXES = ["us","a","um","is","ii","ae","orum","arum","e","os","es","i"]
|
| 25 |
+
|
| 26 |
+
def keep_toluan80(s):
|
| 27 |
+
if s is None:
|
| 28 |
+
return ""
|
| 29 |
+
s = str(s)
|
| 30 |
+
s = re.sub(r'(?i)(吐温\s*80)', "__TWW80__", s)
|
| 31 |
+
s = re.sub(r'\d+', '', s)
|
| 32 |
+
return s.replace("__TWW80__", "吐温80")
|
| 33 |
+
|
| 34 |
+
def remove_brackets_content(s):
|
| 35 |
+
if s is None:
|
| 36 |
+
return ""
|
| 37 |
+
return re.sub(r'\(.*?\)|\(.*?\)|\[.*?\]|<.*?>', '', str(s)).strip()
|
| 38 |
+
|
| 39 |
+
def split_bracket_inner_and_outer(s):
|
| 40 |
+
if s is None:
|
| 41 |
+
return []
|
| 42 |
+
s = str(s).strip()
|
| 43 |
+
inners = re.findall(r'\((.*?)\)|\((.*?)\)|\[(.*?)\]|<(.*?)>', s)
|
| 44 |
+
values = []
|
| 45 |
+
if inners:
|
| 46 |
+
for t in inners:
|
| 47 |
+
for v in t:
|
| 48 |
+
if v:
|
| 49 |
+
values.append(v.strip())
|
| 50 |
+
outer = remove_brackets_content(s)
|
| 51 |
+
if outer:
|
| 52 |
+
values.insert(0, outer)
|
| 53 |
+
seen = set(); out = []
|
| 54 |
+
for v in values:
|
| 55 |
+
if v and v not in seen:
|
| 56 |
+
seen.add(v); out.append(v)
|
| 57 |
+
return out
|
| 58 |
+
|
| 59 |
+
def strip_english_and_punct(s):
|
| 60 |
+
if s is None:
|
| 61 |
+
return ""
|
| 62 |
+
s = str(s)
|
| 63 |
+
s = re.sub(r'[A-Za-z\u0041-\u007A0-9\(\)\[\]<>/\\@#\$%&\*\-—_+=~`:,.;?"!%]', ' ', s)
|
| 64 |
+
s = re.sub(r'\s+', ' ', s).strip()
|
| 65 |
+
return s
|
| 66 |
+
|
| 67 |
+
def normalize_chinese_candidate(s):
|
| 68 |
+
if s is None or str(s).strip() == "":
|
| 69 |
+
return []
|
| 70 |
+
s0 = str(s).strip()
|
| 71 |
+
s1 = keep_toluan80(s0)
|
| 72 |
+
outer = remove_brackets_content(s1)
|
| 73 |
+
outer = strip_english_and_punct(outer)
|
| 74 |
+
candidates = []
|
| 75 |
+
if outer:
|
| 76 |
+
candidates.append(re.sub(r'[\s\W_0-9]+','', outer))
|
| 77 |
+
b_parts = split_bracket_inner_and_outer(s1)
|
| 78 |
+
for part in b_parts:
|
| 79 |
+
p = strip_english_and_punct(part)
|
| 80 |
+
p_clean = re.sub(r'[\s\W_0-9]+','', p)
|
| 81 |
+
if p_clean and p_clean not in candidates:
|
| 82 |
+
candidates.append(p_clean)
|
| 83 |
+
base2 = re.sub(r'[\s\W_0-9]+','', strip_english_and_punct(s0))
|
| 84 |
+
if base2 and base2 not in candidates:
|
| 85 |
+
candidates.append(base2)
|
| 86 |
+
return candidates
|
| 87 |
+
|
| 88 |
+
def split_aliases(cell):
|
| 89 |
+
if cell is None or str(cell).strip() == "":
|
| 90 |
+
return []
|
| 91 |
+
parts = re.split(ALIAS_SEPARATORS, str(cell))
|
| 92 |
+
parts = [p.strip() for p in parts if p.strip()]
|
| 93 |
+
return parts
|
| 94 |
+
|
| 95 |
+
def normalize_latin_name(s):
|
| 96 |
+
if s is None or str(s).strip() == "":
|
| 97 |
+
return ""
|
| 98 |
+
s = str(s)
|
| 99 |
+
s = re.sub(r'[^A-Za-z\s]', ' ', s)
|
| 100 |
+
s = re.sub(r'\s+', ' ', s).strip().lower()
|
| 101 |
+
return s
|
| 102 |
+
|
| 103 |
+
def latin_first_two_words(s):
|
| 104 |
+
n = normalize_latin_name(s)
|
| 105 |
+
words = n.split()
|
| 106 |
+
return " ".join(words[:2]) if words else ""
|
| 107 |
+
|
| 108 |
+
def remove_latin_part_words(s):
|
| 109 |
+
n = normalize_latin_name(s)
|
| 110 |
+
words = [w for w in n.split() if w not in LATIN_PART_WORDS]
|
| 111 |
+
return " ".join(words)
|
| 112 |
+
|
| 113 |
+
def latin_word_stem(w):
|
| 114 |
+
if not w: return w
|
| 115 |
+
w0 = w.lower()
|
| 116 |
+
for suf in sorted(LATIN_SUFFIXES, key=len, reverse=True):
|
| 117 |
+
if w0.endswith(suf) and len(w0) - len(suf) >= 3:
|
| 118 |
+
return w0[:-len(suf)]
|
| 119 |
+
return w0
|
| 120 |
+
|
| 121 |
+
def latin_two_word_key_variants(s):
|
| 122 |
+
keys = set()
|
| 123 |
+
raw = latin_first_two_words(s)
|
| 124 |
+
if raw: keys.add(raw)
|
| 125 |
+
removed = latin_first_two_words(remove_latin_part_words(s))
|
| 126 |
+
if removed: keys.add(removed)
|
| 127 |
+
for k in list(keys):
|
| 128 |
+
ws = k.split()
|
| 129 |
+
stems = [latin_word_stem(w) for w in ws]
|
| 130 |
+
keys.add(" ".join(stems))
|
| 131 |
+
return keys
|
| 132 |
+
|
| 133 |
+
def latin_names_from_cell(cell):
|
| 134 |
+
if cell is None or str(cell).strip() == "":
|
| 135 |
+
return []
|
| 136 |
+
parts = re.split(LATIN_NAME_SEP, str(cell))
|
| 137 |
+
results = []
|
| 138 |
+
for p in parts:
|
| 139 |
+
p = p.strip()
|
| 140 |
+
if not p: continue
|
| 141 |
+
normalized = normalize_latin_name(p)
|
| 142 |
+
if normalized:
|
| 143 |
+
results.append((p, normalized))
|
| 144 |
+
return results
|
| 145 |
+
|
| 146 |
+
def normalize_pinyin_for_compare(s):
|
| 147 |
+
if s is None or str(s).strip() == "":
|
| 148 |
+
return ""
|
| 149 |
+
s = str(s)
|
| 150 |
+
s = re.sub(r'[\d]', '', s)
|
| 151 |
+
s = re.sub(r'[^\w\s]', '', s)
|
| 152 |
+
s = re.sub(r'\s+', '', s)
|
| 153 |
+
return s.lower()
|
| 154 |
+
|
| 155 |
+
# ---------- I/O ----------
|
| 156 |
+
def read_any_table(path):
|
| 157 |
+
p = Path(path)
|
| 158 |
+
if not p.exists():
|
| 159 |
+
raise FileNotFoundError(path)
|
| 160 |
+
if p.suffix.lower() in ('.xls', '.xlsx'):
|
| 161 |
+
return pd.read_excel(path, dtype=str, engine='openpyxl').fillna("")
|
| 162 |
+
else:
|
| 163 |
+
try:
|
| 164 |
+
return pd.read_csv(path, dtype=str, encoding='utf-8').fillna("")
|
| 165 |
+
except Exception:
|
| 166 |
+
return pd.read_csv(path, dtype=str, encoding='gbk').fillna("")
|
| 167 |
+
|
| 168 |
+
# ---------- Build indices (fast) ----------
|
| 169 |
+
def build_herb_indices(herb_df):
|
| 170 |
+
# heuristics for column detection
|
| 171 |
+
def find(cols):
|
| 172 |
+
for c in cols:
|
| 173 |
+
if c in herb_df.columns:
|
| 174 |
+
return c
|
| 175 |
+
return None
|
| 176 |
+
idc = find(["Herb_id","herb_id","herbid","ID","id"])
|
| 177 |
+
ch = find(["中文名","chinese","name","Name"])
|
| 178 |
+
alias = find(["别名","alias","aliases","other_names","别名/异名"])
|
| 179 |
+
latin = find(["Latin_name","latinname","latin_name","latin"])
|
| 180 |
+
pinyin = find(["pinyin_name","pinyin","pinyinname","pinyinnorm"])
|
| 181 |
+
|
| 182 |
+
herb_entries = []
|
| 183 |
+
# inverted indices
|
| 184 |
+
ch_index = defaultdict(list) # ch_key -> [herb_id,...]
|
| 185 |
+
latin_key_index = defaultdict(list) # latin two-word key -> [herb_id,...]
|
| 186 |
+
stem_index = defaultdict(set) # stem_token -> set(herb_id)
|
| 187 |
+
pinyin_index = defaultdict(list) # pinyin_norm -> [herb_id,...]
|
| 188 |
+
# also keep mapping herb_id -> meta (for output)
|
| 189 |
+
herb_meta = {}
|
| 190 |
+
|
| 191 |
+
for idx, r in herb_df.iterrows():
|
| 192 |
+
hid = str(r[idc]) if idc and r[idc] != "" else ""
|
| 193 |
+
if not hid:
|
| 194 |
+
continue
|
| 195 |
+
herb_meta[hid] = {'idx': idx, 'orig_row': r.to_dict()}
|
| 196 |
+
# chinese candidates
|
| 197 |
+
if ch and r[ch] != "":
|
| 198 |
+
k = re.sub(r'[\s\W_0-9]+','', strip_english_and_punct(r[ch]))
|
| 199 |
+
if k:
|
| 200 |
+
ch_index[k].append(hid)
|
| 201 |
+
if alias and r[alias] != "":
|
| 202 |
+
for a in split_aliases(r[alias]):
|
| 203 |
+
a_clean = re.sub(r'[\s\W_0-9]+','', strip_english_and_punct(a))
|
| 204 |
+
if a_clean:
|
| 205 |
+
ch_index[a_clean].append(hid)
|
| 206 |
+
# pinyin
|
| 207 |
+
if pinyin and r[pinyin] != "":
|
| 208 |
+
pk = normalize_pinyin_for_compare(r[pinyin])
|
| 209 |
+
if pk:
|
| 210 |
+
pinyin_index[pk].append(hid)
|
| 211 |
+
# latin list
|
| 212 |
+
if latin and r[latin] != "":
|
| 213 |
+
llist = latin_names_from_cell(r[latin])
|
| 214 |
+
for orig, norm in llist:
|
| 215 |
+
# keys variants
|
| 216 |
+
for key in latin_two_word_key_variants(norm):
|
| 217 |
+
latin_key_index[key].append(hid)
|
| 218 |
+
# build stem tokens (split by whitespace after stemming)
|
| 219 |
+
words = norm.split()
|
| 220 |
+
stems = [latin_word_stem(w) for w in words if w]
|
| 221 |
+
for st in stems:
|
| 222 |
+
if st:
|
| 223 |
+
stem_index[st].add(hid)
|
| 224 |
+
|
| 225 |
+
# convert stem_index values to lists for faster later handling (but keep as sets to allow fast membership)
|
| 226 |
+
# return indices and detected column names
|
| 227 |
+
cols = {'idc': idc, 'ch': ch, 'alias': alias, 'latin': latin, 'pinyin': pinyin}
|
| 228 |
+
return {'ch_index': ch_index, 'latin_key_index': latin_key_index, 'stem_index': stem_index, 'pinyin_index': pinyin_index, 'herb_meta': herb_meta, 'cols': cols}
|
| 229 |
+
|
| 230 |
+
# ---------- Diagnostic for a batch of unmatched rows ----------
|
| 231 |
+
def diagnose_unmatched_df(unmatched_df, indices, limit=None, topN=10):
|
| 232 |
+
rows_out = []
|
| 233 |
+
ch_index = indices['ch_index']; latin_key_index = indices['latin_key_index']
|
| 234 |
+
stem_index = indices['stem_index']; pinyin_index = indices['pinyin_index']
|
| 235 |
+
herb_meta = indices['herb_meta']
|
| 236 |
+
cols = indices['cols']
|
| 237 |
+
|
| 238 |
+
# precompute all available herbs set for quick membership checks
|
| 239 |
+
all_herbs = set(herb_meta.keys())
|
| 240 |
+
|
| 241 |
+
# iterate (optionally limit)
|
| 242 |
+
it = unmatched_df.iterrows()
|
| 243 |
+
if limit:
|
| 244 |
+
it = (x for _, x in zip(range(limit), unmatched_df.iterrows()))
|
| 245 |
+
for idx, r in it:
|
| 246 |
+
rec = {'orig_index': idx}
|
| 247 |
+
rec['orig_chinese'] = r.get('name','') or r.get('中文名','') or ""
|
| 248 |
+
rec['orig_latin'] = r.get('latin.name','') or r.get('Latin_name','') or r.get('latin','') or ""
|
| 249 |
+
rec['orig_pinyin'] = r.get('pinyin.name','') or r.get('pinyin','') or ""
|
| 250 |
+
|
| 251 |
+
# chinese candidates and matches
|
| 252 |
+
ch_cands = normalize_chinese_candidate(rec['orig_chinese'])
|
| 253 |
+
rec['ch_candidates'] = "|".join(ch_cands)
|
| 254 |
+
ch_hits = set()
|
| 255 |
+
for c in ch_cands:
|
| 256 |
+
if c in ch_index:
|
| 257 |
+
ch_hits.update(ch_index[c])
|
| 258 |
+
rec['ch_matches'] = "|".join(sorted(ch_hits)) if ch_hits else ""
|
| 259 |
+
|
| 260 |
+
# latin candidates/keys
|
| 261 |
+
lat_cands = latin_names_from_cell(rec['orig_latin'])
|
| 262 |
+
rec['latin_candidates'] = "|".join([o for o,n in lat_cands])
|
| 263 |
+
summary_keys = set()
|
| 264 |
+
for o,n in lat_cands:
|
| 265 |
+
summary_keys.update(latin_two_word_key_variants(n))
|
| 266 |
+
rec['latin_keys'] = "|".join(summary_keys)
|
| 267 |
+
lat_hits = set()
|
| 268 |
+
for k in summary_keys:
|
| 269 |
+
if k in latin_key_index:
|
| 270 |
+
lat_hits.update(latin_key_index[k])
|
| 271 |
+
rec['latin_matches'] = "|".join(sorted(lat_hits)) if lat_hits else ""
|
| 272 |
+
|
| 273 |
+
# latin stem fuzzy: compute stems of summary and then score via inverted stem_index:
|
| 274 |
+
stem_tokens = set()
|
| 275 |
+
for _, n in lat_cands:
|
| 276 |
+
words = n.split()
|
| 277 |
+
for w in words:
|
| 278 |
+
st = latin_word_stem(w)
|
| 279 |
+
if st:
|
| 280 |
+
stem_tokens.add(st)
|
| 281 |
+
rec['latin_summary_stems'] = "|".join(sorted(stem_tokens))
|
| 282 |
+
# count herb occurrence across stems via stem_index (fast)
|
| 283 |
+
counter = Counter()
|
| 284 |
+
for st in stem_tokens:
|
| 285 |
+
if st in stem_index:
|
| 286 |
+
for hid in stem_index[st]:
|
| 287 |
+
counter[hid] += 1
|
| 288 |
+
# take topN highest scores
|
| 289 |
+
if counter:
|
| 290 |
+
top = counter.most_common(topN)
|
| 291 |
+
rec['latin_stem_matches'] = "|".join([f"{hid}(s{sc})" for hid, sc in top])
|
| 292 |
+
else:
|
| 293 |
+
rec['latin_stem_matches'] = ""
|
| 294 |
+
|
| 295 |
+
# pinyin matches
|
| 296 |
+
pkey = normalize_pinyin_for_compare(rec['orig_pinyin'])
|
| 297 |
+
p_hits = set()
|
| 298 |
+
if pkey:
|
| 299 |
+
if pkey in pinyin_index:
|
| 300 |
+
p_hits.update(pinyin_index[pkey])
|
| 301 |
+
rec['pinyin_matches'] = "|".join(sorted(p_hits)) if p_hits else ""
|
| 302 |
+
|
| 303 |
+
rows_out.append(rec)
|
| 304 |
+
return pd.DataFrame(rows_out)
|
| 305 |
+
|
| 306 |
+
# ---------- CLI ----------
|
| 307 |
+
def main():
|
| 308 |
+
p = argparse.ArgumentParser()
|
| 309 |
+
p.add_argument('--unmatched', required=True)
|
| 310 |
+
p.add_argument('--herbdb', required=True)
|
| 311 |
+
p.add_argument('--out', default='diagnose_results_fast.csv')
|
| 312 |
+
p.add_argument('--n', type=int, default=50, help='终端打印前 n 条')
|
| 313 |
+
p.add_argument('--limit', type=int, default=None, help='只处理前 limit 条未匹配记录(便于测试)')
|
| 314 |
+
args = p.parse_args()
|
| 315 |
+
|
| 316 |
+
start = time.time()
|
| 317 |
+
um = read_any_table(args.unmatched)
|
| 318 |
+
herb = read_any_table(args.herbdb)
|
| 319 |
+
print(f"读取完毕:未匹配行数= {len(um)} herb 库行数= {len(herb)} (耗时 {time.time()-start:.1f}s)")
|
| 320 |
+
|
| 321 |
+
# build indices
|
| 322 |
+
t0 = time.time()
|
| 323 |
+
indices = build_herb_indices(herb)
|
| 324 |
+
print(f"构建索引完毕(中文/拉丁key/拉丁词干倒排/pinyin),耗时 {time.time()-t0:.1f}s")
|
| 325 |
+
|
| 326 |
+
# diagnose (with optional limit)
|
| 327 |
+
t1 = time.time()
|
| 328 |
+
diag = diagnose_unmatched_df(um, indices, limit=args.limit, topN=10)
|
| 329 |
+
print(f"诊断生成完毕(处理 {len(diag)} 条),耗时 {time.time()-t1:.1f}s,总耗时 {time.time()-start:.1f}s")
|
| 330 |
+
|
| 331 |
+
# save
|
| 332 |
+
outp = Path(args.out)
|
| 333 |
+
diag.to_csv(outp, index=False, encoding='utf-8-sig')
|
| 334 |
+
print("诊断结果已保存:", outp)
|
| 335 |
+
# print first n rows summary
|
| 336 |
+
n = min(args.n, len(diag))
|
| 337 |
+
if n>0:
|
| 338 |
+
print(f"\n--- 前 {n} 条诊断摘要 ---")
|
| 339 |
+
print(diag.head(n).to_string(index=False))
|
| 340 |
+
|
| 341 |
+
if __name__ == '__main__':
|
| 342 |
+
main()
|
recovery_20261030/zip_preserved_scripts/111药精图模型/归档/1.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import os
|
| 3 |
+
import sqlite3
|
| 4 |
+
import pandas as pd
|
| 5 |
+
|
| 6 |
+
# ===== 配置部分 =====
|
| 7 |
+
DB_FILE = r"D:\2\111数据库\化合物汇总\compounds.db" # 你的数据库文件
|
| 8 |
+
DATA_DIR = r"D:\2\111数据库\数据库-化合物" # 七个数据库文件夹的上级目录
|
| 9 |
+
OUTPUT_FILE = r"D:\2\111数据库\化合物汇总\compound_herb_flat.csv"
|
| 10 |
+
UNMATCHED_FILE = r"D:\2\111数据库\化合物汇总\compound_unmatched.csv"
|
| 11 |
+
|
| 12 |
+
DATABASES = ["BATMAN-TCM_info", "DCABM-TCM_info", "ETCM2_info",
|
| 13 |
+
"HERB2.0_info", "SymMap_info", "TCMIO_info", "TM-MC_info"]
|
| 14 |
+
|
| 15 |
+
# ===== 工具函数 =====
|
| 16 |
+
def preprocess_inchi(inchi: str) -> str:
|
| 17 |
+
"""去掉 InChI 中的立体化学/质子化信息"""
|
| 18 |
+
if not inchi:
|
| 19 |
+
return None
|
| 20 |
+
return inchi.split("/t")[0].split("/m")[0].split("/s")[0]
|
| 21 |
+
|
| 22 |
+
def find_compound(cursor, row):
|
| 23 |
+
"""多字段匹配,按优先级依次尝试"""
|
| 24 |
+
# 1. CID
|
| 25 |
+
if "CID" in row and pd.notna(row["CID"]):
|
| 26 |
+
cursor.execute("SELECT pubchem_cid, inchi FROM compounds WHERE pubchem_cid=?", (str(row["CID"]),))
|
| 27 |
+
res = cursor.fetchone()
|
| 28 |
+
if res: return res
|
| 29 |
+
|
| 30 |
+
# 2. InChIKey
|
| 31 |
+
if "InChIKey" in row and pd.notna(row["InChIKey"]):
|
| 32 |
+
cursor.execute("SELECT pubchem_cid, inchi FROM compounds WHERE inchikey=?", (row["InChIKey"],))
|
| 33 |
+
res = cursor.fetchone()
|
| 34 |
+
if res: return res
|
| 35 |
+
|
| 36 |
+
# 3. InChI
|
| 37 |
+
if "InChI" in row and pd.notna(row["InChI"]):
|
| 38 |
+
inchi = preprocess_inchi(row["InChI"])
|
| 39 |
+
cursor.execute("SELECT pubchem_cid, inchi FROM compounds WHERE inchi=?", (inchi,))
|
| 40 |
+
res = cursor.fetchone()
|
| 41 |
+
if res: return res
|
| 42 |
+
|
| 43 |
+
# 4. SMILES
|
| 44 |
+
if "SMILES" in row and pd.notna(row["SMILES"]):
|
| 45 |
+
cursor.execute("SELECT pubchem_cid, inchi FROM compounds WHERE smiles=?", (row["SMILES"],))
|
| 46 |
+
res = cursor.fetchone()
|
| 47 |
+
if res: return res
|
| 48 |
+
|
| 49 |
+
# 5. 名称
|
| 50 |
+
if "Name" in row and pd.notna(row["Name"]):
|
| 51 |
+
cursor.execute("SELECT pubchem_cid, inchi FROM compounds WHERE name LIKE ?", (row["Name"],))
|
| 52 |
+
res = cursor.fetchone()
|
| 53 |
+
if res: return res
|
| 54 |
+
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
# ===== 主程序 =====
|
| 58 |
+
def main():
|
| 59 |
+
conn = sqlite3.connect(DB_FILE)
|
| 60 |
+
cursor = conn.cursor()
|
| 61 |
+
|
| 62 |
+
# 已处理的记录 (Compound_CID, Herb_Name)
|
| 63 |
+
processed = set()
|
| 64 |
+
if os.path.exists(OUTPUT_FILE):
|
| 65 |
+
try:
|
| 66 |
+
old_df = pd.read_csv(OUTPUT_FILE)
|
| 67 |
+
for _, r in old_df.iterrows():
|
| 68 |
+
key = (str(r["Compound_CID"]), str(r["Herb_Name"]))
|
| 69 |
+
processed.add(key)
|
| 70 |
+
print(f"🔄 已加载历史结果,共 {len(processed)} 条,将跳过这些记录")
|
| 71 |
+
except Exception:
|
| 72 |
+
print("⚠️ 读取已有 CSV 失败,可能是空文件,将重新生成")
|
| 73 |
+
|
| 74 |
+
header_needed = not os.path.exists(OUTPUT_FILE)
|
| 75 |
+
unmatched_header_needed = not os.path.exists(UNMATCHED_FILE)
|
| 76 |
+
|
| 77 |
+
for db_folder in DATABASES:
|
| 78 |
+
db_path = os.path.join(DATA_DIR, db_folder)
|
| 79 |
+
if not os.path.exists(db_path):
|
| 80 |
+
print(f"⚠️ 文件夹缺失: {db_path}")
|
| 81 |
+
continue
|
| 82 |
+
|
| 83 |
+
for file in os.listdir(db_path):
|
| 84 |
+
if not file.endswith(".xlsx"):
|
| 85 |
+
continue
|
| 86 |
+
|
| 87 |
+
herb_name = os.path.splitext(file)[0] # 文件名 = 中药名
|
| 88 |
+
file_path = os.path.join(db_path, file)
|
| 89 |
+
|
| 90 |
+
try:
|
| 91 |
+
df = pd.read_excel(file_path)
|
| 92 |
+
except Exception as e:
|
| 93 |
+
print(f"❌ 读取失败: {file_path}, 错误: {e}")
|
| 94 |
+
continue
|
| 95 |
+
|
| 96 |
+
new_records = []
|
| 97 |
+
unmatched_records = []
|
| 98 |
+
|
| 99 |
+
for _, row in df.iterrows():
|
| 100 |
+
compound = find_compound(cursor, row)
|
| 101 |
+
if compound:
|
| 102 |
+
cid, inchi = compound
|
| 103 |
+
else:
|
| 104 |
+
cid, inchi = None, None
|
| 105 |
+
|
| 106 |
+
key = (str(cid), str(herb_name))
|
| 107 |
+
if cid and key in processed:
|
| 108 |
+
continue # 已处理过
|
| 109 |
+
|
| 110 |
+
if cid: # 匹配成功
|
| 111 |
+
record = {
|
| 112 |
+
"Compound_CID": cid,
|
| 113 |
+
"Compound_InChI": inchi,
|
| 114 |
+
"Herb_Name": herb_name,
|
| 115 |
+
"BATMAN-TCM": "✓" if db_folder.startswith("BATMAN-TCM") else "",
|
| 116 |
+
"DCABM-TCM": "✓" if db_folder.startswith("DCABM-TCM") else "",
|
| 117 |
+
"ETCM2": "✓" if db_folder.startswith("ETCM2") else "",
|
| 118 |
+
"HERB2.0": "✓" if db_folder.startswith("HERB2.0") else "",
|
| 119 |
+
"SymMap": "✓" if db_folder.startswith("SymMap") else "",
|
| 120 |
+
"TCMIO": "✓" if db_folder.startswith("TCMIO") else "",
|
| 121 |
+
"TM-MC": "✓" if db_folder.startswith("TM-MC") else ""
|
| 122 |
+
}
|
| 123 |
+
new_records.append(record)
|
| 124 |
+
processed.add(key)
|
| 125 |
+
else: # 匹配失败 → 记���到 unmatched
|
| 126 |
+
unmatched_records.append({
|
| 127 |
+
"Herb_Name": herb_name,
|
| 128 |
+
"Database": db_folder,
|
| 129 |
+
**row.to_dict()
|
| 130 |
+
})
|
| 131 |
+
|
| 132 |
+
if new_records:
|
| 133 |
+
pd.DataFrame(new_records).to_csv(
|
| 134 |
+
OUTPUT_FILE,
|
| 135 |
+
mode="a",
|
| 136 |
+
header=header_needed,
|
| 137 |
+
index=False,
|
| 138 |
+
encoding="utf-8-sig"
|
| 139 |
+
)
|
| 140 |
+
header_needed = False
|
| 141 |
+
|
| 142 |
+
if unmatched_records:
|
| 143 |
+
pd.DataFrame(unmatched_records).to_csv(
|
| 144 |
+
UNMATCHED_FILE,
|
| 145 |
+
mode="a",
|
| 146 |
+
header=unmatched_header_needed,
|
| 147 |
+
index=False,
|
| 148 |
+
encoding="utf-8-sig"
|
| 149 |
+
)
|
| 150 |
+
unmatched_header_needed = False
|
| 151 |
+
|
| 152 |
+
print(f"✅ 处理完成: {file_path}, 匹配 {len(df)} 条, 成功 {len(new_records)} 条, 未匹配 {len(unmatched_records)} 条")
|
| 153 |
+
|
| 154 |
+
conn.close()
|
| 155 |
+
print(f"🎉 全部处理完成,结果已追加到 {OUTPUT_FILE},未匹配的保存到 {UNMATCHED_FILE}")
|
| 156 |
+
|
| 157 |
+
if __name__ == "__main__":
|
| 158 |
+
main()
|
recovery_20261030/zip_preserved_scripts/111药精图模型/归档/dedup.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
方案 A: 在 compounds 表中直接去重
|
| 4 |
+
优先级:InChI > InChIKey > PubChem CID
|
| 5 |
+
保留 id 最小的那条,其余的补全非空字段后删除
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import sqlite3
|
| 9 |
+
|
| 10 |
+
DB_FILE = r"D:\2\111数据库\化合物汇总\compounds.db"
|
| 11 |
+
|
| 12 |
+
FIELDS = [
|
| 13 |
+
"name",
|
| 14 |
+
"molecular_formula",
|
| 15 |
+
"smiles",
|
| 16 |
+
"average_weight",
|
| 17 |
+
"inchi",
|
| 18 |
+
"inchikey",
|
| 19 |
+
"cas",
|
| 20 |
+
"pubchem_cid"
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
def coalesce_update(cursor, keep_id, drop_id):
|
| 24 |
+
"""把 drop_id 的非空字段补到 keep_id"""
|
| 25 |
+
cursor.execute(f"SELECT {','.join(FIELDS)} FROM compounds WHERE id=?", (keep_id,))
|
| 26 |
+
keep_row = cursor.fetchone()
|
| 27 |
+
cursor.execute(f"SELECT {','.join(FIELDS)} FROM compounds WHERE id=?", (drop_id,))
|
| 28 |
+
drop_row = cursor.fetchone()
|
| 29 |
+
|
| 30 |
+
updates = {}
|
| 31 |
+
for i, col in enumerate(FIELDS):
|
| 32 |
+
keep_val = keep_row[i]
|
| 33 |
+
drop_val = drop_row[i]
|
| 34 |
+
if (keep_val is None or str(keep_val).strip() == "") and drop_val not in (None, "", "nan"):
|
| 35 |
+
updates[col] = drop_val
|
| 36 |
+
|
| 37 |
+
if updates:
|
| 38 |
+
set_clause = ", ".join([f"{col}=?" for col in updates.keys()])
|
| 39 |
+
sql = f"UPDATE compounds SET {set_clause} WHERE id=?"
|
| 40 |
+
cursor.execute(sql, tuple(updates.values()) + (keep_id,))
|
| 41 |
+
|
| 42 |
+
def process_groups(cursor, groups, key_type):
|
| 43 |
+
merged = deleted = 0
|
| 44 |
+
for key_val, ids_str, count in groups:
|
| 45 |
+
ids = [int(x) for x in ids_str.split(",")]
|
| 46 |
+
ids.sort()
|
| 47 |
+
keep_id, drop_ids = ids[0], ids[1:]
|
| 48 |
+
for drop_id in drop_ids:
|
| 49 |
+
coalesce_update(cursor, keep_id, drop_id)
|
| 50 |
+
cursor.execute("DELETE FROM compounds WHERE id=?", (drop_id,))
|
| 51 |
+
merged += 1
|
| 52 |
+
deleted += 1
|
| 53 |
+
print(f"🔑 {key_type} 去重:合并 {merged} 条,删除 {deleted} 条")
|
| 54 |
+
return merged, deleted
|
| 55 |
+
|
| 56 |
+
def deduplicate(conn):
|
| 57 |
+
cursor = conn.cursor()
|
| 58 |
+
|
| 59 |
+
# InChI 分组
|
| 60 |
+
cursor.execute("""
|
| 61 |
+
SELECT inchi, GROUP_CONCAT(id), COUNT(*)
|
| 62 |
+
FROM compounds
|
| 63 |
+
WHERE inchi IS NOT NULL AND TRIM(inchi) != ''
|
| 64 |
+
GROUP BY inchi HAVING COUNT(*) > 1
|
| 65 |
+
""")
|
| 66 |
+
inchi_groups = cursor.fetchall()
|
| 67 |
+
|
| 68 |
+
# InChIKey 分组(InChI 缺失时)
|
| 69 |
+
cursor.execute("""
|
| 70 |
+
SELECT inchikey, GROUP_CONCAT(id), COUNT(*)
|
| 71 |
+
FROM compounds
|
| 72 |
+
WHERE (inchi IS NULL OR TRIM(inchi) = '')
|
| 73 |
+
AND inchikey IS NOT NULL AND TRIM(inchikey) != ''
|
| 74 |
+
GROUP BY inchikey HAVING COUNT(*) > 1
|
| 75 |
+
""")
|
| 76 |
+
inchikey_groups = cursor.fetchall()
|
| 77 |
+
|
| 78 |
+
# CID 分组(InChI + InChIKey 都缺失时)
|
| 79 |
+
cursor.execute("""
|
| 80 |
+
SELECT pubchem_cid, GROUP_CONCAT(id), COUNT(*)
|
| 81 |
+
FROM compounds
|
| 82 |
+
WHERE (inchi IS NULL OR TRIM(inchi) = '')
|
| 83 |
+
AND (inchikey IS NULL OR TRIM(inchikey) = '')
|
| 84 |
+
AND pubchem_cid IS NOT NULL
|
| 85 |
+
GROUP BY pubchem_cid HAVING COUNT(*) > 1
|
| 86 |
+
""")
|
| 87 |
+
cid_groups = cursor.fetchall()
|
| 88 |
+
|
| 89 |
+
print(f"检测到 {len(inchi_groups)} 组 InChI 重复")
|
| 90 |
+
print(f"检测到 {len(inchikey_groups)} 组 InChIKey 重复")
|
| 91 |
+
print(f"检测到 {len(cid_groups)} 组 CID 重复")
|
| 92 |
+
|
| 93 |
+
total_merged = total_deleted = 0
|
| 94 |
+
for groups, key in [(inchi_groups, "InChI"), (inchikey_groups, "InChIKey"), (cid_groups, "CID")]:
|
| 95 |
+
merged, deleted = process_groups(cursor, groups, key)
|
| 96 |
+
total_merged += merged
|
| 97 |
+
total_deleted += deleted
|
| 98 |
+
|
| 99 |
+
conn.commit()
|
| 100 |
+
print(f"🎉 总计:合并 {total_merged} 条,删除 {total_deleted} 条")
|
| 101 |
+
|
| 102 |
+
if __name__ == "__main__":
|
| 103 |
+
print("⚠️ 请确保已备份 DB 文件!")
|
| 104 |
+
conn = sqlite3.connect(DB_FILE)
|
| 105 |
+
deduplicate(conn)
|
| 106 |
+
conn.close()
|
recovery_20261030/zip_preserved_scripts/111药精图模型/归档/herb.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import os
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import sqlite3
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
OUTPUT_DB = r"D:\2\111数据库\herbs.db"
|
| 8 |
+
DUP_REPORT = r"D:\2\111数据库\herbs_duplicates.xlsx"
|
| 9 |
+
|
| 10 |
+
# ========= 拼音归一化 =========
|
| 11 |
+
def normalize_pinyin(name):
|
| 12 |
+
if pd.isna(name):
|
| 13 |
+
return ""
|
| 14 |
+
return re.sub(r"\s+", "", str(name)).lower()
|
| 15 |
+
|
| 16 |
+
# ========= 数据读取函数 =========
|
| 17 |
+
def load_batman(file):
|
| 18 |
+
# BATMAN-TCM: Pinyin.Name, Chinese.Name, English.Name, Latin.Name
|
| 19 |
+
df = pd.read_excel(file)
|
| 20 |
+
df = df.rename(columns={
|
| 21 |
+
"Chinese.Name": "chinese_name",
|
| 22 |
+
"Latin.Name": "latin_name",
|
| 23 |
+
"Pinyin.Name": "pinyin_name"
|
| 24 |
+
})
|
| 25 |
+
df["pinyin_norm"] = df["pinyin_name"].apply(normalize_pinyin)
|
| 26 |
+
return df[["chinese_name", "latin_name", "pinyin_name", "pinyin_norm"]]
|
| 27 |
+
|
| 28 |
+
def load_dcabm(file):
|
| 29 |
+
# DCABM-TCM: Pinyin.name, English.name, Latin.name, Chinese.name
|
| 30 |
+
df = pd.read_excel(file)
|
| 31 |
+
df = df.rename(columns={
|
| 32 |
+
"Chinese.name": "chinese_name",
|
| 33 |
+
"Latin.name": "latin_name",
|
| 34 |
+
"Pinyin.name": "pinyin_name"
|
| 35 |
+
})
|
| 36 |
+
df["pinyin_norm"] = df["pinyin_name"].apply(normalize_pinyin)
|
| 37 |
+
return df[["chinese_name", "latin_name", "pinyin_name", "pinyin_norm"]]
|
| 38 |
+
|
| 39 |
+
def load_etcm2(file):
|
| 40 |
+
# ETCM2: 拉丁名, 拼音名(英文式写法)
|
| 41 |
+
df = pd.read_excel(file)
|
| 42 |
+
df = df.rename(columns={
|
| 43 |
+
"拉丁名": "latin_name",
|
| 44 |
+
"拼音名": "pinyin_name"
|
| 45 |
+
})
|
| 46 |
+
df["pinyin_norm"] = df["pinyin_name"].apply(normalize_pinyin)
|
| 47 |
+
return df[["latin_name", "pinyin_name", "pinyin_norm"]]
|
| 48 |
+
|
| 49 |
+
def load_herb(file):
|
| 50 |
+
# HERB2.0: Herb_id, Herb_cn_name
|
| 51 |
+
df = pd.read_excel(file)
|
| 52 |
+
df = df.rename(columns={
|
| 53 |
+
"Herb_cn_name": "chinese_name"
|
| 54 |
+
})
|
| 55 |
+
df["pinyin_name"] = ""
|
| 56 |
+
df["latin_name"] = ""
|
| 57 |
+
df["pinyin_norm"] = ""
|
| 58 |
+
return df[["chinese_name", "latin_name", "pinyin_name", "pinyin_norm"]]
|
| 59 |
+
|
| 60 |
+
def load_symmap(file):
|
| 61 |
+
# SymMap: Chinese_name, Pinyin_name, Latin_name, English_name
|
| 62 |
+
df = pd.read_excel(file)
|
| 63 |
+
df = df.rename(columns={
|
| 64 |
+
"Chinese_name": "chinese_name",
|
| 65 |
+
"Latin_name": "latin_name",
|
| 66 |
+
"Pinyin_name": "pinyin_name"
|
| 67 |
+
})
|
| 68 |
+
df["pinyin_norm"] = df["pinyin_name"].apply(normalize_pinyin)
|
| 69 |
+
return df[["chinese_name", "latin_name", "pinyin_name", "pinyin_norm"]]
|
| 70 |
+
|
| 71 |
+
def load_tcmio(file):
|
| 72 |
+
# TCMIO: chinese_name, pinyin_name, english_name, ...
|
| 73 |
+
df = pd.read_excel(file)
|
| 74 |
+
df = df.rename(columns={
|
| 75 |
+
"chinese_name": "chinese_name",
|
| 76 |
+
"pinyin_name": "pinyin_name"
|
| 77 |
+
})
|
| 78 |
+
df["latin_name"] = ""
|
| 79 |
+
df["pinyin_norm"] = df["pinyin_name"].apply(normalize_pinyin)
|
| 80 |
+
return df[["chinese_name", "latin_name", "pinyin_name", "pinyin_norm"]]
|
| 81 |
+
|
| 82 |
+
def load_tm_mc(file):
|
| 83 |
+
# TM-MC: LATIN, CHINESE, PINYIN
|
| 84 |
+
df = pd.read_excel(file)
|
| 85 |
+
df = df.rename(columns={
|
| 86 |
+
"CHINESE": "chinese_name",
|
| 87 |
+
"LATIN": "latin_name",
|
| 88 |
+
"PINYIN": "pinyin_name"
|
| 89 |
+
})
|
| 90 |
+
df["pinyin_norm"] = df["pinyin_name"].apply(normalize_pinyin)
|
| 91 |
+
return df[["chinese_name", "latin_name", "pinyin_name", "pinyin_norm"]]
|
| 92 |
+
|
| 93 |
+
# ========= 合并逻辑 =========
|
| 94 |
+
def merge_all(dfs, old_df=None):
|
| 95 |
+
merged = pd.concat(dfs, ignore_index=True)
|
| 96 |
+
|
| 97 |
+
# 优先级:中文 > 拉丁 > 拼音
|
| 98 |
+
merged["key"] = merged["chinese_name"].fillna("")
|
| 99 |
+
merged.loc[merged["key"] == "", "key"] = merged["latin_name"].fillna("")
|
| 100 |
+
merged.loc[merged["key"] == "", "key"] = merged["pinyin_norm"].fillna("")
|
| 101 |
+
|
| 102 |
+
if old_df is not None and not old_df.empty:
|
| 103 |
+
merged = pd.concat([old_df, merged], ignore_index=True)
|
| 104 |
+
|
| 105 |
+
# 分组合并
|
| 106 |
+
final = merged.groupby("key").agg(
|
| 107 |
+
lambda x: ";".join(set([str(i) for i in x if pd.notna(i) and i != ""]))
|
| 108 |
+
).reset_index()
|
| 109 |
+
|
| 110 |
+
return final
|
| 111 |
+
|
| 112 |
+
# ========= 疑似重复检查 =========
|
| 113 |
+
def check_duplicates(df):
|
| 114 |
+
suspects = []
|
| 115 |
+
for _, row in df.iterrows():
|
| 116 |
+
issues = []
|
| 117 |
+
if ";" in str(row["chinese_name"]):
|
| 118 |
+
issues.append("多个中文名")
|
| 119 |
+
if ";" in str(row["latin_name"]):
|
| 120 |
+
issues.append("多个拉丁名")
|
| 121 |
+
if ";" in str(row["pinyin_name"]):
|
| 122 |
+
issues.append("多个拼音名")
|
| 123 |
+
if issues:
|
| 124 |
+
row_dict = row.to_dict()
|
| 125 |
+
row_dict["可能问题类型"] = ";".join(issues)
|
| 126 |
+
suspects.append(row_dict)
|
| 127 |
+
|
| 128 |
+
if suspects:
|
| 129 |
+
dup_df = pd.DataFrame(suspects)
|
| 130 |
+
dup_df.to_excel(DUP_REPORT, index=False)
|
| 131 |
+
print(f"⚠️ 已发现 {len(dup_df)} 条疑似重复,已写入 {DUP_REPORT}")
|
| 132 |
+
else:
|
| 133 |
+
print("✅ 未发现疑似重复")
|
| 134 |
+
|
| 135 |
+
# ========= 主程序 =========
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
dfs = []
|
| 138 |
+
dfs.append(load_batman(r"D:\2\111数据库\中药表格\BATMAN-TCM.xlsx"))
|
| 139 |
+
dfs.append(load_dcabm(r"D:\2\111数据库\中药表格\DCABM-TCM.xlsx"))
|
| 140 |
+
dfs.append(load_etcm2(r"D:\2\111数据库\中药表格\ETCM2.xlsx"))
|
| 141 |
+
dfs.append(load_herb(r"D:\2\111数据库\中药表格\HERB2.0.xlsx"))
|
| 142 |
+
dfs.append(load_symmap(r"D:\2\111数据库\中药表格\SymMap.xlsx"))
|
| 143 |
+
dfs.append(load_tcmio(r"D:\2\111数据库\中药表格\TCMIO.xlsx"))
|
| 144 |
+
dfs.append(load_tm_mc(r"D:\2\111数据库\中药表格\TM-MC.xlsx"))
|
| 145 |
+
|
| 146 |
+
# 断点续跑
|
| 147 |
+
if os.path.exists(OUTPUT_DB):
|
| 148 |
+
conn = sqlite3.connect(OUTPUT_DB)
|
| 149 |
+
try:
|
| 150 |
+
old_df = pd.read_sql("SELECT * FROM herbs", conn)
|
| 151 |
+
except:
|
| 152 |
+
old_df = pd.DataFrame()
|
| 153 |
+
conn.close()
|
| 154 |
+
else:
|
| 155 |
+
old_df = pd.DataFrame()
|
| 156 |
+
|
| 157 |
+
# 合并
|
| 158 |
+
final = merge_all(dfs, old_df)
|
| 159 |
+
|
| 160 |
+
# 保存结果
|
| 161 |
+
conn = sqlite3.connect(OUTPUT_DB)
|
| 162 |
+
final.to_sql("herbs", conn, if_exists="replace", index=False)
|
| 163 |
+
conn.close()
|
| 164 |
+
|
| 165 |
+
# 检查疑似重复
|
| 166 |
+
check_duplicates(final)
|
| 167 |
+
|
| 168 |
+
print(f"✅ 汇总完成,结果已保存到 {OUTPUT_DB} (表: herbs)")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/归档/import.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import os
|
| 3 |
+
import sqlite3
|
| 4 |
+
import pandas as pd
|
| 5 |
+
|
| 6 |
+
# ===== 配置部分 =====
|
| 7 |
+
DATA_FOLDER = r"D:\2\111数据库\数据库-化合物\TM-MC_Info" # 存放所有xlsx文件的文件夹路径
|
| 8 |
+
DB_FILE = r"D:\2\111数据库\化合物汇总\compounds.db" # 数据库文件名
|
| 9 |
+
|
| 10 |
+
# ===== 第一步:连接数据库 =====
|
| 11 |
+
conn = sqlite3.connect(DB_FILE)
|
| 12 |
+
cursor = conn.cursor()
|
| 13 |
+
|
| 14 |
+
# ===== 第二步:建立表 =====
|
| 15 |
+
cursor.execute("""
|
| 16 |
+
CREATE TABLE IF NOT EXISTS compounds (
|
| 17 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 18 |
+
pubchem_cid INTEGER,
|
| 19 |
+
name TEXT,
|
| 20 |
+
molecular_formula TEXT,
|
| 21 |
+
smiles TEXT,
|
| 22 |
+
average_weight REAL,
|
| 23 |
+
inchi TEXT,
|
| 24 |
+
inchikey TEXT,
|
| 25 |
+
cas TEXT
|
| 26 |
+
);
|
| 27 |
+
""")
|
| 28 |
+
conn.commit()
|
| 29 |
+
|
| 30 |
+
# ===== 第三步:遍历xlsx文件并导入 =====
|
| 31 |
+
for file in os.listdir(DATA_FOLDER):
|
| 32 |
+
if file.endswith(".xlsx"):
|
| 33 |
+
filepath = os.path.join(DATA_FOLDER, file)
|
| 34 |
+
print(f"正在导入: {filepath}")
|
| 35 |
+
|
| 36 |
+
# 读取Excel
|
| 37 |
+
df = pd.read_excel(filepath)
|
| 38 |
+
|
| 39 |
+
# 保证列名和数据库字段一致(必要时可以rename)
|
| 40 |
+
df = df.rename(columns={
|
| 41 |
+
"PubChem CID": "pubchem_cid",
|
| 42 |
+
"Name": "name",
|
| 43 |
+
"Molecular Formula": "molecular_formula",
|
| 44 |
+
"SMILES": "smiles",
|
| 45 |
+
"Average Weight": "average_weight",
|
| 46 |
+
"InChI": "inchi",
|
| 47 |
+
"InChKey": "inchikey",
|
| 48 |
+
"CAS": "cas"
|
| 49 |
+
})
|
| 50 |
+
# 只保留需要的列
|
| 51 |
+
expected_cols = ["pubchem_cid", "name", "molecular_formula", "smiles",
|
| 52 |
+
"average_weight", "inchi", "inchikey", "cas"]
|
| 53 |
+
df = df[[col for col in expected_cols if col in df.columns]]
|
| 54 |
+
|
| 55 |
+
# 把数据写入数据库
|
| 56 |
+
df.to_sql("compounds", conn, if_exists="append", index=False)
|
| 57 |
+
|
| 58 |
+
# ===== 结束 =====
|
| 59 |
+
conn.close()
|
| 60 |
+
print("✅ 全部数据导入完成!")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/归档/query_db.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import sqlite3
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
DB_FILE = r"D:\2\111数据库\化合物汇总\compounds.db" # 你的数据库路径
|
| 6 |
+
|
| 7 |
+
# 连接数据库
|
| 8 |
+
conn = sqlite3.connect(DB_FILE)
|
| 9 |
+
|
| 10 |
+
# 1. 查看总行数
|
| 11 |
+
count = pd.read_sql("SELECT COUNT(*) AS total FROM compounds", conn)
|
| 12 |
+
print("数据库里共有多少条数据:")
|
| 13 |
+
print(count, "\n")
|
| 14 |
+
|
| 15 |
+
# 2. 查看前10行数据
|
| 16 |
+
preview = pd.read_sql("SELECT * FROM compounds LIMIT 10", conn)
|
| 17 |
+
print("前10行数据预览:")
|
| 18 |
+
print(preview, "\n")
|
| 19 |
+
print(preview.to_string())
|
| 20 |
+
|
| 21 |
+
# 3. 按条件查询(比如 PubChem CID=5280805)
|
| 22 |
+
example = pd.read_sql("SELECT * FROM compounds WHERE pubchem_cid = 5280805", conn)
|
| 23 |
+
print("查询 PubChem CID = 5280805 的记录:")
|
| 24 |
+
print(example, "\n")
|
| 25 |
+
|
| 26 |
+
conn.close()
|
recovery_20261030/zip_preserved_scripts/111药精图模型/归档/update.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import sqlite3
|
| 3 |
+
import pubchempy as pcp
|
| 4 |
+
|
| 5 |
+
DB_FILE = r"D:\2\111数据库\化合物汇总\compounds.db" # 修改为你的数据库路径
|
| 6 |
+
|
| 7 |
+
# ===== 连接数据库 =====
|
| 8 |
+
conn = sqlite3.connect(DB_FILE)
|
| 9 |
+
cursor = conn.cursor()
|
| 10 |
+
|
| 11 |
+
# ===== 找到有缺失数据的记录 =====
|
| 12 |
+
cursor.execute("""
|
| 13 |
+
SELECT id, pubchem_cid FROM compounds
|
| 14 |
+
WHERE name IS NULL
|
| 15 |
+
OR molecular_formula IS NULL
|
| 16 |
+
OR smiles IS NULL
|
| 17 |
+
OR average_weight IS NULL
|
| 18 |
+
OR inchi IS NULL
|
| 19 |
+
OR inchikey IS NULL
|
| 20 |
+
OR cas IS NULL
|
| 21 |
+
""")
|
| 22 |
+
rows = cursor.fetchall()
|
| 23 |
+
|
| 24 |
+
print(f"需要补全的记录数: {len(rows)}")
|
| 25 |
+
|
| 26 |
+
for rid, cid in rows:
|
| 27 |
+
if cid is None:
|
| 28 |
+
print(f"⚠️ id={rid} 没有 PubChem CID,跳过")
|
| 29 |
+
continue
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
compound = pcp.Compound.from_cid(cid)
|
| 33 |
+
|
| 34 |
+
# 从PubChem获取信息
|
| 35 |
+
name = compound.iupac_name or (compound.synonyms[0] if compound.synonyms else None)
|
| 36 |
+
formula = compound.molecular_formula
|
| 37 |
+
smiles = compound.isomeric_smiles
|
| 38 |
+
weight = compound.molecular_weight
|
| 39 |
+
inchi = compound.inchi
|
| 40 |
+
inchikey = compound.inchikey
|
| 41 |
+
|
| 42 |
+
# 尝试在synonyms中找CAS号
|
| 43 |
+
cas = None
|
| 44 |
+
if compound.synonyms:
|
| 45 |
+
cas = next((s for s in compound.synonyms if s.replace("-", "").isdigit()), None)
|
| 46 |
+
|
| 47 |
+
# 更新数据库(仅补全缺失的,不会覆盖已有数据)
|
| 48 |
+
cursor.execute("""
|
| 49 |
+
UPDATE compounds
|
| 50 |
+
SET
|
| 51 |
+
name = COALESCE(name, ?),
|
| 52 |
+
molecular_formula = COALESCE(molecular_formula, ?),
|
| 53 |
+
smiles = COALESCE(smiles, ?),
|
| 54 |
+
average_weight = COALESCE(average_weight, ?),
|
| 55 |
+
inchi = COALESCE(inchi, ?),
|
| 56 |
+
inchikey = COALESCE(inchikey, ?),
|
| 57 |
+
cas = COALESCE(cas, ?)
|
| 58 |
+
WHERE id = ?
|
| 59 |
+
""", (name, formula, smiles, weight, inchi, inchikey, cas, rid))
|
| 60 |
+
|
| 61 |
+
conn.commit()
|
| 62 |
+
print(f"✅ 已补全 PubChem CID {cid}")
|
| 63 |
+
|
| 64 |
+
except Exception as e:
|
| 65 |
+
print(f"❌ CID {cid} 补全失败: {e}")
|
| 66 |
+
|
| 67 |
+
conn.close()
|
| 68 |
+
print("🎉 所有缺失字段补全完成!")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/归档/update_cid.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import sqlite3
|
| 3 |
+
import requests
|
| 4 |
+
import time
|
| 5 |
+
from rdkit import Chem
|
| 6 |
+
import pubchempy as pcp
|
| 7 |
+
|
| 8 |
+
DB_FILE = r"D:\2\111数据库\化合物汇总\compounds.db"
|
| 9 |
+
SLEEP_TIME = 1.5 # 请求间隔,避免 PubChem 限流
|
| 10 |
+
NOT_FOUND_LOG = "not_found_inchi.log"
|
| 11 |
+
|
| 12 |
+
# ===== 1. 连接数据库 =====
|
| 13 |
+
conn = sqlite3.connect(DB_FILE)
|
| 14 |
+
cursor = conn.cursor()
|
| 15 |
+
|
| 16 |
+
cursor.execute("""
|
| 17 |
+
SELECT id, inchi FROM compounds
|
| 18 |
+
WHERE (pubchem_cid IS NULL OR TRIM(pubchem_cid) = '')
|
| 19 |
+
AND inchi IS NOT NULL
|
| 20 |
+
AND TRIM(inchi) != ''
|
| 21 |
+
""")
|
| 22 |
+
rows = cursor.fetchall()
|
| 23 |
+
print(f"待补全记录数: {len(rows)}")
|
| 24 |
+
|
| 25 |
+
if not rows:
|
| 26 |
+
print("没有需要补全的记录,退出")
|
| 27 |
+
exit()
|
| 28 |
+
|
| 29 |
+
# ===== 2. 工具函数 =====
|
| 30 |
+
def inchi_to_inchikey(inchi: str):
|
| 31 |
+
try:
|
| 32 |
+
return Chem.inchi.InchiToInchiKey(inchi)
|
| 33 |
+
except Exception:
|
| 34 |
+
return None
|
| 35 |
+
|
| 36 |
+
def query_pubchem_by_inchikey(inchikey: str):
|
| 37 |
+
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/inchikey/{inchikey}/property/CID,InChI,InChIKey,CanonicalSMILES,IsomericSMILES,MolecularFormula,MolecularWeight/JSON"
|
| 38 |
+
try:
|
| 39 |
+
r = requests.get(url, timeout=30)
|
| 40 |
+
if r.status_code == 200:
|
| 41 |
+
data = r.json()
|
| 42 |
+
props = data.get("PropertyTable", {}).get("Properties", [])
|
| 43 |
+
if props:
|
| 44 |
+
return props[0]
|
| 45 |
+
except Exception:
|
| 46 |
+
pass
|
| 47 |
+
return None
|
| 48 |
+
|
| 49 |
+
def query_pubchem_by_inchi(inchi: str):
|
| 50 |
+
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/inchi/property/CID,InChI,InChIKey,CanonicalSMILES,IsomericSMILES,MolecularFormula,MolecularWeight/JSON"
|
| 51 |
+
try:
|
| 52 |
+
r = requests.post(url, data={"inchi": inchi}, timeout=30)
|
| 53 |
+
if r.status_code == 200:
|
| 54 |
+
data = r.json()
|
| 55 |
+
props = data.get("PropertyTable", {}).get("Properties", [])
|
| 56 |
+
if props:
|
| 57 |
+
return props[0]
|
| 58 |
+
except Exception:
|
| 59 |
+
pass
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
def query_pubchempy(inchi: str):
|
| 63 |
+
try:
|
| 64 |
+
comps = pcp.get_compounds(inchi, 'inchi')
|
| 65 |
+
if comps:
|
| 66 |
+
c = comps[0]
|
| 67 |
+
return {
|
| 68 |
+
"CID": c.cid,
|
| 69 |
+
"InChI": c.inchi,
|
| 70 |
+
"InChIKey": c.inchikey,
|
| 71 |
+
"CanonicalSMILES": c.canonical_smiles,
|
| 72 |
+
"IsomericSMILES": c.isomeric_smiles,
|
| 73 |
+
"MolecularFormula": c.molecular_formula,
|
| 74 |
+
"MolecularWeight": c.molecular_weight
|
| 75 |
+
}
|
| 76 |
+
except Exception:
|
| 77 |
+
pass
|
| 78 |
+
return None
|
| 79 |
+
|
| 80 |
+
def update_compound(rid, props):
|
| 81 |
+
cid = str(props.get("CID")) if props.get("CID") else None
|
| 82 |
+
inchi = props.get("InChI")
|
| 83 |
+
inchikey = props.get("InChIKey")
|
| 84 |
+
smiles = props.get("CanonicalSMILES") or props.get("IsomericSMILES")
|
| 85 |
+
formula = props.get("MolecularFormula")
|
| 86 |
+
weight = props.get("MolecularWeight")
|
| 87 |
+
|
| 88 |
+
cursor.execute("""
|
| 89 |
+
UPDATE compounds
|
| 90 |
+
SET
|
| 91 |
+
pubchem_cid = COALESCE(pubchem_cid, ?),
|
| 92 |
+
molecular_formula = COALESCE(molecular_formula, ?),
|
| 93 |
+
smiles = COALESCE(smiles, ?),
|
| 94 |
+
average_weight = COALESCE(average_weight, ?),
|
| 95 |
+
inchi = COALESCE(inchi, ?),
|
| 96 |
+
inchikey = COALESCE(inchikey, ?)
|
| 97 |
+
WHERE id = ?
|
| 98 |
+
""", (cid, formula, smiles, weight, inchi, inchikey, rid))
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# ===== 3. 主循环 =====
|
| 102 |
+
updated, not_found = 0, 0
|
| 103 |
+
with open(NOT_FOUND_LOG, "w", encoding="utf-8") as logf:
|
| 104 |
+
for idx, (rid, raw_inchi) in enumerate(rows, 1):
|
| 105 |
+
print(f"处理 {idx} / {len(rows)} (id={rid})")
|
| 106 |
+
props = None
|
| 107 |
+
|
| 108 |
+
# Step 1: InChI → InChIKey
|
| 109 |
+
inchikey = inchi_to_inchikey(raw_inchi)
|
| 110 |
+
if inchikey:
|
| 111 |
+
props = query_pubchem_by_inchikey(inchikey)
|
| 112 |
+
|
| 113 |
+
# Step 2: InChI 查询
|
| 114 |
+
if not props:
|
| 115 |
+
props = query_pubchem_by_inchi(raw_inchi)
|
| 116 |
+
|
| 117 |
+
# Step 3: pubchempy fallback
|
| 118 |
+
if not props:
|
| 119 |
+
props = query_pubchempy(raw_inchi)
|
| 120 |
+
|
| 121 |
+
# Step 4: 更新或记录未找到
|
| 122 |
+
if props:
|
| 123 |
+
update_compound(rid, props)
|
| 124 |
+
updated += 1
|
| 125 |
+
if updated <= 10: # 前10条打印调试
|
| 126 |
+
print(f"✅ 更新 id={rid}, CID={props.get('CID')}, InChIKey={props.get('InChIKey')}")
|
| 127 |
+
else:
|
| 128 |
+
not_found += 1
|
| 129 |
+
logf.write(f"{rid}\t{raw_inchi}\n")
|
| 130 |
+
print(f"❌ 未找到 id={rid}")
|
| 131 |
+
|
| 132 |
+
time.sleep(SLEEP_TIME)
|
| 133 |
+
|
| 134 |
+
# ===== 4. 收尾 =====
|
| 135 |
+
conn.commit()
|
| 136 |
+
conn.close()
|
| 137 |
+
print(f"🎉 已更新 {updated} 条记录,未找到 {not_found} 条,详情见 {NOT_FOUND_LOG}")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/归档/update_inchi.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import sqlite3
|
| 3 |
+
import requests
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import time
|
| 6 |
+
import io
|
| 7 |
+
|
| 8 |
+
DB_FILE = r"D:\2\111数据库\化合物汇总\compounds.db"
|
| 9 |
+
BATCH_SIZE = 5000
|
| 10 |
+
SLEEP_TIME = 2
|
| 11 |
+
|
| 12 |
+
# ===== 1. 连接数据库 =====
|
| 13 |
+
conn = sqlite3.connect(DB_FILE)
|
| 14 |
+
cursor = conn.cursor()
|
| 15 |
+
|
| 16 |
+
cursor.execute("""
|
| 17 |
+
SELECT id, pubchem_cid FROM compounds
|
| 18 |
+
WHERE (inchi IS NULL OR TRIM(inchi) = '')
|
| 19 |
+
AND pubchem_cid IS NOT NULL
|
| 20 |
+
""")
|
| 21 |
+
rows = cursor.fetchall()
|
| 22 |
+
print(f"待补全记录数: {len(rows)}")
|
| 23 |
+
|
| 24 |
+
if not rows:
|
| 25 |
+
print("没有缺失 InChI 的记录,退出")
|
| 26 |
+
exit()
|
| 27 |
+
|
| 28 |
+
# 转换为字符串形式,避免 int/str 不一致
|
| 29 |
+
cid_to_id = {str(cid): rid for rid, cid in rows}
|
| 30 |
+
cids = list(cid_to_id.keys())
|
| 31 |
+
|
| 32 |
+
# ===== 2. 批量请求 PubChem IEX =====
|
| 33 |
+
all_results = []
|
| 34 |
+
|
| 35 |
+
for i in range(0, len(cids), BATCH_SIZE):
|
| 36 |
+
batch = cids[i:i+BATCH_SIZE]
|
| 37 |
+
print(f"处理 {i+1} ~ {i+len(batch)} / {len(cids)}")
|
| 38 |
+
|
| 39 |
+
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/property/" \
|
| 40 |
+
"InChI,InChIKey,CanonicalSMILES,IsomericSMILES,MolecularFormula,MolecularWeight/CSV"
|
| 41 |
+
|
| 42 |
+
try:
|
| 43 |
+
response = requests.post(url, data={"cid": ",".join(batch)}, timeout=120)
|
| 44 |
+
response.raise_for_status()
|
| 45 |
+
df = pd.read_csv(io.StringIO(response.text))
|
| 46 |
+
all_results.append(df)
|
| 47 |
+
except Exception as e:
|
| 48 |
+
print(f"❌ 批次 {i} 出错: {e}")
|
| 49 |
+
time.sleep(SLEEP_TIME)
|
| 50 |
+
|
| 51 |
+
if not all_results:
|
| 52 |
+
print("没有获取到结果,退出")
|
| 53 |
+
exit()
|
| 54 |
+
|
| 55 |
+
results_df = pd.concat(all_results, ignore_index=True)
|
| 56 |
+
print(f"成功获取 {len(results_df)} 条 PubChem 结果")
|
| 57 |
+
|
| 58 |
+
# ===== 3. 写回数据库 =====
|
| 59 |
+
updated = 0
|
| 60 |
+
debug_count = 0
|
| 61 |
+
|
| 62 |
+
for _, row in results_df.iterrows():
|
| 63 |
+
cid = str(row.get("CID"))
|
| 64 |
+
if cid not in cid_to_id:
|
| 65 |
+
continue
|
| 66 |
+
rid = cid_to_id[cid]
|
| 67 |
+
|
| 68 |
+
inchi = row.get("InChI")
|
| 69 |
+
inchikey = row.get("InChIKey")
|
| 70 |
+
smiles = row.get("CanonicalSMILES") or row.get("IsomericSMILES")
|
| 71 |
+
formula = row.get("MolecularFormula")
|
| 72 |
+
weight = row.get("MolecularWeight")
|
| 73 |
+
|
| 74 |
+
cursor.execute("""
|
| 75 |
+
UPDATE compounds
|
| 76 |
+
SET
|
| 77 |
+
molecular_formula = COALESCE(molecular_formula, ?),
|
| 78 |
+
smiles = COALESCE(smiles, ?),
|
| 79 |
+
average_weight = COALESCE(average_weight, ?),
|
| 80 |
+
inchi = COALESCE(inchi, ?),
|
| 81 |
+
inchikey = COALESCE(inchikey, ?)
|
| 82 |
+
WHERE id = ?
|
| 83 |
+
""", (formula, smiles, weight, inchi, inchikey, rid))
|
| 84 |
+
if cursor.rowcount > 0:
|
| 85 |
+
updated += 1
|
| 86 |
+
if debug_count < 10: # 只打印前 10 条
|
| 87 |
+
print(f"更新 id={rid}, cid={cid}, inchi={inchi}, inchikey={inchikey}")
|
| 88 |
+
debug_count += 1
|
| 89 |
+
|
| 90 |
+
conn.commit()
|
| 91 |
+
conn.close()
|
| 92 |
+
|
| 93 |
+
print(f"🎉 已更新 {updated} 条记录")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/归档/补充.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import os
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import pubchempy as pcp
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
# ⚠️ 改成你存放 xlsx 的文件夹路径
|
| 8 |
+
INPUT_DIR = r"D:\2\111数据库\数据库-化合物\BATMAN-TCM_Info"
|
| 9 |
+
|
| 10 |
+
# 设置 PubChem API 请求超时
|
| 11 |
+
pcp.requests_timeout = 20
|
| 12 |
+
|
| 13 |
+
# 需要的列
|
| 14 |
+
COLUMNS = ["PubChem CID","Name","Molecular Formula","SMILES",
|
| 15 |
+
"Average Weight","InChI","InChKey","CAS"]
|
| 16 |
+
|
| 17 |
+
def fetch_info(identifier):
|
| 18 |
+
"""根据各种标识符在 PubChem 获取化合物对象"""
|
| 19 |
+
compound = None
|
| 20 |
+
try:
|
| 21 |
+
if str(identifier).isdigit():
|
| 22 |
+
compound = pcp.Compound.from_cid(int(identifier))
|
| 23 |
+
else:
|
| 24 |
+
compound = pcp.get_compounds(identifier, 'inchikey')
|
| 25 |
+
if not compound:
|
| 26 |
+
compound = pcp.get_compounds(identifier, 'inchi')
|
| 27 |
+
if not compound:
|
| 28 |
+
compound = pcp.get_compounds(identifier, 'smiles')
|
| 29 |
+
if not compound:
|
| 30 |
+
compound = pcp.get_compounds(identifier, 'name')
|
| 31 |
+
if compound:
|
| 32 |
+
compound = compound[0]
|
| 33 |
+
except Exception as e:
|
| 34 |
+
print(f"❌ 获取失败: {identifier}, 错误: {e}")
|
| 35 |
+
return compound
|
| 36 |
+
|
| 37 |
+
def fetch_cas(cid):
|
| 38 |
+
"""通过 PUG REST API 获取 CAS 号"""
|
| 39 |
+
try:
|
| 40 |
+
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{cid}/xrefs/RN/JSON"
|
| 41 |
+
r = requests.get(url, timeout=15)
|
| 42 |
+
r.raise_for_status()
|
| 43 |
+
data = r.json()
|
| 44 |
+
cas_list = data["InformationList"]["Information"][0]["RN"]
|
| 45 |
+
return ";".join(cas_list)
|
| 46 |
+
except Exception:
|
| 47 |
+
return None
|
| 48 |
+
|
| 49 |
+
def extract_info(compound):
|
| 50 |
+
"""从 compound 对象提取所需信息"""
|
| 51 |
+
if not compound:
|
| 52 |
+
return {col: None for col in COLUMNS}
|
| 53 |
+
|
| 54 |
+
cas_value = fetch_cas(compound.cid) if compound.cid else None
|
| 55 |
+
|
| 56 |
+
return {
|
| 57 |
+
"PubChem CID": compound.cid,
|
| 58 |
+
"Name": compound.iupac_name,
|
| 59 |
+
"Molecular Formula": compound.molecular_formula,
|
| 60 |
+
"SMILES": compound.canonical_smiles,
|
| 61 |
+
"Average Weight": compound.molecular_weight,
|
| 62 |
+
"InChI": compound.inchi,
|
| 63 |
+
"InChKey": compound.inchikey,
|
| 64 |
+
"CAS": cas_value
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
# 遍历文件夹下的所有 xlsx 文件
|
| 68 |
+
for file in os.listdir(INPUT_DIR):
|
| 69 |
+
if not file.endswith(".xlsx"):
|
| 70 |
+
continue
|
| 71 |
+
file_path = os.path.join(INPUT_DIR, file)
|
| 72 |
+
print(f"\n📂 正在处理: {file}")
|
| 73 |
+
|
| 74 |
+
df = pd.read_excel(file_path)
|
| 75 |
+
|
| 76 |
+
# 保证目标列存在
|
| 77 |
+
for col in COLUMNS:
|
| 78 |
+
if col not in df.columns:
|
| 79 |
+
df[col] = None
|
| 80 |
+
|
| 81 |
+
for i, row in df.iterrows():
|
| 82 |
+
# 如果该行所有目标字段都有值 -> 跳过
|
| 83 |
+
if all(pd.notna(row[col]) for col in COLUMNS):
|
| 84 |
+
continue
|
| 85 |
+
|
| 86 |
+
identifier = (row.get("PubChem CID") or row.get("InChKey") or
|
| 87 |
+
row.get("InChI") or row.get("SMILES") or row.get("Name"))
|
| 88 |
+
if not identifier or pd.isna(identifier):
|
| 89 |
+
continue
|
| 90 |
+
|
| 91 |
+
compound = fetch_info(identifier)
|
| 92 |
+
info = extract_info(compound)
|
| 93 |
+
|
| 94 |
+
# 只补全缺失的列
|
| 95 |
+
for col in COLUMNS:
|
| 96 |
+
if pd.isna(row[col]) or row[col] is None:
|
| 97 |
+
df.at[i, col] = info[col]
|
| 98 |
+
|
| 99 |
+
print(f"✅ {i+1}/{len(df)} 已补全: {identifier}")
|
| 100 |
+
|
| 101 |
+
# ⚠️ 覆盖保存原文件
|
| 102 |
+
df.to_excel(file_path, index=False)
|
| 103 |
+
print(f"💾 已覆盖保存: {file_path}")
|
| 104 |
+
|
| 105 |
+
print("\n🎉 所有文件已处理完成!")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/模型/Compound/KNN_cos_distance.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pickle
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from sklearn.neighbors import KNeighborsClassifier
|
| 5 |
+
from sklearn.preprocessing import LabelEncoder
|
| 6 |
+
|
| 7 |
+
# -------------------- Paths --------------------
|
| 8 |
+
multihot_path = r"D:\2\111数据库\模型\cluster512_result\herb_multihot.pkl"
|
| 9 |
+
seed_path = r"D:\2\111数据库\模型\seed2.csv"
|
| 10 |
+
|
| 11 |
+
# -------------------- 1. Load multihot --------------------
|
| 12 |
+
with open(multihot_path, "rb") as f:
|
| 13 |
+
herb_dict = pickle.load(f)
|
| 14 |
+
|
| 15 |
+
all_names = sorted(herb_dict.keys())
|
| 16 |
+
all_fp = np.array([herb_dict[name] for name in all_names], dtype=float)
|
| 17 |
+
|
| 18 |
+
print("Loaded multi-hot herbs:", len(all_names))
|
| 19 |
+
print("Feature shape:", all_fp.shape)
|
| 20 |
+
|
| 21 |
+
# -------------------- 2. Load seed.csv --------------------
|
| 22 |
+
df_seed = pd.read_csv(seed_path, encoding="gbk")
|
| 23 |
+
name_to_idx = {name: i for i, name in enumerate(all_names)}
|
| 24 |
+
|
| 25 |
+
train_idxs = []
|
| 26 |
+
for name in df_seed["herb"]:
|
| 27 |
+
if name not in name_to_idx:
|
| 28 |
+
raise ValueError(f"Seed herb '{name}' not found in multihot list.")
|
| 29 |
+
train_idxs.append(name_to_idx[name])
|
| 30 |
+
|
| 31 |
+
X_train = all_fp[train_idxs]
|
| 32 |
+
y_train = df_seed["label"].values
|
| 33 |
+
X_all = all_fp
|
| 34 |
+
|
| 35 |
+
# -------------------- 3. Encode labels --------------------
|
| 36 |
+
le = LabelEncoder()
|
| 37 |
+
y_train_enc = le.fit_transform(y_train)
|
| 38 |
+
|
| 39 |
+
# -------------------- 4. Fit KNN --------------------
|
| 40 |
+
knn = KNeighborsClassifier(
|
| 41 |
+
n_neighbors=7,
|
| 42 |
+
metric="cosine",
|
| 43 |
+
weights="distance"
|
| 44 |
+
)
|
| 45 |
+
knn.fit(X_train, y_train_enc)
|
| 46 |
+
|
| 47 |
+
# -------------------- 5. Predict all --------------------
|
| 48 |
+
y_pred_enc = knn.predict(X_all)
|
| 49 |
+
y_pred = le.inverse_transform(y_pred_enc)
|
| 50 |
+
|
| 51 |
+
# -------------------- 6. Neighbors --------------------
|
| 52 |
+
distances, indices = knn.kneighbors(X_all, n_neighbors=7)
|
| 53 |
+
similarities = 1 - distances
|
| 54 |
+
|
| 55 |
+
# -------------------- 7. Fix predictions for seed herbs --------------------
|
| 56 |
+
for herb, label in zip(df_seed["herb"], df_seed["label"]):
|
| 57 |
+
idx = name_to_idx[herb]
|
| 58 |
+
y_pred[idx] = label
|
| 59 |
+
|
| 60 |
+
# -------------------- 8. Build label → seed herbs --------------------
|
| 61 |
+
label_to_herbs = df_seed.groupby("label")["herb"].apply(list).to_dict()
|
| 62 |
+
|
| 63 |
+
# -------------------- 9. Build output --------------------
|
| 64 |
+
rows = []
|
| 65 |
+
for i, herb in enumerate(all_names):
|
| 66 |
+
pred_label = y_pred[i]
|
| 67 |
+
pred_seed_list = label_to_herbs.get(pred_label, [])
|
| 68 |
+
pred_seed_str = "\t".join(pred_seed_list)
|
| 69 |
+
|
| 70 |
+
# neighbor info
|
| 71 |
+
neigh_fields = []
|
| 72 |
+
for pos, sim in zip(indices[i], similarities[i]):
|
| 73 |
+
global_idx = train_idxs[pos]
|
| 74 |
+
neigh_name = all_names[global_idx]
|
| 75 |
+
neigh_label = y_train[pos]
|
| 76 |
+
neigh_fields += [neigh_name, neigh_label, f"{sim:.4f}"]
|
| 77 |
+
|
| 78 |
+
rows.append([
|
| 79 |
+
herb,
|
| 80 |
+
pred_label,
|
| 81 |
+
pred_seed_str,
|
| 82 |
+
"\t".join(neigh_fields)
|
| 83 |
+
])
|
| 84 |
+
|
| 85 |
+
df_out = pd.DataFrame(rows, columns=[
|
| 86 |
+
"herb", "pred_label", "pred_label_herbs", "neighbors"
|
| 87 |
+
])
|
| 88 |
+
df_out.to_csv("KNN_results.csv", index=False, encoding="utf-8-sig")
|
| 89 |
+
|
| 90 |
+
print("🎉 完成:输出已保存为 KNN_results.csv")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/模型/Compound/Kmeans_multi-hot.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pickle
|
| 3 |
+
import numpy as np
|
| 4 |
+
from sklearn.cluster import KMeans
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
|
| 7 |
+
# ============================================
|
| 8 |
+
# 配置路径 —— 与你提供的脚本保持一致
|
| 9 |
+
# ============================================
|
| 10 |
+
fp_path = "/mnt/disk1/yanganqi/RE/Fingerprint/structure/ECFP4/morgan_fp.npy"
|
| 11 |
+
name_path = "/mnt/disk1/yanganqi/RE/Fingerprint/structure/ECFP4/morgan_fp_names.pkl"
|
| 12 |
+
herb_root = "/mnt/disk1/yanganqi/chemical_structures"
|
| 13 |
+
|
| 14 |
+
# 输出目录
|
| 15 |
+
outdir = "./cluster512_result"
|
| 16 |
+
os.makedirs(outdir, exist_ok=True)
|
| 17 |
+
|
| 18 |
+
# ============================================
|
| 19 |
+
# 1. 加载分子指纹 + 名字
|
| 20 |
+
# ============================================
|
| 21 |
+
print("📥 Loading fingerprints ...")
|
| 22 |
+
fps = np.load(fp_path) # shape: (41948, 2048)
|
| 23 |
+
|
| 24 |
+
with open(name_path, "rb") as f:
|
| 25 |
+
fp_names = pickle.load(f)
|
| 26 |
+
|
| 27 |
+
n_mol, n_bits = fps.shape
|
| 28 |
+
print(f"Loaded {n_mol} fingerprints, each {n_bits} bits")
|
| 29 |
+
|
| 30 |
+
# 建立名字索引
|
| 31 |
+
fp_name_to_idx = {str(name): i for i, name in enumerate(fp_names)}
|
| 32 |
+
fp_name_set = set(fp_name_to_idx.keys())
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# ============================================
|
| 36 |
+
# 名字归一化(复用你原脚本的逻辑)
|
| 37 |
+
# ============================================
|
| 38 |
+
def normalize_key_variants(name):
|
| 39 |
+
s = str(name)
|
| 40 |
+
cand = [s, s.lower()]
|
| 41 |
+
|
| 42 |
+
if s.lower().endswith(".sdf"):
|
| 43 |
+
s_no = s[:-4]
|
| 44 |
+
cand += [s_no, s_no.lower()]
|
| 45 |
+
else:
|
| 46 |
+
cand += [s + ".sdf", (s + ".sdf").lower()]
|
| 47 |
+
|
| 48 |
+
# strip prefixes
|
| 49 |
+
for prefix in ("CID_", "cid_", "CID", "cid", "mol_", "m_"):
|
| 50 |
+
if s.startswith(prefix):
|
| 51 |
+
cand += [s[len(prefix):], s[len(prefix):].lower()]
|
| 52 |
+
cand += [prefix + s, (prefix + s).lower()]
|
| 53 |
+
|
| 54 |
+
# digits
|
| 55 |
+
digits = "".join(ch for ch in s if ch.isdigit())
|
| 56 |
+
if digits:
|
| 57 |
+
cand += [digits, digits.lstrip("0"), digits + ".sdf"]
|
| 58 |
+
|
| 59 |
+
uniq = []
|
| 60 |
+
seen = set()
|
| 61 |
+
for c in cand:
|
| 62 |
+
if c not in seen:
|
| 63 |
+
seen.add(c)
|
| 64 |
+
uniq.append(c)
|
| 65 |
+
return uniq
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# ============================================
|
| 69 |
+
# 2. K-Means 聚类(K=512)
|
| 70 |
+
# ============================================
|
| 71 |
+
K = 512
|
| 72 |
+
print(f"🔧 Running K-Means clustering with K={K} ...")
|
| 73 |
+
|
| 74 |
+
kmeans = KMeans(
|
| 75 |
+
n_clusters=K,
|
| 76 |
+
random_state=42,
|
| 77 |
+
max_iter=300,
|
| 78 |
+
n_init=10,
|
| 79 |
+
verbose=1
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
labels = kmeans.fit_predict(fps)
|
| 83 |
+
|
| 84 |
+
print("🎉 Clustering finished.")
|
| 85 |
+
|
| 86 |
+
# 保存聚类结果
|
| 87 |
+
np.save(os.path.join(outdir, "cluster_labels.npy"), labels)
|
| 88 |
+
|
| 89 |
+
name_to_cluster = {fp_names[i]: int(labels[i]) for i in range(n_mol)}
|
| 90 |
+
|
| 91 |
+
with open(os.path.join(outdir, "name_to_cluster.pkl"), "wb") as f:
|
| 92 |
+
pickle.dump(name_to_cluster, f)
|
| 93 |
+
|
| 94 |
+
print("📁 Saved cluster labels and name mapping.")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# ============================================
|
| 98 |
+
# 3. 读取 herb 文件夹结构,匹配成分
|
| 99 |
+
# ============================================
|
| 100 |
+
print("🌿 Building herb → compound mapping from herb folders ...")
|
| 101 |
+
|
| 102 |
+
all_herbs = sorted(os.listdir(herb_root))
|
| 103 |
+
herb_multihot = {}
|
| 104 |
+
missing_log = []
|
| 105 |
+
|
| 106 |
+
for herb in all_herbs:
|
| 107 |
+
herb_dir = os.path.join(herb_root, herb)
|
| 108 |
+
if not os.path.isdir(herb_dir):
|
| 109 |
+
continue
|
| 110 |
+
|
| 111 |
+
sdf_files = [x for x in os.listdir(herb_dir) if x.endswith(".sdf")]
|
| 112 |
+
if len(sdf_files) == 0:
|
| 113 |
+
print(f"[WARN] Herb {herb} has 0 sdf files, skipping.")
|
| 114 |
+
continue
|
| 115 |
+
|
| 116 |
+
vec = np.zeros(K, dtype=int)
|
| 117 |
+
miss_local = []
|
| 118 |
+
|
| 119 |
+
for sdf in sdf_files:
|
| 120 |
+
found = False
|
| 121 |
+
variants = normalize_key_variants(sdf)
|
| 122 |
+
|
| 123 |
+
for v in variants:
|
| 124 |
+
if v in fp_name_to_idx:
|
| 125 |
+
idx = fp_name_to_idx[v]
|
| 126 |
+
c = labels[idx]
|
| 127 |
+
vec[c] += 1
|
| 128 |
+
found = True
|
| 129 |
+
break
|
| 130 |
+
|
| 131 |
+
if not found:
|
| 132 |
+
miss_local.append(sdf)
|
| 133 |
+
missing_log.append(f"{herb}\t{sdf}")
|
| 134 |
+
|
| 135 |
+
herb_multihot[herb] = vec
|
| 136 |
+
|
| 137 |
+
print(f"[INFO] Herb {herb}: {len(sdf_files)} SDFs, matched {len(sdf_files)-len(miss_local)}, missing {len(miss_local)}")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# ============================================
|
| 141 |
+
# 4. 保存中药 multi-hot 向量
|
| 142 |
+
# ============================================
|
| 143 |
+
with open(os.path.join(outdir, "herb_multihot.pkl"), "wb") as f:
|
| 144 |
+
pickle.dump(herb_multihot, f)
|
| 145 |
+
|
| 146 |
+
# 保存为 CSV(可选)
|
| 147 |
+
import pandas as pd
|
| 148 |
+
df = pd.DataFrame.from_dict(herb_multihot, orient="index")
|
| 149 |
+
df.to_csv(os.path.join(outdir, "herb_multihot.csv"))
|
| 150 |
+
|
| 151 |
+
print("🌈 Saved herb multi-hot fingerprints.")
|
| 152 |
+
|
| 153 |
+
# missing log
|
| 154 |
+
with open(os.path.join(outdir, "missing_sdf.txt"), "w", encoding="utf-8") as f:
|
| 155 |
+
for line in missing_log:
|
| 156 |
+
f.write(line + "\n")
|
| 157 |
+
|
| 158 |
+
print("📄 Logged missing sdf files.")
|
| 159 |
+
print("✨ All done.")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/模型/Compound/结构下载.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
import pubchempy as pcp
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
# 设置基本参数
|
| 8 |
+
BASE_DIR = "chemical_structures"
|
| 9 |
+
ERROR_LOG_FILE = os.path.join(BASE_DIR, "download_errors.log")
|
| 10 |
+
CSV_FILE = r"D:\2\111数据库\药典中药汇总.csv"
|
| 11 |
+
|
| 12 |
+
def clean_herb_name(name):
|
| 13 |
+
"""清理中药名称,去掉括号及其中的内容"""
|
| 14 |
+
return re.sub(r'\(.*?\)|\(.*?\)', '', str(name)).strip()
|
| 15 |
+
|
| 16 |
+
def clean_data():
|
| 17 |
+
"""清理数据并保存"""
|
| 18 |
+
print("开始清理数据...")
|
| 19 |
+
try:
|
| 20 |
+
df = pd.read_csv(CSV_FILE, encoding='gbk', low_memory=False)
|
| 21 |
+
|
| 22 |
+
# 清理pubchemcid列
|
| 23 |
+
def clean_pubchemcid(x):
|
| 24 |
+
if pd.isna(x):
|
| 25 |
+
return None
|
| 26 |
+
try:
|
| 27 |
+
return int(float(str(x).strip()))
|
| 28 |
+
except:
|
| 29 |
+
return None
|
| 30 |
+
|
| 31 |
+
# 清理并转换数据类型
|
| 32 |
+
df['pubchemcid'] = df['pubchemcid'].apply(clean_pubchemcid)
|
| 33 |
+
|
| 34 |
+
# 保存修改后的文件
|
| 35 |
+
df.to_csv(CSV_FILE, index=False, encoding='gbk')
|
| 36 |
+
|
| 37 |
+
print("数据清理完成!")
|
| 38 |
+
print(f"总行数: {len(df)}")
|
| 39 |
+
print(f"有效CID数量: {df['pubchemcid'].notna().sum()}")
|
| 40 |
+
print(f"空值数量: {df['pubchemcid'].isna().sum()}")
|
| 41 |
+
print("\n数据类型检查:")
|
| 42 |
+
print(df['pubchemcid'].dtype)
|
| 43 |
+
print("\n前几个CID示例:")
|
| 44 |
+
print(df['pubchemcid'].head(10))
|
| 45 |
+
|
| 46 |
+
return df
|
| 47 |
+
|
| 48 |
+
except Exception as e:
|
| 49 |
+
print(f"数据清理过程出错: {str(e)}")
|
| 50 |
+
return None
|
| 51 |
+
|
| 52 |
+
def log_error(cid, record_type, error_message):
|
| 53 |
+
"""记录错误信息"""
|
| 54 |
+
try:
|
| 55 |
+
with open(ERROR_LOG_FILE, 'a', encoding='utf-8') as log_file:
|
| 56 |
+
log_file.write(f"CID {cid} ({record_type}): {error_message}\n")
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print(f"Failed to log error: {e}")
|
| 59 |
+
|
| 60 |
+
def download_sdf(cid, herb_dir, herb_name, max_retries=5, retry_delay=60):
|
| 61 |
+
"""下载单个化合物的结构"""
|
| 62 |
+
try:
|
| 63 |
+
cid = int(cid)
|
| 64 |
+
except:
|
| 65 |
+
print(f"Invalid CID: {cid}")
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
if not os.path.exists(herb_dir):
|
| 69 |
+
os.makedirs(herb_dir)
|
| 70 |
+
|
| 71 |
+
output_file_path = os.path.join(herb_dir, f"{cid}.sdf")
|
| 72 |
+
|
| 73 |
+
# 只检查当前中药文件夹中是否存在该结构文件
|
| 74 |
+
if os.path.exists(output_file_path) and os.path.getsize(output_file_path) > 50:
|
| 75 |
+
print(f"File already exists for CID {cid} in {herb_name}")
|
| 76 |
+
return output_file_path
|
| 77 |
+
|
| 78 |
+
# 尝试下载3D结构
|
| 79 |
+
try:
|
| 80 |
+
sdf_data = pcp.get_sdf(identifier=cid, namespace='cid', record_type='3d', overwrite=True)
|
| 81 |
+
|
| 82 |
+
if sdf_data and len(sdf_data) >= 50:
|
| 83 |
+
with open(output_file_path, 'wb') as file:
|
| 84 |
+
file.write(sdf_data.encode('utf-8') if isinstance(sdf_data, str) else sdf_data)
|
| 85 |
+
|
| 86 |
+
if os.path.getsize(output_file_path) >= 50:
|
| 87 |
+
print(f"Successfully downloaded CID {cid} (3d)")
|
| 88 |
+
return output_file_path
|
| 89 |
+
|
| 90 |
+
print(f"CID {cid} (3d) 返回空结构")
|
| 91 |
+
|
| 92 |
+
except Exception as e:
|
| 93 |
+
print(f"Error downloading 3D structure for CID {cid}: {e}")
|
| 94 |
+
log_error(cid, '3d', f"Download error: {e}")
|
| 95 |
+
|
| 96 |
+
# 尝试下载2D结构
|
| 97 |
+
try:
|
| 98 |
+
sdf_data = pcp.get_sdf(identifier=cid, namespace='cid', record_type='2d', overwrite=True)
|
| 99 |
+
|
| 100 |
+
if not sdf_data or len(sdf_data) < 50:
|
| 101 |
+
print(f"CID {cid} (2d) 返回空结构")
|
| 102 |
+
log_error(cid, '2d', "Empty SDF content")
|
| 103 |
+
return None
|
| 104 |
+
|
| 105 |
+
with open(output_file_path, 'wb') as file:
|
| 106 |
+
file.write(sdf_data.encode('utf-8') if isinstance(sdf_data, str) else sdf_data)
|
| 107 |
+
|
| 108 |
+
if os.path.getsize(output_file_path) < 50:
|
| 109 |
+
print(f"CID {cid} (2d) 文件过小,可能无效")
|
| 110 |
+
log_error(cid, '2d', "File too small")
|
| 111 |
+
return None
|
| 112 |
+
|
| 113 |
+
print(f"Successfully downloaded CID {cid} (2d)")
|
| 114 |
+
return output_file_path
|
| 115 |
+
|
| 116 |
+
except pcp.PubChemHTTPError as e:
|
| 117 |
+
if 'PUGREST.ServerBusy' in str(e):
|
| 118 |
+
print(f"Server busy for CID {cid}. Please try later.")
|
| 119 |
+
else:
|
| 120 |
+
print(f"Unexpected error for CID {cid}: {e}")
|
| 121 |
+
log_error(cid, '2d', f"Download error: {e}")
|
| 122 |
+
return None
|
| 123 |
+
|
| 124 |
+
except Exception as e:
|
| 125 |
+
print(f"Error downloading 2D structure for CID {cid}: {e}")
|
| 126 |
+
log_error(cid, '2d', f"Download error: {e}")
|
| 127 |
+
return None
|
| 128 |
+
|
| 129 |
+
def main():
|
| 130 |
+
# 清理数据
|
| 131 |
+
df = clean_data()
|
| 132 |
+
if df is None:
|
| 133 |
+
print("数据清理失败,程序退出")
|
| 134 |
+
return
|
| 135 |
+
|
| 136 |
+
# 创建基础目录
|
| 137 |
+
if not os.path.exists(BASE_DIR):
|
| 138 |
+
os.makedirs(BASE_DIR)
|
| 139 |
+
|
| 140 |
+
# 清除旧的错误日志
|
| 141 |
+
if os.path.exists(ERROR_LOG_FILE):
|
| 142 |
+
os.remove(ERROR_LOG_FILE)
|
| 143 |
+
|
| 144 |
+
success_count = 0
|
| 145 |
+
fail_count = 0
|
| 146 |
+
|
| 147 |
+
# 遍历每个中药及其化学成分
|
| 148 |
+
for herb, group in df.groupby('herb'):
|
| 149 |
+
if pd.isna(herb):
|
| 150 |
+
continue
|
| 151 |
+
|
| 152 |
+
# 清理中药名称
|
| 153 |
+
cleaned_herb = clean_herb_name(herb)
|
| 154 |
+
print(f"\nProcessing herb: {herb} (cleaned name: {cleaned_herb})")
|
| 155 |
+
|
| 156 |
+
herb_dir = os.path.join(BASE_DIR, cleaned_herb)
|
| 157 |
+
|
| 158 |
+
# 处理该中药的所有化学成分
|
| 159 |
+
for _, row in group.iterrows():
|
| 160 |
+
if pd.notna(row['pubchemcid']):
|
| 161 |
+
result = download_sdf(row['pubchemcid'], herb_dir, cleaned_herb)
|
| 162 |
+
if result:
|
| 163 |
+
success_count += 1
|
| 164 |
+
else:
|
| 165 |
+
fail_count += 1
|
| 166 |
+
|
| 167 |
+
print("\nDownload completed!")
|
| 168 |
+
print(f"\n统计信息:")
|
| 169 |
+
print(f"成功下载: {success_count}")
|
| 170 |
+
print(f"失败数量: {fail_count}")
|
| 171 |
+
print(f"总中药数量: {df['herb'].nunique()}")
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
main()
|
recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/check.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
print(f"是否检测到显卡: {torch.cuda.is_available()}")
|
| 3 |
+
print(f"当前设备名: {torch.cuda.get_device_name(0)}")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/embed_herb_text.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoTokenizer, AutoModel
|
| 2 |
+
import torch
|
| 3 |
+
import numpy as np
|
| 4 |
+
from tqdm import tqdm
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
# ================== 路径配置 ==================
|
| 8 |
+
# 本地模型路径(已提前下载)
|
| 9 |
+
MODEL_PATH = Path("herberta_seq_512_V2")
|
| 10 |
+
|
| 11 |
+
# 输入文本(相对路径)
|
| 12 |
+
INPUT_TXT = Path("processed_文本1.txt")
|
| 13 |
+
|
| 14 |
+
# 输出目录
|
| 15 |
+
OUTPUT_DIR = Path("output1")
|
| 16 |
+
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 17 |
+
|
| 18 |
+
EMB_PATH = OUTPUT_DIR / "herb_embeddings.npy"
|
| 19 |
+
NAME_PATH = OUTPUT_DIR / "herb_names.txt"
|
| 20 |
+
|
| 21 |
+
# ================== 设备 ==================
|
| 22 |
+
# ⚠️ 显式使用国产 AI 卡的 cuda:0
|
| 23 |
+
device = torch.device("cuda:0")
|
| 24 |
+
print(f"📟 使用设备: {device}")
|
| 25 |
+
print(f"🧩 设备名称: {torch.cuda.get_device_name(0)}")
|
| 26 |
+
|
| 27 |
+
# ================== 模型 ==================
|
| 28 |
+
print("🔄 加载 tokenizer 和 model ...")
|
| 29 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
|
| 30 |
+
|
| 31 |
+
# ⚠️ 不使用 pooler,只做 encoder 推理
|
| 32 |
+
model = AutoModel.from_pretrained(
|
| 33 |
+
MODEL_PATH,
|
| 34 |
+
add_pooling_layer=False
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
model.to(device)
|
| 38 |
+
model.eval()
|
| 39 |
+
|
| 40 |
+
# ================== 读取文本 ==================
|
| 41 |
+
herb_names = []
|
| 42 |
+
texts = []
|
| 43 |
+
|
| 44 |
+
with INPUT_TXT.open("r", encoding="utf-8") as f:
|
| 45 |
+
for idx, line in enumerate(f):
|
| 46 |
+
line = line.strip()
|
| 47 |
+
if not line:
|
| 48 |
+
continue
|
| 49 |
+
|
| 50 |
+
# 情况 1:药名:功效文本
|
| 51 |
+
if ":" in line:
|
| 52 |
+
name, text = line.split(":", 1)
|
| 53 |
+
# 情况 2:只有文本
|
| 54 |
+
else:
|
| 55 |
+
name = f"herb_{idx}"
|
| 56 |
+
text = line
|
| 57 |
+
|
| 58 |
+
herb_names.append(name)
|
| 59 |
+
texts.append(text)
|
| 60 |
+
|
| 61 |
+
print(f"📄 读取到 {len(texts)} 条中药文本")
|
| 62 |
+
|
| 63 |
+
# ================== 生成 embedding ==================
|
| 64 |
+
embeddings = []
|
| 65 |
+
|
| 66 |
+
with torch.no_grad():
|
| 67 |
+
for text in tqdm(texts, desc="🧠 Embedding herbs (K500SM_AI)"):
|
| 68 |
+
inputs = tokenizer(
|
| 69 |
+
text,
|
| 70 |
+
return_tensors="pt",
|
| 71 |
+
truncation=True,
|
| 72 |
+
max_length=512,
|
| 73 |
+
padding="max_length"
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 77 |
+
outputs = model(**inputs)
|
| 78 |
+
|
| 79 |
+
# ✅ 使用 CLS token 的 hidden state
|
| 80 |
+
vec = outputs.last_hidden_state[:, 0, :]
|
| 81 |
+
embeddings.append(vec.detach().cpu().numpy()[0])
|
| 82 |
+
|
| 83 |
+
embeddings = np.vstack(embeddings)
|
| 84 |
+
|
| 85 |
+
# ================== 保存 ==================
|
| 86 |
+
np.save(EMB_PATH, embeddings)
|
| 87 |
+
|
| 88 |
+
with NAME_PATH.open("w", encoding="utf-8") as f:
|
| 89 |
+
for name in herb_names:
|
| 90 |
+
f.write(name + "\n")
|
| 91 |
+
|
| 92 |
+
print("✅ 嵌入完成")
|
| 93 |
+
print(f"📐 向量形状: {embeddings.shape}")
|
| 94 |
+
print(f"💾 向量保存路径: {EMB_PATH.resolve()}")
|
| 95 |
+
print(f"📄 名称保存路径: {NAME_PATH.resolve()}")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/embedding/check.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
print(f"是否检测到显卡: {torch.cuda.is_available()}")
|
| 3 |
+
print(f"当前设备名: {torch.cuda.get_device_name(0)}")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/embedding/kg/filter_pharmacopoeia_herbs.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
# =====================
|
| 5 |
+
# 路径
|
| 6 |
+
# =====================
|
| 7 |
+
|
| 8 |
+
PRED_PATH = "/public/home/vitami/embedding/kg/herb_flavor_knn_prediction.csv"
|
| 9 |
+
PHARMA_PATH = "/public/home/vitami/embedding/kg/药典.xlsx"
|
| 10 |
+
|
| 11 |
+
OUTPUT_PATH = "/public/home/vitami/embedding/kg/pharmacopoeia_herb_predictions.csv"
|
| 12 |
+
UNMATCHED_PATH = "/public/home/vitami/embedding/kg/unmatched_pharmacopoeia.txt"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# =====================
|
| 16 |
+
# alias 表(手动维护)
|
| 17 |
+
# 药典名 -> KG名
|
| 18 |
+
# =====================
|
| 19 |
+
|
| 20 |
+
alias_map = {
|
| 21 |
+
|
| 22 |
+
# 物种 → 药材
|
| 23 |
+
"白芍": ["芍药"],
|
| 24 |
+
"赤芍": ["芍药"],
|
| 25 |
+
"元胡": ["延胡索"],
|
| 26 |
+
"冰片": ["天然冰片"],
|
| 27 |
+
"大血藤": ["红藤"],
|
| 28 |
+
"大皂角": ["皂荚"],
|
| 29 |
+
"大青叶": ["大青"],
|
| 30 |
+
"土荆皮": ["土荆芥"],
|
| 31 |
+
"山银花": ["大金银花"],
|
| 32 |
+
"川射干": ["鸢尾"],
|
| 33 |
+
"龙胆": ["龙胆草"],
|
| 34 |
+
"广藿香": ["藿香"],
|
| 35 |
+
"小叶莲": ["桃儿七"],
|
| 36 |
+
"白矾": ["明矾"],
|
| 37 |
+
"白果": ["银杏"],
|
| 38 |
+
"白扁豆": ["扁豆"],
|
| 39 |
+
"西红花": ["藏红花"],
|
| 40 |
+
"西青果": ["藏青果"],
|
| 41 |
+
"西河柳": ["山柳"],
|
| 42 |
+
"血余炭": ["血余"],
|
| 43 |
+
"牡荆叶": ["黄荆叶"],
|
| 44 |
+
"辛夷": ["辛夷花"],
|
| 45 |
+
"苦杏仁": ["杏仁"],
|
| 46 |
+
"郁金": ["郁金香"],
|
| 47 |
+
"金龙胆草": ["苦蒿"],
|
| 48 |
+
"枫香脂": ["白胶香"],
|
| 49 |
+
"昆布": ["海带"],
|
| 50 |
+
"肿节风": ["九节茶"],
|
| 51 |
+
"锦灯笼": ["灯笼草"],
|
| 52 |
+
"矮地茶": ["紫金牛"],
|
| 53 |
+
"滑石粉": ["滑石"],
|
| 54 |
+
"黑芝麻": ["黑脂麻"],
|
| 55 |
+
"紫萁贯众": ["紫萁"],
|
| 56 |
+
"硫黄": ["硫磺"],
|
| 57 |
+
"断血流": ["风轮菜"],
|
| 58 |
+
"海风藤": ["风藤"],
|
| 59 |
+
"海金沙": ["海金砂"],
|
| 60 |
+
"红大戟": ["九龙根"],
|
| 61 |
+
"龙脷叶": ["龙利叶"],
|
| 62 |
+
"功劳木": ["十大功劳"],
|
| 63 |
+
"火麻仁": ["胡麻仁"],
|
| 64 |
+
"广枣": ["南酸枣"],
|
| 65 |
+
"小茴香": ["茴香"],
|
| 66 |
+
"小驳骨": ["接骨草"],
|
| 67 |
+
"天山雪莲": ["雪莲"],
|
| 68 |
+
"广东紫珠": ["止血丹"],
|
| 69 |
+
"天仙子": ["东莨菪"],
|
| 70 |
+
"木芙蓉叶": ["芙蓉叶"],
|
| 71 |
+
"天葵子": ["天葵"],
|
| 72 |
+
"谷芽": ["稻芽"],
|
| 73 |
+
"闹羊花": ["羊踯躅"],
|
| 74 |
+
"油松节": ["松节"],
|
| 75 |
+
"贯叶金丝桃": ["贯叶连翘"],
|
| 76 |
+
"南五味子": ["山五味子"],
|
| 77 |
+
"南沙参": ["沙参"],
|
| 78 |
+
"哈蟆油": ["蛤蟆油"],
|
| 79 |
+
"禹余粮": ["禹粮土"],
|
| 80 |
+
"急性子": ["凤仙"],
|
| 81 |
+
"洪连": ["兔耳草"],
|
| 82 |
+
"洋金花": ["曼陀罗"],
|
| 83 |
+
"穿山龙": ["穿龙薯蓣"],
|
| 84 |
+
"络石藤": ["白花藤"],
|
| 85 |
+
"秦皮": ["白蜡树皮"],
|
| 86 |
+
"预知子": ["八月瓜"],
|
| 87 |
+
"滇鸡血藤": ["黑血藤"],
|
| 88 |
+
"颠茄草": ["颠茄"],
|
| 89 |
+
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# =====================
|
| 94 |
+
# 1 读取预测结果
|
| 95 |
+
# =====================
|
| 96 |
+
|
| 97 |
+
print("Loading prediction results...")
|
| 98 |
+
|
| 99 |
+
pred_df = pd.read_csv(PRED_PATH)
|
| 100 |
+
|
| 101 |
+
print("Total predicted herbs:", len(pred_df))
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# KG中herb名称集合
|
| 105 |
+
kg_names = set(pred_df["name"])
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# =====================
|
| 109 |
+
# 2 读取药典
|
| 110 |
+
# =====================
|
| 111 |
+
|
| 112 |
+
print("Loading pharmacopoeia list...")
|
| 113 |
+
|
| 114 |
+
pharma_df = pd.read_excel(PHARMA_PATH)
|
| 115 |
+
|
| 116 |
+
print("Pharmacopoeia herbs:", len(pharma_df))
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# =====================
|
| 120 |
+
# 3 括号处理
|
| 121 |
+
# =====================
|
| 122 |
+
|
| 123 |
+
def expand_name(name):
|
| 124 |
+
|
| 125 |
+
name = str(name).strip()
|
| 126 |
+
|
| 127 |
+
m = re.match(r"(.+?)((.+?))", name)
|
| 128 |
+
|
| 129 |
+
if m:
|
| 130 |
+
|
| 131 |
+
outside = m.group(1).strip()
|
| 132 |
+
inside = m.group(2).strip()
|
| 133 |
+
|
| 134 |
+
return {outside, inside}
|
| 135 |
+
|
| 136 |
+
else:
|
| 137 |
+
|
| 138 |
+
return {name}
|
| 139 |
+
|
| 140 |
+
# =====================
|
| 141 |
+
# 4 构建药典名称集合
|
| 142 |
+
# =====================
|
| 143 |
+
|
| 144 |
+
pharma_names = set()
|
| 145 |
+
|
| 146 |
+
for n in pharma_df["cn"]:
|
| 147 |
+
|
| 148 |
+
expanded = expand_name(n)
|
| 149 |
+
|
| 150 |
+
pharma_names.update(expanded)
|
| 151 |
+
|
| 152 |
+
print("Expanded pharmacopoeia names:", len(pharma_names))
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# =====================
|
| 156 |
+
# 5 匹配
|
| 157 |
+
# =====================
|
| 158 |
+
|
| 159 |
+
matched_rows = []
|
| 160 |
+
unmatched_entries = []
|
| 161 |
+
|
| 162 |
+
for _, row in pharma_df.iterrows():
|
| 163 |
+
|
| 164 |
+
pharma_raw = str(row["cn"]).strip()
|
| 165 |
+
|
| 166 |
+
candidates = expand_name(pharma_raw)
|
| 167 |
+
|
| 168 |
+
matched = False
|
| 169 |
+
|
| 170 |
+
for name in candidates:
|
| 171 |
+
|
| 172 |
+
# 直接匹配
|
| 173 |
+
if name in kg_names:
|
| 174 |
+
|
| 175 |
+
kg_row = pred_df[pred_df["name"] == name].iloc[0]
|
| 176 |
+
|
| 177 |
+
matched_rows.append({
|
| 178 |
+
"pharma_name": pharma_raw,
|
| 179 |
+
"kg_name": name,
|
| 180 |
+
"pred_flavor": kg_row["pred_dunhuang_flavor"]
|
| 181 |
+
})
|
| 182 |
+
|
| 183 |
+
matched = True
|
| 184 |
+
break
|
| 185 |
+
|
| 186 |
+
# alias匹配
|
| 187 |
+
if name in alias_map:
|
| 188 |
+
|
| 189 |
+
for kg_name in alias_map[name]:
|
| 190 |
+
|
| 191 |
+
if kg_name in kg_names:
|
| 192 |
+
|
| 193 |
+
kg_row = pred_df[pred_df["name"] == kg_name].iloc[0]
|
| 194 |
+
|
| 195 |
+
matched_rows.append({
|
| 196 |
+
"pharma_name": pharma_raw,
|
| 197 |
+
"kg_name": kg_name,
|
| 198 |
+
"pred_flavor": kg_row["pred_dunhuang_flavor"]
|
| 199 |
+
})
|
| 200 |
+
|
| 201 |
+
matched = True
|
| 202 |
+
break
|
| 203 |
+
|
| 204 |
+
if matched:
|
| 205 |
+
break
|
| 206 |
+
|
| 207 |
+
if not matched:
|
| 208 |
+
unmatched_entries.append(pharma_raw)
|
| 209 |
+
|
| 210 |
+
with open(UNMATCHED_PATH, "w", encoding="utf-8") as f:
|
| 211 |
+
|
| 212 |
+
for name in unmatched_entries:
|
| 213 |
+
f.write(name + "\n")
|
| 214 |
+
|
| 215 |
+
# =====================
|
| 216 |
+
# 6 生成结果
|
| 217 |
+
# =====================
|
| 218 |
+
|
| 219 |
+
matched_df = pd.DataFrame(matched_rows)
|
| 220 |
+
|
| 221 |
+
matched_df = matched_df.drop_duplicates()
|
| 222 |
+
|
| 223 |
+
print("Matched herbs:", len(matched_df))
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
# =====================
|
| 227 |
+
# 保存未匹配
|
| 228 |
+
# =====================
|
| 229 |
+
|
| 230 |
+
with open(UNMATCHED_PATH, "w", encoding="utf-8") as f:
|
| 231 |
+
|
| 232 |
+
for name in unmatched_entries:
|
| 233 |
+
f.write(name + "\n")
|
| 234 |
+
|
| 235 |
+
print("Unmatched list saved to:", UNMATCHED_PATH)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
# =====================
|
| 239 |
+
# 8 保存结果
|
| 240 |
+
# =====================
|
| 241 |
+
|
| 242 |
+
matched_df.to_csv(
|
| 243 |
+
OUTPUT_PATH,
|
| 244 |
+
index=False,
|
| 245 |
+
encoding="utf-8-sig"
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
print("Saved to:", OUTPUT_PATH)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
# =====================
|
| 252 |
+
# 9 统计信息
|
| 253 |
+
# =====================
|
| 254 |
+
|
| 255 |
+
print("\n===== Summary =====")
|
| 256 |
+
|
| 257 |
+
print("Pharmacopoeia herbs:", len(pharma_df))
|
| 258 |
+
print("Expanded names:", len(pharma_names))
|
| 259 |
+
print("Matched:", len(matched_df))
|
| 260 |
+
print("Unmatched:", len(unmatched_entries))
|
| 261 |
+
|
| 262 |
+
match_rate = len(matched_df) / len(pharma_df)
|
| 263 |
+
|
| 264 |
+
print("Match rate:", round(match_rate * 100, 2), "%")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/embedding/kg/predict_flavor_knn.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
from sklearn.neighbors import KNeighborsClassifier
|
| 5 |
+
|
| 6 |
+
# =========================
|
| 7 |
+
# 路径
|
| 8 |
+
# =========================
|
| 9 |
+
|
| 10 |
+
EMB_PATH = "/public/home/vitami/embedding/kg/entity_embeddings.pt"
|
| 11 |
+
ENTITY_PATH = "/public/home/vitami/embedding/kg/entity_names.tsv"
|
| 12 |
+
SEED_PATH = "/public/home/vitami/embedding/kg/seed2.csv"
|
| 13 |
+
|
| 14 |
+
OUTPUT_PATH = "/public/home/vitami/embedding/kg/herb_flavor_knn_prediction.csv"
|
| 15 |
+
|
| 16 |
+
# =========================
|
| 17 |
+
# 1 读取 embedding
|
| 18 |
+
# =========================
|
| 19 |
+
|
| 20 |
+
print("Loading embeddings...")
|
| 21 |
+
|
| 22 |
+
emb = torch.load(EMB_PATH, map_location="cpu")
|
| 23 |
+
|
| 24 |
+
# RotatE 是 complex embedding
|
| 25 |
+
if torch.is_complex(emb):
|
| 26 |
+
print("Complex embedding detected, converting...")
|
| 27 |
+
emb = torch.cat([emb.real, emb.imag], dim=1)
|
| 28 |
+
|
| 29 |
+
emb = emb.numpy()
|
| 30 |
+
|
| 31 |
+
print("Embedding shape:", emb.shape)
|
| 32 |
+
|
| 33 |
+
# =========================
|
| 34 |
+
# 2 读取实体表
|
| 35 |
+
# =========================
|
| 36 |
+
|
| 37 |
+
print("Loading entity table...")
|
| 38 |
+
|
| 39 |
+
entity_df = pd.read_csv(
|
| 40 |
+
ENTITY_PATH,
|
| 41 |
+
sep="\t"
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
entity_df["emb_index"] = entity_df.index
|
| 45 |
+
|
| 46 |
+
# 只保留 herb
|
| 47 |
+
herb_df = entity_df[entity_df["type"] == "herb"].copy()
|
| 48 |
+
|
| 49 |
+
print("Total herbs:", len(herb_df))
|
| 50 |
+
|
| 51 |
+
# =========================
|
| 52 |
+
# 3 读取 seed
|
| 53 |
+
# =========================
|
| 54 |
+
|
| 55 |
+
print("Loading seed labels...")
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
seed_df = pd.read_csv(SEED_PATH, encoding="utf-8-sig")
|
| 59 |
+
except:
|
| 60 |
+
seed_df = pd.read_csv(SEED_PATH, encoding="gbk")
|
| 61 |
+
|
| 62 |
+
print("Seed size:", len(seed_df))
|
| 63 |
+
print("Seed columns:", seed_df.columns)
|
| 64 |
+
|
| 65 |
+
# =========================
|
| 66 |
+
# 4 对齐 herb name
|
| 67 |
+
# =========================
|
| 68 |
+
|
| 69 |
+
seed_df = seed_df.merge(
|
| 70 |
+
herb_df,
|
| 71 |
+
left_on="herb",
|
| 72 |
+
right_on="name",
|
| 73 |
+
how="left"
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
missing = seed_df["emb_index"].isna().sum()
|
| 77 |
+
|
| 78 |
+
if missing > 0:
|
| 79 |
+
print("Warning: some seed herbs not found:", missing)
|
| 80 |
+
|
| 81 |
+
seed_df = seed_df.dropna(subset=["emb_index"])
|
| 82 |
+
|
| 83 |
+
# =========================
|
| 84 |
+
# 5 构建训练数据
|
| 85 |
+
# =========================
|
| 86 |
+
|
| 87 |
+
X_train = []
|
| 88 |
+
y_train = []
|
| 89 |
+
|
| 90 |
+
for _, row in seed_df.iterrows():
|
| 91 |
+
|
| 92 |
+
idx = int(row["emb_index"])
|
| 93 |
+
label = row["dunhuang_flavor"]
|
| 94 |
+
|
| 95 |
+
X_train.append(emb[idx])
|
| 96 |
+
y_train.append(label)
|
| 97 |
+
|
| 98 |
+
X_train = np.array(X_train)
|
| 99 |
+
y_train = np.array(y_train)
|
| 100 |
+
|
| 101 |
+
print("Training samples:", X_train.shape)
|
| 102 |
+
|
| 103 |
+
# =========================
|
| 104 |
+
# 6 训练 KNN
|
| 105 |
+
# =========================
|
| 106 |
+
|
| 107 |
+
print("Training KNN...")
|
| 108 |
+
|
| 109 |
+
knn = KNeighborsClassifier(
|
| 110 |
+
n_neighbors=5,
|
| 111 |
+
metric="cosine"
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
knn.fit(X_train, y_train)
|
| 115 |
+
|
| 116 |
+
print("KNN trained")
|
| 117 |
+
|
| 118 |
+
# =========================
|
| 119 |
+
# 7 预测全部 herb
|
| 120 |
+
# =========================
|
| 121 |
+
|
| 122 |
+
print("Predicting herbs...")
|
| 123 |
+
|
| 124 |
+
results = []
|
| 125 |
+
|
| 126 |
+
for _, row in herb_df.iterrows():
|
| 127 |
+
|
| 128 |
+
idx = int(row["emb_index"])
|
| 129 |
+
vec = emb[idx].reshape(1, -1)
|
| 130 |
+
|
| 131 |
+
pred = knn.predict(vec)[0]
|
| 132 |
+
|
| 133 |
+
results.append({
|
| 134 |
+
"entity": row["entity"],
|
| 135 |
+
"name": row["name"],
|
| 136 |
+
"pred_dunhuang_flavor": pred
|
| 137 |
+
})
|
| 138 |
+
|
| 139 |
+
result_df = pd.DataFrame(results)
|
| 140 |
+
|
| 141 |
+
# =========================
|
| 142 |
+
# 8 保存
|
| 143 |
+
# =========================
|
| 144 |
+
|
| 145 |
+
result_df.to_csv(
|
| 146 |
+
OUTPUT_PATH,
|
| 147 |
+
index=False,
|
| 148 |
+
encoding="utf-8-sig"
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
print("Prediction finished")
|
| 152 |
+
print("Saved to:", OUTPUT_PATH)
|
recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/embedding/kg/train_kg_embedding.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from pykeen.pipeline import pipeline
|
| 5 |
+
from pykeen.triples import TriplesFactory
|
| 6 |
+
|
| 7 |
+
# =========================
|
| 8 |
+
# 文件路径
|
| 9 |
+
# =========================
|
| 10 |
+
|
| 11 |
+
TRIPLE_FILE = "/root/private_data/embedding/kg/tcmkg_triples.tsv"
|
| 12 |
+
MODEL_DIR = "/root/private_data/embedding/kg/kg_model"
|
| 13 |
+
|
| 14 |
+
print("Loading triples...")
|
| 15 |
+
|
| 16 |
+
triples = pd.read_csv(
|
| 17 |
+
TRIPLE_FILE,
|
| 18 |
+
sep="\t",
|
| 19 |
+
header=None,
|
| 20 |
+
names=["head", "relation", "tail"],
|
| 21 |
+
dtype=str
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
print("Triples:", len(triples))
|
| 25 |
+
|
| 26 |
+
# =========================
|
| 27 |
+
# 转换为 PyKEEN triples
|
| 28 |
+
# =========================
|
| 29 |
+
|
| 30 |
+
triples_array = triples.values
|
| 31 |
+
|
| 32 |
+
tf = TriplesFactory.from_labeled_triples(triples_array)
|
| 33 |
+
|
| 34 |
+
# 自动划分训练测试
|
| 35 |
+
training, testing = tf.split([0.9, 0.1])
|
| 36 |
+
|
| 37 |
+
print("Start training KG embedding...")
|
| 38 |
+
|
| 39 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 40 |
+
|
| 41 |
+
print("Using device:", device)
|
| 42 |
+
|
| 43 |
+
# =========================
|
| 44 |
+
# 训练
|
| 45 |
+
# =========================
|
| 46 |
+
|
| 47 |
+
result = pipeline(
|
| 48 |
+
training=training,
|
| 49 |
+
testing=testing,
|
| 50 |
+
|
| 51 |
+
model="RotatE",
|
| 52 |
+
|
| 53 |
+
model_kwargs=dict(
|
| 54 |
+
embedding_dim=200
|
| 55 |
+
),
|
| 56 |
+
|
| 57 |
+
training_kwargs=dict(
|
| 58 |
+
num_epochs=50,
|
| 59 |
+
batch_size=256,
|
| 60 |
+
),
|
| 61 |
+
|
| 62 |
+
optimizer="Adam",
|
| 63 |
+
|
| 64 |
+
optimizer_kwargs=dict(
|
| 65 |
+
lr=1e-3
|
| 66 |
+
),
|
| 67 |
+
|
| 68 |
+
negative_sampler="basic",
|
| 69 |
+
|
| 70 |
+
device=device,
|
| 71 |
+
|
| 72 |
+
random_seed=42,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
print("Training finished")
|
| 76 |
+
|
| 77 |
+
# =========================
|
| 78 |
+
# 保存模型
|
| 79 |
+
# =========================
|
| 80 |
+
|
| 81 |
+
result.save_to_directory(MODEL_DIR)
|
| 82 |
+
|
| 83 |
+
print("Model saved")
|
| 84 |
+
|
| 85 |
+
# =========================
|
| 86 |
+
# 保存实体向量
|
| 87 |
+
# =========================
|
| 88 |
+
|
| 89 |
+
entity_embeddings = result.model.entity_representations[0]().detach().cpu()
|
| 90 |
+
|
| 91 |
+
torch.save(
|
| 92 |
+
entity_embeddings,
|
| 93 |
+
"/root/private_data/embedding/kg/entity_embeddings.pt"
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
print("Entity embeddings saved")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/embedding/text/embed_herb_text.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoTokenizer, AutoModel
|
| 2 |
+
import torch
|
| 3 |
+
import numpy as np
|
| 4 |
+
from tqdm import tqdm
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
# ================== 路径配置 ==================
|
| 8 |
+
# 本地模型路径(已提前下载)
|
| 9 |
+
MODEL_PATH = Path("herberta_seq_512_V2")
|
| 10 |
+
|
| 11 |
+
# 输入文本(相对路径)
|
| 12 |
+
INPUT_TXT = Path("processed_文本1.txt")
|
| 13 |
+
|
| 14 |
+
# 输出目录
|
| 15 |
+
OUTPUT_DIR = Path("output1")
|
| 16 |
+
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 17 |
+
|
| 18 |
+
EMB_PATH = OUTPUT_DIR / "herb_embeddings.npy"
|
| 19 |
+
NAME_PATH = OUTPUT_DIR / "herb_names.txt"
|
| 20 |
+
|
| 21 |
+
# ================== 设备 ==================
|
| 22 |
+
# ⚠️ 显式使用国产 AI 卡的 cuda:0
|
| 23 |
+
device = torch.device("cuda:0")
|
| 24 |
+
print(f"📟 使用设备: {device}")
|
| 25 |
+
print(f"🧩 设备名称: {torch.cuda.get_device_name(0)}")
|
| 26 |
+
|
| 27 |
+
# ================== 模型 ==================
|
| 28 |
+
print("🔄 加载 tokenizer 和 model ...")
|
| 29 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
|
| 30 |
+
|
| 31 |
+
# ⚠️ 不使用 pooler,只做 encoder 推理
|
| 32 |
+
model = AutoModel.from_pretrained(
|
| 33 |
+
MODEL_PATH,
|
| 34 |
+
add_pooling_layer=False
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
model.to(device)
|
| 38 |
+
model.eval()
|
| 39 |
+
|
| 40 |
+
# ================== 读取文本 ==================
|
| 41 |
+
herb_names = []
|
| 42 |
+
texts = []
|
| 43 |
+
|
| 44 |
+
with INPUT_TXT.open("r", encoding="utf-8") as f:
|
| 45 |
+
for idx, line in enumerate(f):
|
| 46 |
+
line = line.strip()
|
| 47 |
+
if not line:
|
| 48 |
+
continue
|
| 49 |
+
|
| 50 |
+
# 情况 1:药名:功效文本
|
| 51 |
+
if ":" in line:
|
| 52 |
+
name, text = line.split(":", 1)
|
| 53 |
+
# 情况 2:只有文本
|
| 54 |
+
else:
|
| 55 |
+
name = f"herb_{idx}"
|
| 56 |
+
text = line
|
| 57 |
+
|
| 58 |
+
herb_names.append(name)
|
| 59 |
+
texts.append(text)
|
| 60 |
+
|
| 61 |
+
print(f"📄 读取到 {len(texts)} 条中药文本")
|
| 62 |
+
|
| 63 |
+
# ================== 生成 embedding ==================
|
| 64 |
+
embeddings = []
|
| 65 |
+
|
| 66 |
+
with torch.no_grad():
|
| 67 |
+
for text in tqdm(texts, desc="🧠 Embedding herbs (K500SM_AI)"):
|
| 68 |
+
inputs = tokenizer(
|
| 69 |
+
text,
|
| 70 |
+
return_tensors="pt",
|
| 71 |
+
truncation=True,
|
| 72 |
+
max_length=512,
|
| 73 |
+
padding="max_length"
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 77 |
+
outputs = model(**inputs)
|
| 78 |
+
|
| 79 |
+
# ✅ 使用 CLS token 的 hidden state
|
| 80 |
+
vec = outputs.last_hidden_state[:, 0, :]
|
| 81 |
+
embeddings.append(vec.detach().cpu().numpy()[0])
|
| 82 |
+
|
| 83 |
+
embeddings = np.vstack(embeddings)
|
| 84 |
+
|
| 85 |
+
# ================== 保存 ==================
|
| 86 |
+
np.save(EMB_PATH, embeddings)
|
| 87 |
+
|
| 88 |
+
with NAME_PATH.open("w", encoding="utf-8") as f:
|
| 89 |
+
for name in herb_names:
|
| 90 |
+
f.write(name + "\n")
|
| 91 |
+
|
| 92 |
+
print("✅ 嵌入完成")
|
| 93 |
+
print(f"📐 向量形状: {embeddings.shape}")
|
| 94 |
+
print(f"💾 向量保存路径: {EMB_PATH.resolve()}")
|
| 95 |
+
print(f"📄 名称保存路径: {NAME_PATH.resolve()}")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/模型/embedding/抓文本.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pdfplumber
|
| 2 |
+
import re
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
|
| 7 |
+
# ================= 路径配置 =================
|
| 8 |
+
pdf_dir = Path(r"C:\Users\Lenovo\Desktop\PDF合并")
|
| 9 |
+
start_page = 51
|
| 10 |
+
|
| 11 |
+
md_output = Path(r"D:\ObsidianVault\药典2025_切割汇总.md")
|
| 12 |
+
excel_path = Path(r"D:\2\111数据库\文本.xlsx")
|
| 13 |
+
|
| 14 |
+
# ================= 工具函数 =================
|
| 15 |
+
def normalize_name(name: str) -> str:
|
| 16 |
+
name = re.sub(r"(.*?)|\(.*?\)", "", name)
|
| 17 |
+
name = name.replace("·", "")
|
| 18 |
+
return name.strip()
|
| 19 |
+
|
| 20 |
+
def is_chinese_name(line):
|
| 21 |
+
return 2 <= len(line) <= 12 and re.fullmatch(r"[一-龥·()()]+", line)
|
| 22 |
+
|
| 23 |
+
def is_pinyin(line):
|
| 24 |
+
return re.fullmatch(r"[A-Za-z\u00C0-\u017F\s\-'.]+", line) is not None
|
| 25 |
+
|
| 26 |
+
def is_latin(line):
|
| 27 |
+
# ✅ 支持数字开头
|
| 28 |
+
return re.fullmatch(r"[0-9A-Z\s\-]+", line) is not None
|
| 29 |
+
|
| 30 |
+
def clean_text(line):
|
| 31 |
+
line = re.sub(r"\?{2,}", "%", line)
|
| 32 |
+
line = re.sub(r"\s+", " ", line)
|
| 33 |
+
return line.strip()
|
| 34 |
+
|
| 35 |
+
# ================= 核心:稳定双栏重排 =================
|
| 36 |
+
def extract_lines_strict_two_column(words, page_width, y_tol=3):
|
| 37 |
+
"""
|
| 38 |
+
1. 先按 y 聚成物理行
|
| 39 |
+
2. 每行内部按 x 排序
|
| 40 |
+
3. 按页面中线硬分左右栏
|
| 41 |
+
4. 输出顺序:左栏全文 → 右栏全文
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
mid_x = page_width / 2
|
| 45 |
+
|
| 46 |
+
rows = defaultdict(list)
|
| 47 |
+
for w in words:
|
| 48 |
+
key = round(w["top"] / y_tol)
|
| 49 |
+
rows[key].append(w)
|
| 50 |
+
|
| 51 |
+
left_lines = []
|
| 52 |
+
right_lines = []
|
| 53 |
+
|
| 54 |
+
for _, row in sorted(rows.items()):
|
| 55 |
+
row = sorted(row, key=lambda w: w["x0"])
|
| 56 |
+
|
| 57 |
+
left_words = [w for w in row if w["x0"] + w["width"] / 2 < mid_x]
|
| 58 |
+
right_words = [w for w in row if w["x0"] + w["width"] / 2 >= mid_x]
|
| 59 |
+
|
| 60 |
+
if left_words:
|
| 61 |
+
left_lines.append("".join(w["text"] for w in left_words))
|
| 62 |
+
if right_words:
|
| 63 |
+
right_lines.append("".join(w["text"] for w in right_words))
|
| 64 |
+
|
| 65 |
+
return left_lines + right_lines
|
| 66 |
+
|
| 67 |
+
# ================= 主流程 =================
|
| 68 |
+
all_sections = []
|
| 69 |
+
|
| 70 |
+
current = {
|
| 71 |
+
"name": "__PREFACE__",
|
| 72 |
+
"display": "__PREFACE__",
|
| 73 |
+
"content": []
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
pdf_files = sorted(
|
| 77 |
+
pdf_dir.glob("PDF合并_*.pdf"),
|
| 78 |
+
key=lambda x: int(re.search(r"_(\d+)\.pdf", x.name).group(1))
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
for pdf_path in pdf_files:
|
| 82 |
+
page_no = int(re.search(r"_(\d+)\.pdf", pdf_path.name).group(1))
|
| 83 |
+
if page_no < start_page:
|
| 84 |
+
continue
|
| 85 |
+
|
| 86 |
+
print(f"▶ 处理 {pdf_path.name}")
|
| 87 |
+
|
| 88 |
+
with pdfplumber.open(pdf_path) as pdf:
|
| 89 |
+
page = pdf.pages[0]
|
| 90 |
+
height = page.height
|
| 91 |
+
width = page.width
|
| 92 |
+
words = page.extract_words(use_text_flow=False)
|
| 93 |
+
|
| 94 |
+
# 过滤页眉 / 页脚(保持你当前稳定设置)
|
| 95 |
+
words = [
|
| 96 |
+
w for w in words
|
| 97 |
+
if height * 0.06 < w["top"] < height * 0.97
|
| 98 |
+
]
|
| 99 |
+
if not words:
|
| 100 |
+
continue
|
| 101 |
+
|
| 102 |
+
lines = extract_lines_strict_two_column(words, width)
|
| 103 |
+
lines = [clean_text(l) for l in lines if l.strip()]
|
| 104 |
+
|
| 105 |
+
i = 0
|
| 106 |
+
while i < len(lines) - 2:
|
| 107 |
+
l0, l1, l2 = lines[i], lines[i+1], lines[i+2]
|
| 108 |
+
|
| 109 |
+
if is_chinese_name(l0) and is_pinyin(l1) and is_latin(l2):
|
| 110 |
+
if current["name"] != "__PREFACE__":
|
| 111 |
+
all_sections.append(current)
|
| 112 |
+
|
| 113 |
+
current = {
|
| 114 |
+
"name": normalize_name(l0),
|
| 115 |
+
"display": l0,
|
| 116 |
+
"content": [l0, l1, l2]
|
| 117 |
+
}
|
| 118 |
+
i += 3
|
| 119 |
+
else:
|
| 120 |
+
current["content"].append(lines[i])
|
| 121 |
+
i += 1
|
| 122 |
+
|
| 123 |
+
for tail in lines[i:]:
|
| 124 |
+
current["content"].append(tail)
|
| 125 |
+
|
| 126 |
+
if current["name"] != "__PREFACE__":
|
| 127 |
+
all_sections.append(current)
|
| 128 |
+
|
| 129 |
+
# ================= 输出 Markdown =================
|
| 130 |
+
with open(md_output, "w", encoding="utf-8") as f:
|
| 131 |
+
for sec in all_sections:
|
| 132 |
+
f.write(f"## {sec['display']}\n\n")
|
| 133 |
+
for l in sec["content"]:
|
| 134 |
+
f.write(l + "\n")
|
| 135 |
+
f.write("\n---\n\n")
|
| 136 |
+
|
| 137 |
+
print("✅ Markdown 输出完成")
|
| 138 |
+
|
| 139 |
+
# ================= 写入 Excel =================
|
| 140 |
+
df = pd.read_excel(excel_path)
|
| 141 |
+
|
| 142 |
+
def extract_function(lines):
|
| 143 |
+
text = "\n".join(lines)
|
| 144 |
+
m = re.search(r"【功能与主治】(.+?)(【|$)", text, re.S)
|
| 145 |
+
return m.group(1).strip() if m else ""
|
| 146 |
+
|
| 147 |
+
func_map = {
|
| 148 |
+
sec["name"]: extract_function(sec["content"])
|
| 149 |
+
for sec in all_sections
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
df.iloc[:, 0] = df.iloc[:, 0].astype(str).map(normalize_name)
|
| 153 |
+
df.iloc[:, 1] = df.iloc[:, 0].map(func_map).fillna("")
|
| 154 |
+
df.to_excel(excel_path, index=False)
|
| 155 |
+
|
| 156 |
+
print("✅ Excel 写入完成")
|
recovery_20261030/zip_preserved_scripts/111药精图模型/模型/药典对照.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
def normalize_pinyin(pinyin_str):
|
| 6 |
+
# 删除标点符号和数字,转换为小写
|
| 7 |
+
cleaned = re.sub(r'[^\w\s]|\d', '', str(pinyin_str)).lower()
|
| 8 |
+
return cleaned
|
| 9 |
+
|
| 10 |
+
def get_names_from_text(text):
|
| 11 |
+
# 返回完整名称和括号内外的名称列表
|
| 12 |
+
names = [text]
|
| 13 |
+
# 匹配括号内的内容
|
| 14 |
+
bracket_pattern = r'[((](.*?)[))]'
|
| 15 |
+
matches = re.findall(bracket_pattern, text)
|
| 16 |
+
if matches:
|
| 17 |
+
# 添加括号内的内容
|
| 18 |
+
names.extend(matches)
|
| 19 |
+
# 添加去除括号及其内容后的文本
|
| 20 |
+
clean_text = re.sub(bracket_pattern, '', text).strip()
|
| 21 |
+
if clean_text:
|
| 22 |
+
names.append(clean_text)
|
| 23 |
+
return names
|
| 24 |
+
|
| 25 |
+
def get_database_name(filename):
|
| 26 |
+
return filename.split('_')[0]
|
| 27 |
+
|
| 28 |
+
def print_columns(df, db_name):
|
| 29 |
+
print(f"\n{db_name} 数据库的列名:")
|
| 30 |
+
for i, col in enumerate(df.columns):
|
| 31 |
+
print(f"{i}: {col}")
|
| 32 |
+
|
| 33 |
+
def match_names(tcm_name, tcm_pinyin, db_row, cn_col_name, py_col_name):
|
| 34 |
+
# 获取所有可能的中文名称
|
| 35 |
+
chinese_names = get_names_from_text(tcm_name)
|
| 36 |
+
|
| 37 |
+
# 获取数据库中的所有拼音(按、分割)
|
| 38 |
+
db_pinyins = str(db_row[py_col_name]).split('、')
|
| 39 |
+
|
| 40 |
+
# 中文名匹配
|
| 41 |
+
cn_match = any(name in str(db_row[cn_col_name]) for name in chinese_names)
|
| 42 |
+
|
| 43 |
+
# 拼音匹配
|
| 44 |
+
py_match = False
|
| 45 |
+
for db_pinyin in db_pinyins:
|
| 46 |
+
# 检查数据库中的拼音是否包含空格
|
| 47 |
+
has_space = ' ' in db_pinyin
|
| 48 |
+
|
| 49 |
+
# 标准化处理拼音
|
| 50 |
+
if has_space:
|
| 51 |
+
# 如果数据库拼音包含空格,保持空格但标准化其他部分
|
| 52 |
+
db_pinyin_normalized = normalize_pinyin(db_pinyin)
|
| 53 |
+
tcm_pinyin_normalized = normalize_pinyin(tcm_pinyin)
|
| 54 |
+
else:
|
| 55 |
+
# 如果数据库拼音不包含空格,删除所有空格
|
| 56 |
+
db_pinyin_normalized = normalize_pinyin(db_pinyin).replace(' ', '')
|
| 57 |
+
tcm_pinyin_normalized = normalize_pinyin(tcm_pinyin).replace(' ', '')
|
| 58 |
+
|
| 59 |
+
# 如果任何一个拼音匹配,则认为是匹配的
|
| 60 |
+
if tcm_pinyin_normalized in db_pinyin_normalized:
|
| 61 |
+
py_match = True
|
| 62 |
+
break
|
| 63 |
+
|
| 64 |
+
return cn_match or py_match
|
| 65 |
+
|
| 66 |
+
def get_compound_info(tcm_df, db_files):
|
| 67 |
+
# 要提取的化合物信息列
|
| 68 |
+
compound_cols = ['pubchemcid', 'iupacname', 'name', 'molecularformula',
|
| 69 |
+
'smiles', 'averageweight', 'inchi', 'inchikey', 'cas']
|
| 70 |
+
|
| 71 |
+
# 创建结果DataFrame
|
| 72 |
+
result_df = pd.DataFrame()
|
| 73 |
+
|
| 74 |
+
# 遍历每个数据库文件
|
| 75 |
+
for db_file in db_files:
|
| 76 |
+
db_name = get_database_name(os.path.basename(db_file))
|
| 77 |
+
print(f"\n正在处理 {db_name} 数据库...")
|
| 78 |
+
|
| 79 |
+
# 读取数据库文件
|
| 80 |
+
db_df = pd.read_excel(db_file)
|
| 81 |
+
print_columns(db_df, db_name)
|
| 82 |
+
|
| 83 |
+
# 获取用户输入
|
| 84 |
+
cn_col = input(f"请输入{db_name}数据库中表示中文名的列序号: ")
|
| 85 |
+
py_col = input(f"请输入{db_name}数据库中表示拼音名的列序号: ")
|
| 86 |
+
|
| 87 |
+
# 获取列名
|
| 88 |
+
cn_col_name = db_df.columns[int(cn_col)]
|
| 89 |
+
py_col_name = db_df.columns[int(py_col)]
|
| 90 |
+
|
| 91 |
+
# 匹配过程
|
| 92 |
+
matched_rows = pd.DataFrame()
|
| 93 |
+
for _, tcm_row in tcm_df.iterrows():
|
| 94 |
+
# 使用改进的匹配函数
|
| 95 |
+
mask = db_df.apply(
|
| 96 |
+
lambda row: match_names(
|
| 97 |
+
tcm_row['cn'],
|
| 98 |
+
tcm_row['pinyin'],
|
| 99 |
+
row,
|
| 100 |
+
cn_col_name,
|
| 101 |
+
py_col_name
|
| 102 |
+
),
|
| 103 |
+
axis=1
|
| 104 |
+
)
|
| 105 |
+
matched = db_df[mask]
|
| 106 |
+
|
| 107 |
+
if not matched.empty:
|
| 108 |
+
# 只保留需要的列
|
| 109 |
+
available_cols = [col for col in compound_cols if col in matched.columns]
|
| 110 |
+
matched = matched[available_cols]
|
| 111 |
+
# 添加来源数据库标记
|
| 112 |
+
matched['source_database'] = db_name
|
| 113 |
+
# 添加匹配的中药名
|
| 114 |
+
matched['matched_herb'] = tcm_row['cn']
|
| 115 |
+
matched_rows = pd.concat([matched_rows, matched])
|
| 116 |
+
|
| 117 |
+
# 添加到结果中
|
| 118 |
+
result_df = pd.concat([result_df, matched_rows])
|
| 119 |
+
|
| 120 |
+
return result_df
|
| 121 |
+
|
| 122 |
+
def main():
|
| 123 |
+
# 读取药典表格
|
| 124 |
+
tcm_df = pd.read_excel(r"D:\2\111数据库\药典.xlsx")
|
| 125 |
+
|
| 126 |
+
# 数据库文件路径列表
|
| 127 |
+
db_files = [
|
| 128 |
+
r"D:\2\111数据库\汇总\BATMAN\BATMAN-TCM_Info_汇总_with_herbid_with_cid.xlsx",
|
| 129 |
+
r"D:\2\111数据库\汇总\DCABM\DCABM-TCM_Info_汇总_with_herbid_with_cid.xlsx",
|
| 130 |
+
r"D:\2\111数据库\汇总\ETCM2\ETCM2_Info_汇总_with_herbid_with_cid.xlsx",
|
| 131 |
+
r"D:\2\111数据库\汇总\HERB2\HERB2_Info_汇总_with_herbid_with_cid.xlsx",
|
| 132 |
+
r"D:\2\111数据库\汇总\SymMap\SymMap_Info_汇总_with_herbid_with_cid.xlsx",
|
| 133 |
+
r"D:\2\111数据库\汇总\TCMIO\TCMIO_Info_汇总_with_herbid_with_cid.xlsx",
|
| 134 |
+
r"D:\2\111数据库\汇总\TM-MC\TM-MC_Info_汇总_with_herbid_with_cid.xlsx"
|
| 135 |
+
]
|
| 136 |
+
|
| 137 |
+
# 获取化合物信息
|
| 138 |
+
result_df = get_compound_info(tcm_df, db_files)
|
| 139 |
+
|
| 140 |
+
# 保存结果
|
| 141 |
+
output_path = r"D:\2\111数据库\化合物信息汇总.csv"
|
| 142 |
+
result_df.to_csv(output_path, index=False, encoding='utf-8')
|
| 143 |
+
print(f"\n处理完成!结果已保存到:{output_path}")
|
| 144 |
+
print(f"共找到 {len(result_df)} 条记录")
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
main()
|