Download presentation/insert_overall_mean_coverage_slides.py from JX-Lab/QQCM: direct link, hf CLI and curl.
- Browser
- Download file 16.7 kB
-
https://huggingface.co/datasets/JX-Lab/QQCM/resolve/main/presentation/insert_overall_mean_coverage_slides.py
- Command line
-
hf download hf://datasets/JX-Lab/QQCM/presentation/insert_overall_mean_coverage_slides.py
-
curl -L -o insert_overall_mean_coverage_slides.py https://huggingface.co/datasets/JX-Lab/QQCM/resolve/main/presentation/insert_overall_mean_coverage_slides.py
16.7 kB
| #!/usr/bin/env python3 | |
| from __future__ import annotations | |
| import copy | |
| import csv | |
| import re | |
| import zipfile | |
| import xml.etree.ElementTree as ET | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Iterable | |
| ROOT = Path(__file__).resolve().parents[1] | |
| PPT_PATH = ROOT / "清窍聪明汤.pptx" | |
| OVERALL_SUMMARY = ROOT / "re" / "MS" / "idrug" / "omc" / "formula_indication_summary.csv" | |
| TOPK_SUMMARY = ROOT / "re" / "MS" / "idrug" / "topk" / "formula_indication_summary.csv" | |
| A_NS = "http://schemas.openxmlformats.org/drawingml/2006/main" | |
| P_NS = "http://schemas.openxmlformats.org/presentationml/2006/main" | |
| R_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" | |
| REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships" | |
| CT_NS = "http://schemas.openxmlformats.org/package/2006/content-types" | |
| NS = {"a": A_NS, "p": P_NS, "r": R_NS} | |
| ET.register_namespace("a", A_NS) | |
| ET.register_namespace("p", P_NS) | |
| ET.register_namespace("r", R_NS) | |
| def qn(ns: str, tag: str) -> str: | |
| mapping = {"a": A_NS, "p": P_NS, "r": R_NS} | |
| return f"{{{mapping[ns]}}}{tag}" | |
| class TextSlideSpec: | |
| title: str | |
| paragraphs: list[str] | |
| font_size: int = 1500 | |
| title_font_size: int = 2200 | |
| class TableSlideSpec: | |
| title: str | |
| headers: list[str] | |
| rows: list[list[str]] | |
| body_font_size: int = 1650 | |
| header_font_size: int = 1700 | |
| row_height: int = 640000 | |
| col_widths: list[int] | None = None | |
| title_font_size: int = 2200 | |
| def load_csv_rows(path: Path) -> list[dict[str, str]]: | |
| with path.open("r", encoding="utf-8-sig", newline="") as handle: | |
| reader = csv.DictReader(handle) | |
| return [{(key or "").lstrip("\ufeff"): value or "" for key, value in row.items()} for row in reader] | |
| def short_disease_name(name: str) -> str: | |
| custom = { | |
| "沃尔夫-帕金森-怀特综合症": "WPW综合征", | |
| "增生性髓鞘病对疼痛不敏感": "增生性髓鞘病致痛觉缺失", | |
| "有或没有先兆的偏头痛,易感性,1": "偏头痛(有/无先兆)1", | |
| "人类免疫缺陷病毒 1 型,易感性": "HIV-1易感性", | |
| "疟疾,易感性": "疟疾易感性", | |
| "哮喘,易感性": "哮喘易感性", | |
| "高血压,必不可少": "原发性高血压", | |
| } | |
| return custom.get(name, name) | |
| def format_score(value: str | float, digits: int = 6) -> str: | |
| return f"{float(value):.{digits}f}" | |
| def format_percent(value: str | float, digits: int = 1) -> str: | |
| return f"{100 * float(value):.{digits}f}%" | |
| def clear_paragraphs(tx_body: ET.Element) -> None: | |
| for child in list(tx_body): | |
| if child.tag == qn("a", "p"): | |
| tx_body.remove(child) | |
| def make_paragraph(text: str, font_size: int, align: str = "l") -> ET.Element: | |
| paragraph = ET.Element(qn("a", "p")) | |
| p_pr = ET.SubElement(paragraph, qn("a", "pPr"), {"algn": align}) | |
| ln_spc = ET.SubElement(p_pr, qn("a", "lnSpc")) | |
| ET.SubElement(ln_spc, qn("a", "spcPct"), {"val": "108000"}) | |
| ET.SubElement(p_pr, qn("a", "buNone")) | |
| run = ET.SubElement(paragraph, qn("a", "r")) | |
| ET.SubElement(run, qn("a", "rPr"), {"lang": "zh-CN", "altLang": "en-US", "sz": str(font_size)}) | |
| ET.SubElement(run, qn("a", "t")).text = text | |
| ET.SubElement(paragraph, qn("a", "endParaRPr"), {"lang": "zh-CN", "altLang": "en-US", "sz": str(font_size)}) | |
| return paragraph | |
| def set_textbox_paragraphs(sp: ET.Element, paragraphs: Iterable[str], font_size: int, align: str = "l") -> None: | |
| tx_body = sp.find("p:txBody", NS) | |
| if tx_body is None: | |
| return | |
| clear_paragraphs(tx_body) | |
| for paragraph_text in paragraphs: | |
| tx_body.append(make_paragraph(paragraph_text, font_size=font_size, align=align)) | |
| def set_table_cell_text(tc: ET.Element, text: str, font_size: int, align: str = "ctr") -> None: | |
| tx_body = tc.find("a:txBody", NS) | |
| if tx_body is None: | |
| return | |
| clear_paragraphs(tx_body) | |
| tx_body.append(make_paragraph(text, font_size=font_size, align=align)) | |
| def rebuild_table(tbl: ET.Element, spec: TableSlideSpec) -> None: | |
| tbl_grid = tbl.find("a:tblGrid", NS) | |
| rows = tbl.findall("a:tr", NS) | |
| header_row_template = rows[0] | |
| body_row_template = rows[1] | |
| for child in list(tbl): | |
| if child.tag in {qn("a", "tblGrid"), qn("a", "tr")}: | |
| tbl.remove(child) | |
| new_grid = copy.deepcopy(tbl_grid) | |
| for child in list(new_grid): | |
| new_grid.remove(child) | |
| for width in spec.col_widths or []: | |
| ET.SubElement(new_grid, qn("a", "gridCol"), {"w": str(width)}) | |
| tbl.append(new_grid) | |
| header_row = copy.deepcopy(header_row_template) | |
| header_row.set("h", str(spec.row_height)) | |
| for cell, text in zip(header_row.findall("a:tc", NS), spec.headers): | |
| set_table_cell_text(cell, text, font_size=spec.header_font_size, align="ctr") | |
| tbl.append(header_row) | |
| for row_values in spec.rows: | |
| row = copy.deepcopy(body_row_template) | |
| row.set("h", str(spec.row_height)) | |
| for index, (cell, text) in enumerate(zip(row.findall("a:tc", NS), row_values)): | |
| align = "l" if index == 2 else "ctr" | |
| set_table_cell_text(cell, text, font_size=spec.body_font_size, align=align) | |
| tbl.append(row) | |
| def build_text_slide_xml(template_xml: bytes, spec: TextSlideSpec) -> bytes: | |
| root = ET.fromstring(template_xml) | |
| shapes = root.find("p:cSld/p:spTree", NS).findall("p:sp", NS) | |
| set_textbox_paragraphs(shapes[1], [spec.title], font_size=spec.title_font_size) | |
| set_textbox_paragraphs(shapes[2], spec.paragraphs, font_size=spec.font_size) | |
| return ET.tostring(root, encoding="utf-8", xml_declaration=True) | |
| def build_table_slide_xml(template_xml: bytes, spec: TableSlideSpec) -> bytes: | |
| root = ET.fromstring(template_xml) | |
| shapes = root.find("p:cSld/p:spTree", NS).findall("p:sp", NS) | |
| set_textbox_paragraphs(shapes[1], [spec.title], font_size=spec.title_font_size) | |
| tbl = root.find(".//a:tbl", NS) | |
| rebuild_table(tbl, spec) | |
| return ET.tostring(root, encoding="utf-8", xml_declaration=True) | |
| def update_slide_rel_notes_target(rel_xml: bytes, note_number: int) -> bytes: | |
| root = ET.fromstring(rel_xml) | |
| for rel in root.findall(f"{{{REL_NS}}}Relationship"): | |
| if rel.attrib.get("Type", "").endswith("/notesSlide"): | |
| rel.set("Target", f"../notesSlides/notesSlide{note_number}.xml") | |
| return ET.tostring(root, encoding="utf-8", xml_declaration=True) | |
| def update_note_rel_slide_target(rel_xml: bytes, slide_number: int) -> bytes: | |
| root = ET.fromstring(rel_xml) | |
| for rel in root.findall(f"{{{REL_NS}}}Relationship"): | |
| if rel.attrib.get("Type", "").endswith("/slide"): | |
| rel.set("Target", f"../slides/slide{slide_number}.xml") | |
| return ET.tostring(root, encoding="utf-8", xml_declaration=True) | |
| def find_row(rows: list[dict[str, str]], disease_id: str) -> dict[str, str]: | |
| for row in rows: | |
| if row["disease_id"] == disease_id: | |
| return row | |
| raise KeyError(f"Disease not found: {disease_id}") | |
| def build_specs() -> tuple[TableSlideSpec, TextSlideSpec]: | |
| overall_rows = load_csv_rows(OVERALL_SUMMARY) | |
| topk_rows = load_csv_rows(TOPK_SUMMARY) | |
| topk_rank = {row["disease_id"]: int(row["formula_rank"]) for row in topk_rows} | |
| top3 = overall_rows[:3] | |
| breast = find_row(overall_rows, "D114480") | |
| hypertension = find_row(overall_rows, "D145500") | |
| lung = find_row(overall_rows, "D211980") | |
| hiv = find_row(overall_rows, "D609423") | |
| table_rows = [ | |
| [ | |
| str(idx), | |
| row["disease_id"], | |
| short_disease_name(row["disease_name_zh"]), | |
| format_score(row["formula_primary_score"], 6), | |
| format_percent(row["support_ratio_ge_primary_threshold"], 1), | |
| ] | |
| for idx, row in enumerate(overall_rows[:5], start=1) | |
| ] | |
| table_spec = TableSlideSpec( | |
| title="基于MS+iDrug的overall mean coverage结果", | |
| headers=["排名", "疾病ID", "疾病名称", "均值×覆盖率", "覆盖比例"], | |
| rows=table_rows, | |
| col_widths=[900000, 1700000, 3900000, 2200000, 2278515], | |
| ) | |
| text_spec = TextSlideSpec( | |
| title="overall mean coverage结果解读", | |
| paragraphs=[ | |
| "1. overall mean coverage 指标使用全体化合物均值 × 覆盖比例(阈值 >= 1e-4)作为主分数,强调“平均信号强度 + 多成分覆盖度”的综合表现。", | |
| ( | |
| f"2. Top 3 仍为 {short_disease_name(top3[0]['disease_name_zh'])}、" | |
| f"{short_disease_name(top3[1]['disease_name_zh'])} 和 " | |
| f"{short_disease_name(top3[2]['disease_name_zh'])},对应覆盖化合物数分别为 " | |
| f"{top3[0]['support_count_ge_primary_threshold']}、" | |
| f"{top3[1]['support_count_ge_primary_threshold']} 和 " | |
| f"{top3[2]['support_count_ge_primary_threshold']} 个,占全部 MS 化合物的 " | |
| f"{format_percent(top3[0]['support_ratio_ge_primary_threshold'])}、" | |
| f"{format_percent(top3[1]['support_ratio_ge_primary_threshold'])} 和 " | |
| f"{format_percent(top3[2]['support_ratio_ge_primary_threshold'])}。" | |
| ), | |
| ( | |
| f"3. 与 top-k 排序相比,{short_disease_name(breast['disease_name_zh'])}由第 " | |
| f"{topk_rank[breast['disease_id']]} 位升至第 4 位," | |
| f"{short_disease_name(hypertension['disease_name_zh'])}由第 " | |
| f"{topk_rank[hypertension['disease_id']]} 位升至第 5 位," | |
| f"{short_disease_name(lung['disease_name_zh'])}由第 " | |
| f"{topk_rank[lung['disease_id']]} 位升至第 7 位,说明这些候选并非仅由少数峰值成分驱动。" | |
| ), | |
| ( | |
| f"4. {short_disease_name(hiv['disease_name_zh'])}从 top-k 的第 " | |
| f"{topk_rank[hiv['disease_id']]} 位降至这里的第 {hiv['formula_rank']} 位," | |
| f"主要原因是覆盖比例只有 {format_percent(hiv['support_ratio_ge_primary_threshold'])}," | |
| "明显低于前列候选的 30% 左右,提示其更依赖少数高分化合物。" | |
| ), | |
| "5. 因此,overall mean coverage 更适合作为 top-k 结果的稳健性补充;若某疾病在两种排序下都靠前,可优先进入后续人工筛选与文献验证。", | |
| ], | |
| ) | |
| return table_spec, text_spec | |
| def ensure_override(content_root: ET.Element, part_name: str, content_type: str) -> None: | |
| for override in content_root.findall(f"{{{CT_NS}}}Override"): | |
| if override.attrib.get("PartName") == part_name: | |
| return | |
| content_root.append( | |
| ET.Element( | |
| f"{{{CT_NS}}}Override", | |
| { | |
| "PartName": part_name, | |
| "ContentType": content_type, | |
| }, | |
| ) | |
| ) | |
| def insert_after_slide(ppt_path: Path) -> None: | |
| with zipfile.ZipFile(ppt_path) as source_zip: | |
| files = {name: source_zip.read(name) for name in source_zip.namelist()} | |
| if any("overall mean coverage结果".encode("utf-8") in data for name, data in files.items() if name.startswith("ppt/slides/slide")): | |
| raise SystemExit("overall mean coverage slides already exist; no changes made.") | |
| slide_numbers = sorted( | |
| int(match.group(1)) | |
| for name in files | |
| if (match := re.fullmatch(r"ppt/slides/slide(\d+)\.xml", name)) | |
| ) | |
| note_numbers = sorted( | |
| int(match.group(1)) | |
| for name in files | |
| if (match := re.fullmatch(r"ppt/notesSlides/notesSlide(\d+)\.xml", name)) | |
| ) | |
| new_slide_numbers = [max(slide_numbers) + 1, max(slide_numbers) + 2] | |
| new_note_numbers = [max(note_numbers) + 1, max(note_numbers) + 2] | |
| table_spec, text_spec = build_specs() | |
| table_template_xml = files["ppt/slides/slide14.xml"] | |
| text_template_xml = files["ppt/slides/slide15.xml"] | |
| table_slide_rel_template = files["ppt/slides/_rels/slide14.xml.rels"] | |
| text_slide_rel_template = files["ppt/slides/_rels/slide15.xml.rels"] | |
| table_note_xml = files["ppt/notesSlides/notesSlide14.xml"] | |
| text_note_xml = files["ppt/notesSlides/notesSlide15.xml"] | |
| table_note_rel_template = files["ppt/notesSlides/_rels/notesSlide14.xml.rels"] | |
| text_note_rel_template = files["ppt/notesSlides/_rels/notesSlide15.xml.rels"] | |
| files[f"ppt/slides/slide{new_slide_numbers[0]}.xml"] = build_table_slide_xml(table_template_xml, table_spec) | |
| files[f"ppt/slides/slide{new_slide_numbers[1]}.xml"] = build_text_slide_xml(text_template_xml, text_spec) | |
| files[f"ppt/slides/_rels/slide{new_slide_numbers[0]}.xml.rels"] = update_slide_rel_notes_target( | |
| table_slide_rel_template, new_note_numbers[0] | |
| ) | |
| files[f"ppt/slides/_rels/slide{new_slide_numbers[1]}.xml.rels"] = update_slide_rel_notes_target( | |
| text_slide_rel_template, new_note_numbers[1] | |
| ) | |
| files[f"ppt/notesSlides/notesSlide{new_note_numbers[0]}.xml"] = table_note_xml | |
| files[f"ppt/notesSlides/notesSlide{new_note_numbers[1]}.xml"] = text_note_xml | |
| files[f"ppt/notesSlides/_rels/notesSlide{new_note_numbers[0]}.xml.rels"] = update_note_rel_slide_target( | |
| table_note_rel_template, new_slide_numbers[0] | |
| ) | |
| files[f"ppt/notesSlides/_rels/notesSlide{new_note_numbers[1]}.xml.rels"] = update_note_rel_slide_target( | |
| text_note_rel_template, new_slide_numbers[1] | |
| ) | |
| presentation_root = ET.fromstring(files["ppt/presentation.xml"]) | |
| rel_root = ET.fromstring(files["ppt/_rels/presentation.xml.rels"]) | |
| sld_id_list = presentation_root.find("p:sldIdLst", NS) | |
| sld_ids = sld_id_list.findall("p:sldId", NS) | |
| rels = rel_root.findall(f"{{{REL_NS}}}Relationship") | |
| rel_map = {rel.attrib["Id"]: rel.attrib.get("Target", "") for rel in rels} | |
| insert_pos = None | |
| slide15_rid = None | |
| for index, sld in enumerate(sld_ids): | |
| rid = sld.attrib.get(qn("r", "id")) | |
| if rel_map.get(rid) == "slides/slide15.xml": | |
| insert_pos = index + 1 | |
| slide15_rid = rid | |
| break | |
| if insert_pos is None or slide15_rid is None: | |
| raise RuntimeError("Failed to locate slide15.xml in presentation order.") | |
| max_sld_id = max(int(node.attrib["id"]) for node in sld_ids) | |
| max_rid = max(int(rel.attrib["Id"][3:]) for rel in rels if rel.attrib.get("Id", "").startswith("rId")) | |
| new_rids = [f"rId{max_rid + 1}", f"rId{max_rid + 2}"] | |
| for offset, (new_sld_id, new_rid) in enumerate(zip([max_sld_id + 1, max_sld_id + 2], new_rids)): | |
| sld_id_list.insert( | |
| insert_pos + offset, | |
| ET.Element(qn("p", "sldId"), {"id": str(new_sld_id), qn("r", "id"): new_rid}), | |
| ) | |
| for new_rid, slide_number in zip(new_rids, new_slide_numbers): | |
| rel_root.append( | |
| ET.Element( | |
| f"{{{REL_NS}}}Relationship", | |
| { | |
| "Id": new_rid, | |
| "Type": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide", | |
| "Target": f"slides/slide{slide_number}.xml", | |
| }, | |
| ) | |
| ) | |
| files["ppt/presentation.xml"] = ET.tostring(presentation_root, encoding="utf-8", xml_declaration=True) | |
| files["ppt/_rels/presentation.xml.rels"] = ET.tostring(rel_root, encoding="utf-8", xml_declaration=True) | |
| content_root = ET.fromstring(files["[Content_Types].xml"]) | |
| ensure_override( | |
| content_root, | |
| f"/ppt/slides/slide{new_slide_numbers[0]}.xml", | |
| "application/vnd.openxmlformats-officedocument.presentationml.slide+xml", | |
| ) | |
| ensure_override( | |
| content_root, | |
| f"/ppt/slides/slide{new_slide_numbers[1]}.xml", | |
| "application/vnd.openxmlformats-officedocument.presentationml.slide+xml", | |
| ) | |
| ensure_override( | |
| content_root, | |
| f"/ppt/notesSlides/notesSlide{new_note_numbers[0]}.xml", | |
| "application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml", | |
| ) | |
| ensure_override( | |
| content_root, | |
| f"/ppt/notesSlides/notesSlide{new_note_numbers[1]}.xml", | |
| "application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml", | |
| ) | |
| files["[Content_Types].xml"] = ET.tostring(content_root, encoding="utf-8", xml_declaration=True) | |
| temp_path = ppt_path.with_suffix(".tmp.pptx") | |
| with zipfile.ZipFile(temp_path, "w", compression=zipfile.ZIP_DEFLATED) as output_zip: | |
| for name in sorted(files): | |
| output_zip.writestr(name, files[name]) | |
| temp_path.replace(ppt_path) | |
| def main() -> None: | |
| insert_after_slide(PPT_PATH) | |
| print(f"Inserted overall mean coverage slides into: {PPT_PATH}") | |
| if __name__ == "__main__": | |
| main() | |