Apply ruff lint and rename cryptic identifiers to readable names
This commit is contained in:
+562
-156
@@ -1,265 +1,625 @@
|
||||
# llama.py: starts llama-server (local GGUF chat/vision/embedding), routes chat to local or cloud models, installs omp and downloads models.
|
||||
import functools, hashlib, json, os, shutil, socket, ssl, subprocess, sys, time, urllib.error, urllib.request
|
||||
import functools
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
# Paths relative to this file: bin/ (llama-server, omp), models/ (GGUF), out/ (GUI state).
|
||||
HERE = Path(__file__).parent
|
||||
SERVER = HERE / "bin" / "llama-server.exe"
|
||||
MD = HERE / "models"
|
||||
CHOICE = HERE / "out" / "_global" / "llm.txt" # GUI header: "<shots model> <report model>"
|
||||
MODELS_DIR = HERE / "models"
|
||||
CHOICE_FILE = HERE / "out" / "_global" / "llm.txt" # GUI header: "<shots model> <report model>"
|
||||
# Benchmarked on RTX 500 Ada 4 GB (Windows leaves ~3.2 GB free) + Core Ultra 7 155H, 2026-11-02.
|
||||
_Q = ["-ctk", "q8_0", "-ctv", "q8_0", "-fa", "on", "-np", "1"] # KV q8: no measurable loss; V q4 made the 4B loop
|
||||
_IMG = ["--image-min-tokens", "1024", "--image-max-tokens", "1536"] # 1024 = Qwen-VL grounding min; 1536 cap: same quality as 3.7k, 3x faster
|
||||
_KV_ARGS = [
|
||||
"-ctk",
|
||||
"q8_0",
|
||||
"-ctv",
|
||||
"q8_0",
|
||||
"-fa",
|
||||
"on",
|
||||
"-np",
|
||||
"1",
|
||||
] # KV q8: no measurable loss; V q4 made the 4B loop
|
||||
_IMAGE_ARGS = [
|
||||
"--image-min-tokens",
|
||||
"1024",
|
||||
"--image-max-tokens",
|
||||
"1536",
|
||||
] # 1024 = Qwen-VL grounding min; 1536 cap: same quality as 3.7k, 3x faster
|
||||
# key -> (label, model, mmproj, vision args (shots), text args (report/ask: no mmproj, more VRAM for layers/batch))
|
||||
# Values below are the 4 GB profile; _fit() strips -ngl/-ot/--cpu-moe on >= 7 GiB GPUs.
|
||||
MODELS = {
|
||||
# MoE experts in RAM (needs ~48+ GB RAM). Vision: encoder on GPU (CPU encoder was ~100 s/shot), so only 30/40 attention
|
||||
# layers fit (-ngl 25 halves gen speed). Text: no encoder -> all layers + -ub 2048 (prompt eval 230 -> 340 tok/s).
|
||||
"qwen35b": ("Qwen3.6 35B-A3B (RAM)", MD / "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf", MD / "mmproj-BF16.gguf",
|
||||
["--mmproj-offload", *_IMG, "--cpu-moe", "-ngl", "30", "-c", "16384", *_Q],
|
||||
["--cpu-moe", "-ngl", "99", "-c", "16384", "-ub", "2048", "--reasoning-budget", "1024", *_Q]),
|
||||
"qwen35b": (
|
||||
"Qwen3.6 35B-A3B (RAM)",
|
||||
MODELS_DIR / "Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf",
|
||||
MODELS_DIR / "mmproj-BF16.gguf",
|
||||
["--mmproj-offload", *_IMAGE_ARGS, "--cpu-moe", "-ngl", "30", "-c", "16384", *_KV_ARGS],
|
||||
[
|
||||
"--cpu-moe",
|
||||
"-ngl",
|
||||
"99",
|
||||
"-c",
|
||||
"16384",
|
||||
"-ub",
|
||||
"2048",
|
||||
"--reasoning-budget",
|
||||
"1024",
|
||||
*_KV_ARGS,
|
||||
],
|
||||
),
|
||||
# Hybrid attention -> 16k KV is only ~0.3 GB. Q4_K_S: best boxes/entities vs IQ4_XS/Q4_K_M/UD-Q4_K_XL on 8 sample shots.
|
||||
# Vision: encoder on GPU, FFN of the last 13/32 layers in RAM to make room: shot 36 -> 22 s (CPU encoder was ~19 s/image),
|
||||
# gen only 30 -> 25 tok/s; 12 is the limit (10 OOMs), 13 leaves margin. Text: everything on GPU.
|
||||
"qwen4b": ("Qwen3.5 4B (VRAM)", MD / "qwen3.5-4b" / "Qwen3.5-4B-Q4_K_S.gguf", MD / "qwen3.5-4b" / "mmproj-BF16.gguf",
|
||||
["--mmproj-offload", *_IMG, "-ngl", "99", "-ot", r"blk\.(19|2[0-9]|3[01])\.ffn_.*=CPU", "-c", "16384", *_Q],
|
||||
["-ngl", "99", "-c", "16384", "-ub", "1024", "--reasoning-budget", "1024", *_Q]),
|
||||
"qwen4b": (
|
||||
"Qwen3.5 4B (VRAM)",
|
||||
MODELS_DIR / "qwen3.5-4b" / "Qwen3.5-4B-Q4_K_S.gguf",
|
||||
MODELS_DIR / "qwen3.5-4b" / "mmproj-BF16.gguf",
|
||||
[
|
||||
"--mmproj-offload",
|
||||
*_IMAGE_ARGS,
|
||||
"-ngl",
|
||||
"99",
|
||||
"-ot",
|
||||
r"blk\.(19|2[0-9]|3[01])\.ffn_.*=CPU",
|
||||
"-c",
|
||||
"16384",
|
||||
*_KV_ARGS,
|
||||
],
|
||||
["-ngl", "99", "-c", "16384", "-ub", "1024", "--reasoning-budget", "1024", *_KV_ARGS],
|
||||
),
|
||||
}
|
||||
# Ports on 127.0.0.1: chat completion server and bge-m3 embedding server.
|
||||
PORT = 18081
|
||||
EMBED, EMBED_PORT = MD / "bge-m3-Q8_0.gguf", 18082
|
||||
EMBED, EMBED_PORT = MODELS_DIR / "bge-m3-Q8_0.gguf", 18082
|
||||
|
||||
|
||||
# Cached: nvidia-smi is slow and the GPU does not change while the app runs.
|
||||
@functools.cache
|
||||
def vram_mib():
|
||||
"""Largest NVIDIA GPU's total VRAM in MiB; 0 without NVIDIA driver."""
|
||||
# memory.total per GPU in MiB, plain numbers (nounits); max() picks the largest card.
|
||||
try: return max(int(x) for x in subprocess.run(["nvidia-smi", "--query-gpu=memory.total", "--format=csv,noheader,nounits"],
|
||||
capture_output=True, text=True, timeout=10).stdout.split())
|
||||
except (OSError, ValueError, subprocess.SubprocessError): return 0
|
||||
try:
|
||||
return max(
|
||||
int(value)
|
||||
for value in subprocess.run(
|
||||
["nvidia-smi", "--query-gpu=memory.total", "--format=csv,noheader,nounits"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
).stdout.split()
|
||||
)
|
||||
except (OSError, ValueError, subprocess.SubprocessError):
|
||||
return 0
|
||||
|
||||
|
||||
_TUNED = {"-ngl": 1, "-ot": 1, "--cpu-moe": 0} # 4 GB placement flags -> number of values they take
|
||||
|
||||
|
||||
def _fit(args, vision):
|
||||
"""GPUs >= 7 GiB: drop the 4 GB hand-tuned layer/expert placement so llama.cpp --fit (default on) fills VRAM.
|
||||
Vision keeps 3 GiB margin: --fit sizes only the LLM, the mmproj encoder loads after it."""
|
||||
if vram_mib() < 7168: return args
|
||||
out, it = [], iter(args)
|
||||
for a in it:
|
||||
if a in _TUNED:
|
||||
for _ in range(_TUNED[a]): next(it)
|
||||
else: out.append(a)
|
||||
return out + (["-fitt", "3072"] if vision else [])
|
||||
_open = urllib.request.build_opener(urllib.request.ProxyHandler({})).open # corp proxy must not see localhost
|
||||
if vram_mib() < 7168:
|
||||
return args
|
||||
kept_args, arg_iter = [], iter(args)
|
||||
for argument in arg_iter:
|
||||
if argument in _TUNED:
|
||||
for _ in range(_TUNED[argument]):
|
||||
next(arg_iter)
|
||||
else:
|
||||
kept_args.append(argument)
|
||||
return kept_args + (["-fitt", "3072"] if vision else [])
|
||||
|
||||
|
||||
_open = urllib.request.build_opener(
|
||||
urllib.request.ProxyHandler({})
|
||||
).open # corp proxy must not see localhost
|
||||
|
||||
PROXY = "http://zproxy.idg.audi.vwg:9400" # corp proxy for internet calls (docs.py twg, cloud LLMs)
|
||||
# key -> (label, model id, vision, provider). Vision=False: report/docs/memory/ask only (BYOK italdesign/ models reject images).
|
||||
REMOTE = {
|
||||
"cp-haiku": ("Claude Haiku 5.5 (Copilot, crediti)", "claude-haiku-5.5", True, "github-copilot"),
|
||||
"cp-kimi": ("Kimi K2.5 (italdesign BYOK)", "italdesign/Bedrock_Mantle/moonshotai.kimi-k2.5", False, "github-copilot"),
|
||||
"cp-deepseek": ("DeepSeek V3.2 (italdesign BYOK)", "italdesign/Bedrock_Mantle/deepseek.v3.2", False, "github-copilot"),
|
||||
"cp-sonnet": ("Claude Sonnet 5.5 (Copilot, crediti)", "claude-sonnet-5.5", False, "github-copilot"),
|
||||
"cp-gemini": ("Gemini 3.8 Flash (Copilot, crediti)", "gemini-3.8-flash", False, "github-copilot"),
|
||||
"an-haiku": ("Claude Haiku 5.5 (Anthropic, abbonamento)", "claude-haiku-5-5", True, "anthropic"),
|
||||
"an-sonnet": ("Claude Sonnet 5.5 (Anthropic, abbonamento)", "claude-sonnet-5-5", True, "anthropic"),
|
||||
"cp-kimi": (
|
||||
"Kimi K2.5 (italdesign BYOK)",
|
||||
"italdesign/Bedrock_Mantle/moonshotai.kimi-k2.5",
|
||||
False,
|
||||
"github-copilot",
|
||||
),
|
||||
"cp-deepseek": (
|
||||
"DeepSeek V3.2 (italdesign BYOK)",
|
||||
"italdesign/Bedrock_Mantle/deepseek.v3.2",
|
||||
False,
|
||||
"github-copilot",
|
||||
),
|
||||
"cp-sonnet": (
|
||||
"Claude Sonnet 5.5 (Copilot, crediti)",
|
||||
"claude-sonnet-5.5",
|
||||
False,
|
||||
"github-copilot",
|
||||
),
|
||||
"cp-gemini": (
|
||||
"Gemini 3.8 Flash (Copilot, crediti)",
|
||||
"gemini-3.8-flash",
|
||||
False,
|
||||
"github-copilot",
|
||||
),
|
||||
"an-haiku": (
|
||||
"Claude Haiku 5.5 (Anthropic, abbonamento)",
|
||||
"claude-haiku-5-5",
|
||||
True,
|
||||
"anthropic",
|
||||
),
|
||||
"an-sonnet": (
|
||||
"Claude Sonnet 5.5 (Anthropic, abbonamento)",
|
||||
"claude-sonnet-5-5",
|
||||
True,
|
||||
"anthropic",
|
||||
),
|
||||
}
|
||||
# Headers that make Copilot's API accept requests as from the Copilot CLI / editor plugin.
|
||||
_HDR = {"Editor-Version": "vscode/1.107.1", "Editor-Plugin-Version": "copilot-chat/0.26.7", "Copilot-Integration-Id": "copilot-developer-cli"}
|
||||
_ctx = ssl.create_default_context(); _ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT # corp TLS proxy CA lacks critical basicConstraints
|
||||
_NO_PROXY = "localhost,127.0.0.1,.audi.vwg,.vwgroup.com,.vwg,.italdesign.it" # same list as $PROFILE
|
||||
_COPILOT_HEADERS = {
|
||||
"Editor-Version": "vscode/1.107.1",
|
||||
"Editor-Plugin-Version": "copilot-chat/0.26.7",
|
||||
"Copilot-Integration-Id": "copilot-developer-cli",
|
||||
}
|
||||
_ssl_context = ssl.create_default_context()
|
||||
_ssl_context.verify_flags &= (
|
||||
~ssl.VERIFY_X509_STRICT
|
||||
) # corp TLS proxy CA lacks critical basicConstraints
|
||||
_NO_PROXY = (
|
||||
"localhost,127.0.0.1,.audi.vwg,.vwgroup.com,.vwg,.italdesign.it" # same list as $PROFILE
|
||||
)
|
||||
# Cache of the proxy probe: [timestamp, proxy URL or None].
|
||||
_PX = [0.0, None]
|
||||
_proxy_probe = [0.0, None]
|
||||
|
||||
|
||||
def proxy():
|
||||
"""PROXY if reachable right now (TCP connect, 2 s; = $PROFILE's Test-Connection), else None. Re-checked every 5 min: laptops move between office/VPN/home."""
|
||||
if time.time() - _PX[0] > 300:
|
||||
if time.time() - _proxy_probe[0] > 300:
|
||||
# Reachability probe only: a TCP connect to the proxy host, no HTTP request.
|
||||
try: socket.create_connection(("zproxy.idg.audi.vwg", 9400), timeout=2).close(); px = PROXY
|
||||
except OSError: px = None
|
||||
_PX[:] = [time.time(), px]
|
||||
return _PX[1]
|
||||
try:
|
||||
socket.create_connection(("zproxy.idg.audi.vwg", 9400), timeout=2).close()
|
||||
proxy_url = PROXY
|
||||
except OSError:
|
||||
proxy_url = None
|
||||
_proxy_probe[:] = [time.time(), proxy_url]
|
||||
return _proxy_probe[1]
|
||||
|
||||
|
||||
# One opener per proxy setting; the proxy URL is the cache key.
|
||||
@functools.cache
|
||||
def _opener(px):
|
||||
return urllib.request.build_opener(urllib.request.ProxyHandler({"https": px, "http": px} if px else {}), urllib.request.HTTPSHandler(context=_ctx)).open
|
||||
def _opener(proxy_url):
|
||||
return urllib.request.build_opener(
|
||||
urllib.request.ProxyHandler({"https": proxy_url, "http": proxy_url} if proxy_url else {}),
|
||||
urllib.request.HTTPSHandler(context=_ssl_context),
|
||||
).open
|
||||
|
||||
|
||||
def _ropen():
|
||||
"""Opener for internet calls: through the corp proxy when reachable, else direct (ProxyHandler({}) ignores stale env proxies, like $PROFILE's else branch)."""
|
||||
return _opener(proxy())
|
||||
|
||||
|
||||
def omp_env():
|
||||
"""Env for omp subprocesses: omp ignores HTTP(S)_PROXY and reads PI_PROXY; the corp proxy re-signs TLS. Without the proxy, strip every proxy var."""
|
||||
# Build omp's env without any inherited proxy vars, so a stale proxy setting cannot leak in.
|
||||
env = {k: v for k, v in os.environ.items() if k.upper() not in ("HTTP_PROXY", "HTTPS_PROXY", "PI_PROXY", "NO_PROXY")}
|
||||
child_env = {
|
||||
key: value
|
||||
for key, value in os.environ.items()
|
||||
if key.upper() not in ("HTTP_PROXY", "HTTPS_PROXY", "PI_PROXY", "NO_PROXY")
|
||||
}
|
||||
# NODE_TLS_REJECT_UNAUTHORIZED=0: omp's Node runtime rejects the corp proxy's re-signed certificate.
|
||||
# Corp proxy only while reachable; it re-signs TLS, so omp must accept its certificate.
|
||||
if px := proxy(): env.update(HTTP_PROXY=px, HTTPS_PROXY=px, PI_PROXY=px, NO_PROXY=_NO_PROXY, NODE_TLS_REJECT_UNAUTHORIZED="0")
|
||||
return env
|
||||
if proxy_url := proxy():
|
||||
child_env.update(
|
||||
HTTP_PROXY=proxy_url,
|
||||
HTTPS_PROXY=proxy_url,
|
||||
PI_PROXY=proxy_url,
|
||||
NO_PROXY=_NO_PROXY,
|
||||
NODE_TLS_REJECT_UNAUTHORIZED="0",
|
||||
)
|
||||
return child_env
|
||||
|
||||
|
||||
# Local models whose GGUF file is present on disk.
|
||||
def _local(): return [k for k, m in MODELS.items() if m[1].exists()]
|
||||
def _local():
|
||||
return [key for key, spec in MODELS.items() if spec[1].exists()]
|
||||
|
||||
|
||||
# Installed local models, plus cloud models (vision=True keeps only those accepting images).
|
||||
def available(vision=True): return _local() + [k for k, r in REMOTE.items() if r[2] or not vision]
|
||||
def label(k): return (MODELS.get(k) or REMOTE[k])[0]
|
||||
def available(vision=True):
|
||||
return _local() + [key for key, spec in REMOTE.items() if spec[2] or not vision]
|
||||
|
||||
|
||||
def label(key):
|
||||
return (MODELS.get(key) or REMOTE[key])[0]
|
||||
|
||||
|
||||
def current(vision=True):
|
||||
"""Model for shots (vision) or report/ask (text): GUI choice if available, else 4B for shots (VRAM-only, near-35B shots)
|
||||
and the biggest local model for reports (4B reports lose structure on long transcripts). Falls back to the first cloud model only when no local model is installed (cloud-only install)."""
|
||||
# CHOICE holds "<vision key> <text key>"; an empty file gives [""] so fallbacks apply.
|
||||
ks = (CHOICE.read_text().split() if CHOICE.exists() else []) or [""]
|
||||
k = ks[0] if vision else ks[-1] # a single key (old format) applies to both
|
||||
if k in available(vision): return k
|
||||
loc = _local()
|
||||
keys = (CHOICE_FILE.read_text().split() if CHOICE_FILE.exists() else []) or [""]
|
||||
key = keys[0] if vision else keys[-1] # a single key (old format) applies to both
|
||||
if key in available(vision):
|
||||
return key
|
||||
local_keys = _local()
|
||||
# 4B fits fully in VRAM: shots near 35B quality at much higher speed (see MODELS).
|
||||
if vision and "qwen4b" in loc: return "qwen4b"
|
||||
return (loc or available(vision))[0]
|
||||
if vision and "qwen4b" in local_keys:
|
||||
return "qwen4b"
|
||||
return (local_keys or available(vision))[0]
|
||||
|
||||
|
||||
OMP_LOCAL = (
|
||||
HERE / "bin" / "omp.exe"
|
||||
) # Pinokio-local install (llama.py install-omp); wins over a PATH omp so the install's own copy is always the one used
|
||||
|
||||
|
||||
def omp_exe():
|
||||
return str(OMP_LOCAL) if OMP_LOCAL.exists() else shutil.which("omp")
|
||||
|
||||
|
||||
_token_cache = {} # provider -> (token, api base, fetched at)
|
||||
|
||||
OMP_LOCAL = HERE / "bin" / "omp.exe" # Pinokio-local install (llama.py install-omp); wins over a PATH omp so the install's own copy is always the one used
|
||||
def omp_exe(): return str(OMP_LOCAL) if OMP_LOCAL.exists() else shutil.which("omp")
|
||||
|
||||
_TOK = {} # provider -> (token, api base, fetched at)
|
||||
def _token(provider):
|
||||
"""(token, api base) via `omp token` (it refreshes expired OAuth). ponytail: 5-min cache, re-query on every call if a token ever dies inside it."""
|
||||
t = _TOK.get(provider)
|
||||
cached = _token_cache.get(provider)
|
||||
# Reuse the cached token for 5 min instead of spawning omp on every call.
|
||||
if t and time.time() - t[2] < 300: return t[:2]
|
||||
exe = omp_exe()
|
||||
if not exe: raise RuntimeError("omp non installato: esegui Install da Pinokio")
|
||||
if cached and time.time() - cached[2] < 300:
|
||||
return cached[:2]
|
||||
omp_path = omp_exe()
|
||||
if not omp_path:
|
||||
raise RuntimeError("omp non installato: esegui Install da Pinokio")
|
||||
# --raw: bare token, or JSON {token, apiEndpoint}; 60 s guards against a hung omp.
|
||||
r = subprocess.run([exe, "token", provider, "--raw"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60, env=omp_env())
|
||||
result = subprocess.run(
|
||||
[omp_path, "token", provider, "--raw"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
timeout=60,
|
||||
env=omp_env(),
|
||||
)
|
||||
# Non-zero exit = not logged in; surface the reason to the GUI.
|
||||
if r.returncode: raise RuntimeError(f"{provider}: login necessario (Pinokio → Cloud login). {r.stderr.strip()[:200]}")
|
||||
if result.returncode:
|
||||
raise RuntimeError(
|
||||
f"{provider}: login necessario (Pinokio → Cloud login). {result.stderr.strip()[:200]}"
|
||||
)
|
||||
# omp prints a JSON object {token, apiEndpoint} or a bare token; accept both.
|
||||
out = r.stdout.strip(); d = json.loads(out) if out.startswith("{") else {"token": out}
|
||||
stdout_text = result.stdout.strip()
|
||||
data = json.loads(stdout_text) if stdout_text.startswith("{") else {"token": stdout_text}
|
||||
# Fallback API base when omp does not report apiEndpoint.
|
||||
base = d.get("apiEndpoint") or ("https://api.githubcopilot.com" if provider == "github-copilot" else "https://api.anthropic.com")
|
||||
base = data.get("apiEndpoint") or (
|
||||
"https://api.githubcopilot.com"
|
||||
if provider == "github-copilot"
|
||||
else "https://api.anthropic.com"
|
||||
)
|
||||
# Cache the token with its fetch time (checked against the 5-min TTL above).
|
||||
_TOK[provider] = (d["token"], base, time.time()); return _TOK[provider][:2]
|
||||
_token_cache[provider] = (data["token"], base, time.time())
|
||||
return _token_cache[provider][:2]
|
||||
|
||||
|
||||
# Cache for omp_status(): [timestamp, status dict].
|
||||
_ST = [0.0, None]
|
||||
_omp_status_cache = [0.0, None]
|
||||
|
||||
|
||||
def omp_status():
|
||||
"""{'exe': path|None, 'github-copilot': None|reason, 'anthropic': None|reason}: can omp hand out a valid (refreshed) token right now. Cached 60 s (GUI polls every 3 s).
|
||||
ponytail: a revoked Copilot token only shows up on the next API call (its expiresAt is years away)."""
|
||||
if time.time() - _ST[0] < 60: return _ST[1]
|
||||
s = {"exe": omp_exe()}
|
||||
for p in ("github-copilot", "anthropic"):
|
||||
if time.time() - _omp_status_cache[0] < 60:
|
||||
return _omp_status_cache[1]
|
||||
status = {"exe": omp_exe()}
|
||||
for provider in ("github-copilot", "anthropic"):
|
||||
# Drop the cached token so every provider is re-checked for real.
|
||||
_TOK.pop(p, None)
|
||||
try: _token(p); s[p] = None
|
||||
except Exception as e: s[p] = str(e)
|
||||
_ST[:] = [time.time(), s]; return s
|
||||
_token_cache.pop(provider, None)
|
||||
try:
|
||||
_token(provider)
|
||||
status[provider] = None
|
||||
except Exception as err:
|
||||
status[provider] = str(err)
|
||||
_omp_status_cache[:] = [time.time(), status]
|
||||
return status
|
||||
|
||||
|
||||
# Headers Anthropic requires for subscription OAuth (mirrors Claude Code's client).
|
||||
_AHDR = {"anthropic-version": "2023-06-01", "anthropic-beta": "claude-code-20250219,oauth-2025-04-20", "user-agent": "claude-cli/2.1.280", "x-app": "cli"}
|
||||
def _anthropic(body, model, tok, timeout):
|
||||
_ANTHROPIC_HEADERS = {
|
||||
"anthropic-version": "2023-06-01",
|
||||
"anthropic-beta": "claude-code-20250219,oauth-2025-04-20",
|
||||
"user-agent": "claude-cli/2.1.280",
|
||||
"x-app": "cli",
|
||||
}
|
||||
|
||||
|
||||
def _anthropic(body, model, token, timeout):
|
||||
"""OpenAI chat body -> Anthropic Messages (subscription OAuth needs the Claude Code identity first, as omp/pi send) -> OpenAI-shaped response."""
|
||||
# Anthropic accepts subscription OAuth only with the Claude Code identity as the first system block.
|
||||
system, msgs = [{"type": "text", "text": "You are Claude Code, Anthropic's official CLI for Claude."}], []
|
||||
for m in body["messages"]:
|
||||
# Anthropic accepts subscription OAuth only with the Claude Code identity as the first system block.
|
||||
system, msgs = (
|
||||
[{"type": "text", "text": "You are Claude Code, Anthropic's official CLI for Claude."}],
|
||||
[],
|
||||
)
|
||||
for message in body["messages"]:
|
||||
# Anthropic takes system as blocks, so system messages are collected separately.
|
||||
if m["role"] == "system": system.append({"type": "text", "text": m["content"]}); continue
|
||||
c = m["content"]
|
||||
if isinstance(c, list): # shots.py: text + data-URL jpeg
|
||||
if message["role"] == "system":
|
||||
system.append({"type": "text", "text": message["content"]})
|
||||
continue
|
||||
content = message["content"]
|
||||
if isinstance(content, list): # shots.py: text + data-URL jpeg
|
||||
# OpenAI content parts -> Anthropic blocks; images arrive as data URLs.
|
||||
c = [{"type": "text", "text": p["text"]} if p["type"] == "text" else
|
||||
content = [
|
||||
{"type": "text", "text": part["text"]}
|
||||
if part["type"] == "text"
|
||||
# data:<mime>;base64,<data>: [5:] strips "data:", the mime is before ";".
|
||||
{"type": "image", "source": {"type": "base64", "media_type": p["image_url"]["url"][5:].split(";")[0], "data": p["image_url"]["url"].split(",", 1)[1]}} for p in c]
|
||||
msgs.append({"role": m["role"], "content": c})
|
||||
req = {"model": model, "max_tokens": body.get("max_tokens", 8192), "system": system, "messages": msgs, "thinking": {"type": "disabled"}} # no temperature: deprecated on these models (HTTP 400); thinking off: it eats max_tokens (empty text)
|
||||
h = {"Authorization": "Bearer " + tok, "Content-Type": "application/json", **_AHDR}
|
||||
else {
|
||||
"type": "image",
|
||||
"source": {
|
||||
"type": "base64",
|
||||
"media_type": part["image_url"]["url"][5:].split(";")[0],
|
||||
"data": part["image_url"]["url"].split(",", 1)[1],
|
||||
},
|
||||
}
|
||||
for part in content
|
||||
]
|
||||
msgs.append({"role": message["role"], "content": content})
|
||||
request_body = {
|
||||
"model": model,
|
||||
"max_tokens": body.get("max_tokens", 8192),
|
||||
"system": system,
|
||||
"messages": msgs,
|
||||
"thinking": {"type": "disabled"},
|
||||
} # no temperature: deprecated on these models (HTTP 400); thinking off: it eats max_tokens (empty text)
|
||||
headers = {
|
||||
"Authorization": "Bearer " + token,
|
||||
"Content-Type": "application/json",
|
||||
**_ANTHROPIC_HEADERS,
|
||||
}
|
||||
# Request goes through _ropen() so the corp proxy applies when reachable.
|
||||
try: d = json.load(_ropen()(urllib.request.Request("https://api.anthropic.com/v1/messages", json.dumps(req).encode(), h), timeout=timeout))
|
||||
except urllib.error.HTTPError as e: raise RuntimeError(f"Anthropic {model}: HTTP {e.code} {e.read()[:300].decode(errors='replace')}") from e
|
||||
try:
|
||||
data = json.load(
|
||||
_ropen()(
|
||||
urllib.request.Request(
|
||||
"https://api.anthropic.com/v1/messages",
|
||||
json.dumps(request_body).encode(),
|
||||
headers,
|
||||
),
|
||||
timeout=timeout,
|
||||
)
|
||||
)
|
||||
except urllib.error.HTTPError as err:
|
||||
raise RuntimeError(
|
||||
f"Anthropic {model}: HTTP {err.code} {err.read()[:300].decode(errors='replace')}"
|
||||
) from err
|
||||
# Re-wrap in OpenAI shape so report/ask/memory callers need no Anthropic branch.
|
||||
return {"choices": [{"message": {"content": "".join(b.get("text", "") for b in d["content"] if b["type"] == "text")}}],
|
||||
"usage": {"prompt_tokens": d["usage"]["input_tokens"], "completion_tokens": d["usage"]["output_tokens"]}}
|
||||
return {
|
||||
"choices": [
|
||||
{
|
||||
"message": {
|
||||
"content": "".join(
|
||||
block.get("text", "")
|
||||
for block in data["content"]
|
||||
if block["type"] == "text"
|
||||
)
|
||||
}
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": data["usage"]["input_tokens"],
|
||||
"completion_tokens": data["usage"]["output_tokens"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def post(body, vision, timeout):
|
||||
"""Chat completion on llama-server, or on a cloud model (Copilot / Anthropic via omp login) when the GUI picked a REMOTE model."""
|
||||
# Local llama-server unless the GUI picked a cloud (REMOTE) model.
|
||||
# GUI choice decides local vs cloud; REMOTE holds the cloud model metadata.
|
||||
k = current(vision); r = REMOTE.get(k)
|
||||
if not r:
|
||||
key = current(vision)
|
||||
remote = REMOTE.get(key)
|
||||
if not remote:
|
||||
# Local llama-server, OpenAI-compatible endpoint.
|
||||
req = urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions", json.dumps({**body, "model": k}).encode(), {"Content-Type": "application/json"})
|
||||
return json.load(_open(req, timeout=timeout))
|
||||
request = urllib.request.Request(
|
||||
f"http://127.0.0.1:{PORT}/v1/chat/completions",
|
||||
json.dumps({**body, "model": key}).encode(),
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
return json.load(_open(request, timeout=timeout))
|
||||
# Cloud: token and API base from omp.
|
||||
tok, base = _token(r[3])
|
||||
token, api_base = _token(remote[3])
|
||||
# chat_template_kwargs is llama.cpp-specific; cloud APIs would reject it.
|
||||
body = {**{x: v for x, v in body.items() if x != "chat_template_kwargs"}, "model": r[1]}
|
||||
if r[3] == "anthropic": return _anthropic(body, r[1], tok, timeout)
|
||||
body = {
|
||||
**{field: value for field, value in body.items() if field != "chat_template_kwargs"},
|
||||
"model": remote[1],
|
||||
}
|
||||
if remote[3] == "anthropic":
|
||||
return _anthropic(body, remote[1], token, timeout)
|
||||
# Copilot needs this header to accept image inputs.
|
||||
h = {"Authorization": "Bearer " + tok, "Content-Type": "application/json", **_HDR, **({"Copilot-Vision-Request": "true"} if vision else {})}
|
||||
try: return json.load(_ropen()(urllib.request.Request(base + "/chat/completions", json.dumps(body).encode(), h), timeout=timeout))
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 400: raise # callers retry 400 without response_format
|
||||
raise RuntimeError(f"Copilot {r[1]}: HTTP {e.code} {e.read()[:300].decode(errors='replace')}") from e
|
||||
headers = {
|
||||
"Authorization": "Bearer " + token,
|
||||
"Content-Type": "application/json",
|
||||
**_COPILOT_HEADERS,
|
||||
**({"Copilot-Vision-Request": "true"} if vision else {}),
|
||||
}
|
||||
try:
|
||||
return json.load(
|
||||
_ropen()(
|
||||
urllib.request.Request(
|
||||
api_base + "/chat/completions", json.dumps(body).encode(), headers
|
||||
),
|
||||
timeout=timeout,
|
||||
)
|
||||
)
|
||||
except urllib.error.HTTPError as err:
|
||||
if err.code == 400:
|
||||
raise # callers retry 400 without response_format
|
||||
raise RuntimeError(
|
||||
f"Copilot {remote[1]}: HTTP {err.code} {err.read()[:300].decode(errors='replace')}"
|
||||
) from err
|
||||
|
||||
|
||||
def stream(body, timeout):
|
||||
"""Like post() for text calls, but yields the reply text as it is generated (OpenAI SSE: local llama-server and Copilot).
|
||||
Anthropic is not streamed here: its whole reply is yielded at once."""
|
||||
k = current(False); r = REMOTE.get(k)
|
||||
if r and r[3] == "anthropic": yield content(post(body, False, timeout), "ask"); return
|
||||
if not r:
|
||||
req = urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions", json.dumps({**body, "model": k, "stream": True}).encode(), {"Content-Type": "application/json"}); op = _open
|
||||
key = current(False)
|
||||
remote = REMOTE.get(key)
|
||||
if remote and remote[3] == "anthropic":
|
||||
yield content(post(body, False, timeout), "ask")
|
||||
return
|
||||
if not remote:
|
||||
request = urllib.request.Request(
|
||||
f"http://127.0.0.1:{PORT}/v1/chat/completions",
|
||||
json.dumps({**body, "model": key, "stream": True}).encode(),
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
opener = _open
|
||||
else:
|
||||
tok, base = _token(r[3])
|
||||
b = {**{x: v for x, v in body.items() if x != "chat_template_kwargs"}, "model": r[1], "stream": True}
|
||||
req = urllib.request.Request(base + "/chat/completions", json.dumps(b).encode(), {"Authorization": "Bearer " + tok, "Content-Type": "application/json", **_HDR}); op = _ropen()
|
||||
with op(req, timeout=timeout) as f:
|
||||
for line in f:
|
||||
token, api_base = _token(remote[3])
|
||||
cloud_body = {
|
||||
**{field: value for field, value in body.items() if field != "chat_template_kwargs"},
|
||||
"model": remote[1],
|
||||
"stream": True,
|
||||
}
|
||||
request = urllib.request.Request(
|
||||
api_base + "/chat/completions",
|
||||
json.dumps(cloud_body).encode(),
|
||||
{
|
||||
"Authorization": "Bearer " + token,
|
||||
"Content-Type": "application/json",
|
||||
**_COPILOT_HEADERS,
|
||||
},
|
||||
)
|
||||
opener = _ropen()
|
||||
with opener(request, timeout=timeout) as response:
|
||||
for line in response:
|
||||
# SSE lines look like b"data: {json}"; the stream ends with "data: [DONE]".
|
||||
if not line.startswith(b"data: "): continue
|
||||
d = line[6:].strip()
|
||||
if d == b"[DONE]": break
|
||||
ch = json.loads(d).get("choices")
|
||||
if ch and ch[0].get("delta", {}).get("content"): yield ch[0]["delta"]["content"]
|
||||
if not line.startswith(b"data: "):
|
||||
continue
|
||||
payload = line[6:].strip()
|
||||
if payload == b"[DONE]":
|
||||
break
|
||||
choices = json.loads(payload).get("choices")
|
||||
if choices and choices[0].get("delta", {}).get("content"):
|
||||
yield choices[0]["delta"]["content"]
|
||||
|
||||
|
||||
# Persist the GUI choice as "<vision key> <text key>" in out/_global/llm.txt (read by current()).
|
||||
def choose(vision_key, text_key): CHOICE.write_text(f"{vision_key} {text_key}")
|
||||
def choose(vision_key, text_key):
|
||||
CHOICE_FILE.write_text(f"{vision_key} {text_key}")
|
||||
|
||||
|
||||
def content(resp, what):
|
||||
"""Message text of a llama-server chat response; prints its speed (lands in the Prefect log via log_prints)."""
|
||||
# llama.cpp reports timings; cloud APIs report usage instead.
|
||||
t = resp.get("timings") or {}
|
||||
timings = resp.get("timings") or {}
|
||||
# Reasoning models: count thinking words for the speed log only.
|
||||
think = len((resp["choices"][0]["message"].get("reasoning_content") or "").split())
|
||||
if t: print(f"llm {what}: prompt {t.get('prompt_n', 0)} tok @ {t.get('prompt_per_second', 0):.0f} t/s, "
|
||||
f"gen {t.get('predicted_n', 0)} tok @ {t.get('predicted_per_second', 0):.1f} t/s" + (f" (thinking ~{think} words)" if think else ""), flush=True)
|
||||
elif resp.get("usage"): print(f"llm {what}: prompt {resp['usage'].get('prompt_tokens', 0)} tok, gen {resp['usage'].get('completion_tokens', 0)} tok (cloud)", flush=True)
|
||||
if timings:
|
||||
print(
|
||||
f"llm {what}: prompt {timings.get('prompt_n', 0)} tok @ {timings.get('prompt_per_second', 0):.0f} t/s, "
|
||||
f"gen {timings.get('predicted_n', 0)} tok @ {timings.get('predicted_per_second', 0):.1f} t/s"
|
||||
+ (f" (thinking ~{think} words)" if think else ""),
|
||||
flush=True,
|
||||
)
|
||||
elif resp.get("usage"):
|
||||
print(
|
||||
f"llm {what}: prompt {resp['usage'].get('prompt_tokens', 0)} tok, gen {resp['usage'].get('completion_tokens', 0)} tok (cloud)",
|
||||
flush=True,
|
||||
)
|
||||
return resp["choices"][0]["message"]["content"]
|
||||
|
||||
|
||||
# Health probe: llama-server answers /health once the model is loaded.
|
||||
def up(port=PORT):
|
||||
try: _open(f"http://127.0.0.1:{port}/health", timeout=2); return True
|
||||
except Exception: return False
|
||||
try:
|
||||
_open(f"http://127.0.0.1:{port}/health", timeout=2)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# Launch llama-server on port and wait until /health answers. Returns the Popen, or None if already up.
|
||||
def _spawn(args, port, log):
|
||||
# Already serving on this port: reuse it instead of starting a second copy.
|
||||
if up(port): return None
|
||||
if up(port):
|
||||
return None
|
||||
# Log to a file, not a pipe: nothing reads a pipe here, so the server would block once it fills.
|
||||
p = subprocess.Popen([str(SERVER), *args, "--port", str(port)], stdout=open(log, "w"), stderr=subprocess.STDOUT)
|
||||
process = subprocess.Popen(
|
||||
[str(SERVER), *args, "--port", str(port)],
|
||||
stdout=open(log, "w"), # noqa: SIM115
|
||||
stderr=subprocess.STDOUT, # noqa: SIM115
|
||||
)
|
||||
# Poll every 2 s for up to 20 min: large models take minutes to load.
|
||||
for _ in range(600):
|
||||
if up(port): return p
|
||||
if up(port):
|
||||
return process
|
||||
# Server exited (bad args, out of memory): fail now instead of waiting out the timeout.
|
||||
assert p.poll() is None, f"llama-server died, see {log}"
|
||||
assert process.poll() is None, f"llama-server died, see {log}"
|
||||
time.sleep(2)
|
||||
raise TimeoutError("llama-server not ready")
|
||||
|
||||
|
||||
def start(vision=True, port=PORT, log="llama.log"):
|
||||
"""Start llama-server with current() model; vision=False: text profile (no mmproj). None if already running."""
|
||||
# Cloud choice from the GUI: no local server to start.
|
||||
if current(vision) in REMOTE: return None
|
||||
if current(vision) in REMOTE:
|
||||
return None
|
||||
# MODELS entry: (label, model, mmproj, vision args, text args).
|
||||
_, model, mmproj, vargs, targs = MODELS[current(vision)]
|
||||
_, model, mmproj, vision_args, text_args = MODELS[current(vision)]
|
||||
# Vision: mmproj for images. Text: no mmproj. --jinja applies the model's chat template.
|
||||
return _spawn(["-m", str(model), *(["--mmproj", str(mmproj), *_fit(vargs, True)] if vision else _fit(targs, False)), "--jinja"], port, log)
|
||||
return _spawn(
|
||||
[
|
||||
"-m",
|
||||
str(model),
|
||||
*(
|
||||
["--mmproj", str(mmproj), *_fit(vision_args, True)]
|
||||
if vision
|
||||
else _fit(text_args, False)
|
||||
),
|
||||
"--jinja",
|
||||
],
|
||||
port,
|
||||
log,
|
||||
)
|
||||
|
||||
|
||||
def start_embed(log="embed.log"):
|
||||
"""bge-m3 embeddings on CPU (never competes with the GPU model). None if already running."""
|
||||
if not EMBED.exists(): raise FileNotFoundError(f"{EMBED} missing: hf download gpustack/bge-m3-GGUF bge-m3-Q8_0.gguf --local-dir models")
|
||||
if not EMBED.exists():
|
||||
raise FileNotFoundError(
|
||||
f"{EMBED} missing: hf download gpustack/bge-m3-GGUF bge-m3-Q8_0.gguf --local-dir models"
|
||||
)
|
||||
# bge-m3 on CPU only (-ngl 0, -dev none); 8k context; CLS pooling as bge-m3 expects.
|
||||
return _spawn(["-m", str(EMBED), "--embeddings", "--pooling", "cls", "-ngl", "0", "-dev", "none", "-c", "8192", "-b", "2048", "-ub", "2048"], EMBED_PORT, log)
|
||||
return _spawn(
|
||||
[
|
||||
"-m",
|
||||
str(EMBED),
|
||||
"--embeddings",
|
||||
"--pooling",
|
||||
"cls",
|
||||
"-ngl",
|
||||
"0",
|
||||
"-dev",
|
||||
"none",
|
||||
"-c",
|
||||
"8192",
|
||||
"-b",
|
||||
"2048",
|
||||
"-ub",
|
||||
"2048",
|
||||
],
|
||||
EMBED_PORT,
|
||||
log,
|
||||
)
|
||||
|
||||
|
||||
# Latest stable omp build metadata (JSON with download URL and sha256).
|
||||
OMP_BUILD = "https://build.stencil.so/api/products/omp/latest/windows-x86_64?channel=stable"
|
||||
@@ -307,47 +667,93 @@ MODELS_YML = """providers:
|
||||
headers: *copilot_headers
|
||||
"""
|
||||
|
||||
|
||||
def install_omp():
|
||||
"""omp into bin/ unless one is already available; seed ~/.omp/agent/models.yml (Copilot BYOK models) only if absent."""
|
||||
if omp_exe(): print("omp already available:", omp_exe())
|
||||
if omp_exe():
|
||||
print("omp already available:", omp_exe())
|
||||
else:
|
||||
OMP_LOCAL.parent.mkdir(exist_ok=True)
|
||||
ua = {"User-Agent": "teams-whisper-install"} # the build API answers 403 to python-urllib's default UA
|
||||
j = json.load(_ropen()(urllib.request.Request(OMP_BUILD, headers=ua), timeout=60)); part = OMP_LOCAL.with_suffix(".part"); h = hashlib.sha256()
|
||||
headers = {
|
||||
"User-Agent": "teams-whisper-install"
|
||||
} # the build API answers 403 to python-urllib's default UA
|
||||
build_info = json.load(
|
||||
_ropen()(urllib.request.Request(OMP_BUILD, headers=headers), timeout=60)
|
||||
)
|
||||
part = OMP_LOCAL.with_suffix(".part")
|
||||
digest = hashlib.sha256()
|
||||
# Stream into .part while hashing; rename only after the sha256 check passes.
|
||||
with _ropen()(urllib.request.Request(j["download"], headers=ua), timeout=900) as r, open(part, "wb") as f:
|
||||
while b := r.read(1 << 20): h.update(b); f.write(b)
|
||||
if h.hexdigest() != j["file"]["sha256"].lower(): part.unlink(); raise RuntimeError("omp download: checksum mismatch")
|
||||
part.replace(OMP_LOCAL); print("omp", j["build"]["version"], "->", OMP_LOCAL)
|
||||
y = Path.home() / ".omp" / "agent" / "models.yml"
|
||||
if y.exists(): print("kept existing", y)
|
||||
else: y.parent.mkdir(parents=True, exist_ok=True); y.write_text(MODELS_YML, encoding="utf-8"); print("written", y)
|
||||
with (
|
||||
_ropen()(
|
||||
urllib.request.Request(build_info["download"], headers=headers), timeout=900
|
||||
) as response,
|
||||
open(part, "wb") as out_file,
|
||||
):
|
||||
while chunk := response.read(1 << 20):
|
||||
digest.update(chunk)
|
||||
out_file.write(chunk)
|
||||
if digest.hexdigest() != build_info["file"]["sha256"].lower():
|
||||
part.unlink()
|
||||
raise RuntimeError("omp download: checksum mismatch")
|
||||
part.replace(OMP_LOCAL)
|
||||
print("omp", build_info["build"]["version"], "->", OMP_LOCAL)
|
||||
models_yml = Path.home() / ".omp" / "agent" / "models.yml"
|
||||
if models_yml.exists():
|
||||
print("kept existing", models_yml)
|
||||
else:
|
||||
models_yml.parent.mkdir(parents=True, exist_ok=True)
|
||||
models_yml.write_text(MODELS_YML, encoding="utf-8")
|
||||
print("written", models_yml)
|
||||
|
||||
|
||||
def login(provider, if_needed=False):
|
||||
"""Interactive `omp login` in this console with the proxy env; if_needed: skip when omp already hands out a valid token (install)."""
|
||||
exe = omp_exe()
|
||||
if not exe: raise RuntimeError("omp non installato: esegui Install da Pinokio")
|
||||
omp_path = omp_exe()
|
||||
if not omp_path:
|
||||
raise RuntimeError("omp non installato: esegui Install da Pinokio")
|
||||
# if_needed: skip the interactive login when a token is already available.
|
||||
if if_needed:
|
||||
try: _token(provider); print(provider, "already logged in"); return
|
||||
except RuntimeError: pass
|
||||
subprocess.run([exe, "login", provider], env=omp_env()) # inherits stdin/stdout: device code / browser URL shown in the Pinokio terminal
|
||||
try:
|
||||
_token(provider)
|
||||
print(provider, "already logged in")
|
||||
return
|
||||
except RuntimeError:
|
||||
pass
|
||||
subprocess.run(
|
||||
[omp_path, "login", provider], env=omp_env()
|
||||
) # inherits stdin/stdout: device code / browser URL shown in the Pinokio terminal
|
||||
|
||||
def download(url, dest):
|
||||
|
||||
def download(source_url, dest):
|
||||
"""Proxy-aware, resumable file download (Pinokio's fs.download goes direct and fails where corp DNS only resolves via the proxy; hf's own TLS stack rejects the corp CA). Skips an existing dest."""
|
||||
dest = Path(dest)
|
||||
if dest.exists(): print("kept", dest); return
|
||||
dest.parent.mkdir(parents=True, exist_ok=True); part = dest.with_name(dest.name + ".part")
|
||||
if dest.exists():
|
||||
print("kept", dest)
|
||||
return
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
part = dest.with_name(dest.name + ".part")
|
||||
# Resume: bytes already in .part; ask the server for the rest (Range header).
|
||||
have = part.stat().st_size if part.exists() else 0
|
||||
h = {"User-Agent": "teams-whisper-install", **({"Range": f"bytes={have}-"} if have else {})}
|
||||
headers = {
|
||||
"User-Agent": "teams-whisper-install",
|
||||
**({"Range": f"bytes={have}-"} if have else {}),
|
||||
}
|
||||
# Append only if the server honored Range (206); otherwise restart the file.
|
||||
with _ropen()(urllib.request.Request(url, headers=h), timeout=900) as r, open(part, "ab" if have and r.status == 206 else "wb") as f: shutil.copyfileobj(r, f, 1 << 20)
|
||||
part.replace(dest); print("downloaded", dest)
|
||||
with (
|
||||
_ropen()(urllib.request.Request(source_url, headers=headers), timeout=900) as response,
|
||||
open(part, "ab" if have and response.status == 206 else "wb") as out_file,
|
||||
):
|
||||
shutil.copyfileobj(response, out_file, 1 << 20)
|
||||
part.replace(dest)
|
||||
print("downloaded", dest)
|
||||
|
||||
|
||||
# CLI entry point: `install-omp`, `login <provider> [--if-needed]`, `download <url> <dest>`.
|
||||
if __name__ == "__main__":
|
||||
a = sys.argv[1:]
|
||||
if a == ["install-omp"]: install_omp()
|
||||
elif a[:1] == ["login"]: login(a[1], "--if-needed" in a)
|
||||
elif a[:1] == ["download"]: download(a[1], a[2])
|
||||
args = sys.argv[1:]
|
||||
if args == ["install-omp"]:
|
||||
install_omp()
|
||||
elif args[:1] == ["login"]:
|
||||
login(args[1], "--if-needed" in args)
|
||||
elif args[:1] == ["download"]:
|
||||
download(args[1], args[2])
|
||||
|
||||
Reference in New Issue
Block a user