"""Re-test the working links several times and keep only the stable ones.""" import json import os import shutil import subprocess import sys import time HERE = os.path.dirname(os.path.abspath(__file__)) SB = r"C:\Users\F.Naghibi\Downloads\PattN-windows-64\bin\sing_box\sing-box.exe" sys.path.insert(0, HERE) from find_opencode_configs import build_config, parse_link, probe # noqa: E402 ROUNDS = 3 CHUNK = 20 BASE = 22400 src = os.path.join(HERE, "opencode-working.txt") links = [ln.strip() for ln in open(src, encoding="utf-8") if ln.strip()] print(f"re-testing {len(links)} links x{ROUNDS} rounds\n") stats = {ln: {"ok": 0, "ms": []} for ln in links} for ci in range(0, len(links), CHUNK): chunk = links[ci:ci + CHUNK] parsed = [(ln, parse_link(ln)) for ln in chunk] parsed = [(ln, ob) for ln, ob in parsed if ob] if not parsed: continue cfg = build_config([ob for _, ob in parsed], BASE) p = os.path.join(os.environ["TEMP"], "refine.json") with open(p, "w", encoding="utf-8") as fh: json.dump(cfg, fh) proc = subprocess.Popen([SB, "run", "-c", p], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) try: time.sleep(3.5) for _ in range(ROUNDS): for i, (ln, _ob) in enumerate(parsed): code, ms = probe(BASE + i, "https://opencode.ai/zen/v1/models") if code == 200: stats[ln]["ok"] += 1 stats[ln]["ms"].append(ms) time.sleep(1) finally: proc.terminate() try: proc.wait(timeout=5) except Exception: # noqa: BLE001 proc.kill() print(f" {min(ci + CHUNK, len(links))}/{len(links)} done") stable = [] for ln, s in stats.items(): if s["ok"] >= 2: avg = int(sum(s["ms"]) / len(s["ms"])) if s["ms"] else 99999 stable.append((s["ok"], avg, ln)) stable.sort(key=lambda x: (-x[0], x[1])) shutil.copy2(src, os.path.join(HERE, "opencode-all-working.txt")) with open(src, "w", encoding="utf-8") as fh: fh.write("".join(ln + "\n" for _, _, ln in stable)) print(f"\nstable: {len(stable)}/{len(links)} (>=2 of {ROUNDS})") for ok, ms, ln in stable[:10]: print(f" {ok}/{ROUNDS} {ms:>5}ms {ln[:80]}") print(f"\n -> {src}") print(f" -> opencode-all-working.txt (all {len(links)} candidates)")