|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | + |
| 4 | +import re |
| 5 | +import sys |
| 6 | +import json |
| 7 | +import html |
| 8 | +import base64 |
| 9 | +from pathlib import Path |
| 10 | +from typing import Dict, List, Optional, Tuple |
| 11 | +import pandas as pd |
| 12 | +from bs4 import BeautifulSoup |
| 13 | + |
| 14 | + |
| 15 | +def get_png_files(soup: BeautifulSoup, outdir: Path) -> None: |
| 16 | + """Get png base64 images following specific h1 tags in preview.html""" |
| 17 | + target_ids = ["Transcript_Plots", "Noise_Level"] |
| 18 | + outdir.mkdir(parents=True, exist_ok=True) |
| 19 | + |
| 20 | + for h1_id in target_ids: |
| 21 | + h1_tag = soup.find("h1", id=h1_id) |
| 22 | + if not h1_tag: |
| 23 | + print(f"[WARN] No <h1> with id {h1_id} found") |
| 24 | + continue |
| 25 | + |
| 26 | + # Look for the first <img> after the h1 in the DOM |
| 27 | + img_tag = h1_tag.find_next("img") |
| 28 | + if not img_tag or not img_tag.get("src"): |
| 29 | + print(f"[WARN] No <img> found after h1#{h1_id}") |
| 30 | + continue |
| 31 | + |
| 32 | + img_src = img_tag["src"] |
| 33 | + if img_src.startswith("data:image/png;base64,"): |
| 34 | + base64_data = img_src.split(",", 1)[1] |
| 35 | + data = base64.b64decode(base64_data) |
| 36 | + else: |
| 37 | + print(f"[WARN] img src is not base64 PNG for h1#{h1_id}") |
| 38 | + continue |
| 39 | + |
| 40 | + # save png files |
| 41 | + img_name = f"{h1_id}.png".lower() |
| 42 | + out_path = outdir / img_name |
| 43 | + with open(out_path, "wb") as f: |
| 44 | + f.write(data) |
| 45 | + |
| 46 | + print(f"[INFO] Saved {img_name}") |
| 47 | + |
| 48 | + return None |
| 49 | + |
| 50 | + |
| 51 | +def extract_js_object(text: str, start_idx: int) -> Tuple[Optional[str], int]: |
| 52 | + """Extract json-like object starting at start_idx.""" |
| 53 | + if start_idx >= len(text) or text[start_idx] != "{": |
| 54 | + return None, start_idx |
| 55 | + |
| 56 | + stack, in_str, escape, quote = [], False, False, None |
| 57 | + for i in range(start_idx, len(text)): |
| 58 | + ch = text[i] |
| 59 | + if in_str: |
| 60 | + if escape: |
| 61 | + escape = False |
| 62 | + elif ch == "\\": |
| 63 | + escape = True |
| 64 | + elif ch == quote: |
| 65 | + in_str = False |
| 66 | + else: |
| 67 | + if ch in ('"', "'"): |
| 68 | + in_str, quote = True, ch |
| 69 | + elif ch == "{": |
| 70 | + stack.append("{") |
| 71 | + elif ch == "}": |
| 72 | + stack.pop() |
| 73 | + if not stack: |
| 74 | + return text[start_idx : i + 1], i + 1 |
| 75 | + elif ch == "/" and i + 1 < len(text): |
| 76 | + # skip js comments |
| 77 | + nxt = text[i + 1] |
| 78 | + if nxt == "/": |
| 79 | + end = text.find("\n", i + 2) |
| 80 | + i = len(text) - 1 if end == -1 else end |
| 81 | + elif nxt == "*": |
| 82 | + end = text.find("*/", i + 2) |
| 83 | + if end == -1: |
| 84 | + break |
| 85 | + i = end + 1 |
| 86 | + |
| 87 | + return None, start_idx |
| 88 | + |
| 89 | + |
| 90 | +def js_to_json(js: str) -> str: |
| 91 | + """Convert a JS object string to valid JSON.""" |
| 92 | + # Remove comments |
| 93 | + js = re.sub(r"/\*.*?\*/", "", js, flags=re.S) |
| 94 | + js = re.sub(r"//[^\n]*", "", js) |
| 95 | + |
| 96 | + # Convert single-quoted strings to double-quoted strings |
| 97 | + js = re.sub( |
| 98 | + r"'((?:\\.|[^'\\])*)'", |
| 99 | + lambda m: '"' + m.group(1).replace('\"', '\\"') + '\"', |
| 100 | + js |
| 101 | + ) |
| 102 | + |
| 103 | + # Remove trailing commas |
| 104 | + js = re.sub(r",\s*(?=[}\]])", "", js) |
| 105 | + js = re.sub(r",\s*,+", ",", js) |
| 106 | + |
| 107 | + return js.strip() |
| 108 | + |
| 109 | + |
| 110 | +def find_variables(script_text: str) -> Dict[str, str]: |
| 111 | + """Find all 'var|let|const specN =' declarations and extract their objects.""" |
| 112 | + specs: Dict[str, str] = {} |
| 113 | + script_text = html.unescape(script_text) |
| 114 | + pattern = re.compile(r"(?:var|let|const)\s+(spec\d+)\s*=\s*{", re.I) |
| 115 | + |
| 116 | + for match in pattern.finditer(script_text): |
| 117 | + var = match.group(1) |
| 118 | + obj, _ = extract_js_object(script_text, match.end() - 1) |
| 119 | + if obj: |
| 120 | + specs[var] = obj |
| 121 | + else: |
| 122 | + print(f"[WARN] Could not extract object for {var}") |
| 123 | + return specs |
| 124 | + |
| 125 | + |
| 126 | +def write_tsvs(specs: Dict[str, str], outdir: Path) -> List[Path]: |
| 127 | + """Convert extracted json to tsv.""" |
| 128 | + outdir.mkdir(parents=True, exist_ok=True) |
| 129 | + written: List[Path] = [] |
| 130 | + |
| 131 | + for var, js_obj in specs.items(): |
| 132 | + try: |
| 133 | + data = json.loads(js_to_json(js_obj)) |
| 134 | + values = data.get("data", {}).get("values", []) |
| 135 | + if not values: |
| 136 | + print(f"[WARN] No data.values found in {var}") |
| 137 | + continue |
| 138 | + |
| 139 | + df = pd.DataFrame(values) |
| 140 | + outpath = outdir / f"{var}_mqc.tsv" |
| 141 | + |
| 142 | + with open(outpath, "w") as f: |
| 143 | + f.write("# plot_type: linegraph\n") |
| 144 | + f.write(f"# section_name: {var}\n") |
| 145 | + f.write("# description: Extracted preview data\n") |
| 146 | + df.to_csv(f, sep="\t", index=False) |
| 147 | + |
| 148 | + written.append(outpath) |
| 149 | + print(f"[INFO] Wrote {outpath} ({len(df)} rows × {len(df.columns)} cols)") |
| 150 | + except Exception as e: |
| 151 | + print(f"[ERROR] Failed to process {var}: {e}") |
| 152 | + |
| 153 | + return written |
| 154 | + |
| 155 | + |
| 156 | + |
| 157 | +if __name__ == "__main__": |
| 158 | + |
| 159 | + input_path: Path = Path("${preview_html}") |
| 160 | + outdir: Path = Path("${prefix}") |
| 161 | + |
| 162 | + text = input_path.read_text(encoding="utf-8", errors="ignore") |
| 163 | + soup = BeautifulSoup(text, "html.parser") |
| 164 | + |
| 165 | + # get the script section |
| 166 | + if "<script" in text.lower(): |
| 167 | + script_text = "\n".join(s.get_text() for s in soup.find_all("script")) |
| 168 | + else: |
| 169 | + script_text = text |
| 170 | + |
| 171 | + spec_variables = find_variables(script_text) |
| 172 | + if not spec_variables: |
| 173 | + print("[ERROR] No variables (spec1, spec2, spec3) found.") |
| 174 | + sys.exit(1) |
| 175 | + |
| 176 | + # write tsv files for multiqc |
| 177 | + written = write_tsvs(spec_variables, outdir) |
| 178 | + if not written: |
| 179 | + print("[ERROR] No TSVs written.") |
| 180 | + sys.exit(1) |
| 181 | + |
| 182 | + # get png files |
| 183 | + get_png_files(soup=soup, outdir=outdir) |
| 184 | + |
| 185 | + # write versions.yml |
| 186 | + with open("versions.yml", "w") as f: |
| 187 | + f.write('"${task.process}":\\n') |
| 188 | + f.write('EXTRACT_PREVIEW_DATA: "1.0.0"\\n') |
0 commit comments