MorseAI's picture
Link tags: hf-space
43e404f verified
Raw History Blame Contribute Delete
8.97 kB
"""Morse API Playground: a Hugging Face Space that calls open models on the Morse API.
The Space calls Morse from its server, never from the browser. It pays for a few low-cost
models with its own capped key (Space secret MORSE_API_KEY). Every other model, uncensored
ones included, runs only on the visitor's own Morse key, pasted into the Key box. The Space
keeps no chat history and never saves a key.
"""
import os
import time
import collections
import threading
import gradio as gr
import httpx
from openai import OpenAI, APIStatusError, APIConnectionError
BASE_URL = os.environ.get("MORSE_BASE_URL", "https://inference.trymorse.ai/v1")
HOUSE_KEY = os.environ.get("MORSE_API_KEY", "")
LINK_TAG = os.environ.get("LINK_TAG", "hf-space")
MAX_TOKENS = int(os.environ.get("MAX_TOKENS", "1024"))
PER_HOUR = int(os.environ.get("MESSAGES_PER_HOUR", "20"))
# Low-cost, not uncensored. Any id that isn't live in /v1/models is dropped at start.
# The Space's own key may call only these three; the key itself can't be limited to models, so the code is the limit.
# Not configurable on purpose: every other model, uncensored ones included, needs the visitor's own key.
HOUSE_MODELS_WANTED = [
"google/gemma-4-26b-a4b-it",
"z-ai/glm-5.3-flash",
"deepseek/deepseek-v4.1-flash-1017",
]
KEY_URL = f"https://trymorse.ai/inference?src={LINK_TAG}"
MODELS_URL = f"https://trymorse.ai/inference/models?src={LINK_TAG}"
# Uncensored models lead the list (they're why people come); these go first when live, then any other uncensored one.
UNCENSORED_FIRST = [
"qwen/qwen3.8-27b-uncensored",
"deepseek/deepseek-v4.1-flash-1017-abliterated",
"z-ai/glm-5.3-uncensored",
"moonshotai/kimi-k3.1-pro-uncensored",
"z-ai/glm-5.3-flash-uncensored",
"google/gemma-4-26b-a4b-uncensored",
]
def load_models():
"""Read the live model list (no key needed). Returns (uncensored, house, other) lists of (label, id)."""
try:
r = httpx.get(f"{BASE_URL}/models", timeout=20)
r.raise_for_status()
data = r.json().get("data", [])
except Exception:
data = []
chat = [m for m in data if m.get("type", "chat") == "chat" and not m.get("superseded_by")]
live = {m["id"]: m for m in chat}
house_ids = [m for m in HOUSE_MODELS_WANTED if m in live] or (HOUSE_MODELS_WANTED if not live else [])
house = [(f"{live.get(m, {}).get('label', m)} (free here)", m) for m in house_ids]
unc_all = [m for m in chat if m.get("uncensored") and m["id"] not in house_ids]
rank = {mid: i for i, mid in enumerate(UNCENSORED_FIRST)}
unc_all.sort(key=lambda x: (rank.get(x["id"], len(rank)), x.get("lab", ""), x.get("label", x["id"])))
unc = [(f"{m.get('label', m['id'])} (uncensored, your key)", m["id"]) for m in unc_all]
other = []
for m in sorted(chat, key=lambda x: (x.get("lab", ""), x.get("label", x["id"]))):
if m["id"] in house_ids or m.get("uncensored"):
continue
other.append((f"{m.get('label', m['id'])} (your key)", m["id"]))
return unc, house, other
UNC, HOUSE, OTHER = load_models()
HOUSE_IDS = {mid for _, mid in HOUSE}
UNC_IDS = {mid for _, mid in UNC}
CHOICES = UNC + HOUSE + OTHER
# The chat works on the first message without a key, so a free model is selected; the uncensored ones sit above it.
DEFAULT = HOUSE[0][1] if HOUSE else (CHOICES[0][1] if CHOICES else None)
UNC_NAMES = ", ".join(label.split(" (")[0] for label, _ in UNC[:4])
_hits = collections.defaultdict(collections.deque)
_lock = threading.Lock()
def allowed(ip: str) -> bool:
"""At most PER_HOUR messages an hour per visitor on the Space's own key."""
now = time.time()
with _lock:
q = _hits[ip]
while q and now - q[0] > 3600:
q.popleft()
if len(q) >= PER_HOUR:
return False
q.append(now)
return True
def visitor_ip(request) -> str:
if request is None:
return "unknown"
fwd = (request.headers or {}).get("x-forwarded-for", "")
if fwd:
return fwd.split(",")[0].strip()
return getattr(request.client, "host", "unknown") or "unknown"
def to_messages(message, history):
msgs = []
for turn in history or []:
if isinstance(turn, dict):
content = turn.get("content")
if isinstance(content, str) and turn.get("role") in ("user", "assistant"):
msgs.append({"role": turn["role"], "content": content})
elif isinstance(turn, (list, tuple)) and len(turn) == 2:
if turn[0]:
msgs.append({"role": "user", "content": str(turn[0])})
if turn[1]:
msgs.append({"role": "assistant", "content": str(turn[1])})
text = message.get("text", "") if isinstance(message, dict) else str(message)
msgs.append({"role": "user", "content": text})
return msgs
def chat(message, history, model, own_key, request: gr.Request):
own_key = (own_key or "").strip()
if not model:
yield "No models loaded. Try again in a minute."
return
if own_key:
key = own_key
elif model in HOUSE_IDS and HOUSE_KEY:
if not allowed(visitor_ip(request)):
yield f"That's the hourly limit for the free models here. Paste your own Morse key to keep going: [get one]({KEY_URL})."
return
key = HOUSE_KEY
elif model in UNC_IDS:
yield (
f"Uncensored models run on your own Morse key. Paste it in the Key box below. "
f"[Get a key at trymorse.ai/inference]({KEY_URL}), pay as you go."
)
return
else:
yield (
f"This model runs on your own Morse key. Paste it in the Key box below "
f"([get a key]({KEY_URL}), pay as you go). The models marked \"free here\" work without one."
)
return
client = OpenAI(base_url=BASE_URL, api_key=key, timeout=120, max_retries=0)
out = ""
try:
stream = client.chat.completions.create(
model=model,
messages=to_messages(message, history),
max_tokens=MAX_TOKENS,
stream=True,
)
for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta
piece = getattr(delta, "content", None) if delta else None
if piece:
out += piece
yield out
if not out:
yield "(The model returned no text. Try again or pick another model.)"
except APIStatusError as e:
code = getattr(e, "status_code", None)
if code == 401:
yield "That key didn't work. Check it on the console, or clear the Key box to use the free models."
elif code == 402 and key == HOUSE_KEY:
yield f"The free models here are out of credits. Paste your own Morse key to keep going: [get one]({KEY_URL})."
elif code == 402:
yield f"Your key is out of credits or hit its spend limit. [Add credits]({KEY_URL})."
elif code == 429:
yield "Too many requests right now. Wait a few seconds and try again."
else:
yield f"Morse returned an error ({code}). Try again or pick another model."
except APIConnectionError:
yield "Couldn't reach Morse. Try again in a moment."
INTRO = f"""
# Morse API Playground
**Uncensored models on a private, OpenAI-compatible API.** Access abliterated models through one gateway for frontier work in cybersecurity and research. {UNC_NAMES} and more run on [Morse]({KEY_URL}). Paste your Morse key below to try them here.
"""
AFTER_BUTTON = f"""
No key yet? The models marked **free here** work without one, so you can try the API first. [See every model]({MODELS_URL}).
```python
from openai import OpenAI
client = OpenAI(base_url="https://inference.trymorse.ai/v1", api_key="sk_morse_...")
```
This Space keeps no chat history and never saves your key.
"""
with gr.Blocks(title="Morse API Playground") as demo:
gr.Markdown(INTRO)
# A plain link opening a new tab: a Gradio button link would load trymorse.ai inside the Space's frame.
gr.HTML(
f'<a href="{KEY_URL}" target="_blank" rel="noopener" style="display:block;text-align:center;padding:12px 16px;'
f'border-radius:8px;background:#2563eb;color:#fff;font-weight:600;text-decoration:none">'
f'Get a key at trymorse.ai/inference</a>'
)
gr.Markdown(AFTER_BUTTON)
model = gr.Dropdown(choices=CHOICES, value=DEFAULT, label="Model", render=False)
own_key = gr.Textbox(label="Key (optional)", placeholder="sk_morse_...", type="password", render=False)
gr.ChatInterface(
fn=chat,
additional_inputs=[model, own_key],
additional_inputs_accordion=gr.Accordion("Model and key", open=True, render=False),
)
if __name__ == "__main__":
demo.queue(default_concurrency_limit=8).launch(theme=gr.themes.Soft(primary_hue="sky", neutral_hue="slate"))