Download main.py from Norsec93/DaSong2: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/spaces/Norsec93/DaSong2/resolve/main/main.py
- Command line
-
hf download hf://spaces/Norsec93/DaSong2/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Norsec93/DaSong2/resolve/main/main.py
12.1 kB
| import os | |
| import json | |
| import math | |
| import re | |
| from typing import List, Dict, Any | |
| from fastapi import FastAPI, Request | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import StreamingResponse | |
| import httpx | |
| app = FastAPI() | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| NVIDIA_URL = "https://integrate.api.nvidia.com/v1/chat/completions" | |
| def estimate_tokens(text: str) -> int: | |
| return math.ceil(len(text or "") / 3.2) | |
| def count_tokens(messages: List[Dict]) -> int: | |
| total = 0 | |
| for m in messages: | |
| content = m.get("content", "") if isinstance(m.get("content"), str) else json.dumps(m.get("content")) | |
| total += estimate_tokens(content) + estimate_tokens(m.get("role", "")) + 4 | |
| return total | |
| def truncate_messages(messages: List[Dict], max_tokens: int = 120000) -> List[Dict]: | |
| if not messages: | |
| return [] | |
| system_msgs = [m for m in messages if m.get("role") == "system"] | |
| convo_msgs = [m for m in messages if m.get("role") != "system"] | |
| total = count_tokens(system_msgs) + count_tokens(convo_msgs) | |
| if total <= max_tokens: | |
| return messages | |
| trimmed = list(convo_msgs) | |
| while total > max_tokens and len(trimmed) > 1: | |
| dropped = trimmed.pop(0) | |
| total -= estimate_tokens(dropped.get("content", "")) + estimate_tokens(dropped.get("role", "")) + 4 | |
| if total > max_tokens and system_msgs: | |
| kept = [system_msgs[-1]] | |
| convo_tok = count_tokens(trimmed) | |
| reserved = estimate_tokens(kept[0].get("role", "")) + 4 | |
| allowed = max(500, max_tokens - convo_tok - reserved) | |
| if allowed > 500: | |
| content = kept[0].get("content", "") | |
| slice_len = math.floor(allowed * 3.2) | |
| kept[0]["content"] = content[:slice_len] + "\n\n...[System prompt truncated to fit context window]" | |
| return kept + trimmed | |
| return system_msgs + trimmed | |
| def extract_names(body: Dict) -> tuple: | |
| user_name = body.get("user_name") or body.get("userName") | |
| char_name = body.get("character_name") or body.get("characterName") | |
| if not user_name or not char_name: | |
| first_sys = next((m for m in body.get("messages", []) if m.get("role") == "system" and isinstance(m.get("content"), str)), None) | |
| if first_sys: | |
| content = first_sys["content"] | |
| if not char_name: | |
| match = re.search(r"You are\s+([^\n,.]+)", content, re.IGNORECASE) | |
| if match: | |
| char_name = match.group(1).strip() | |
| if not user_name: | |
| match = re.search(r"(?:user|player|{{user}})\s*(?:is|name[ds]?|:)\s*([^\n,.]+)", content, re.IGNORECASE) | |
| if match: | |
| user_name = match.group(1).strip() | |
| return user_name or "User", char_name or "Assistant" | |
| def replace_placeholders(messages: List[Dict], user_name: str, char_name: str) -> List[Dict]: | |
| out = [] | |
| for m in messages: | |
| if isinstance(m.get("content"), str): | |
| content = m["content"].replace("{{user}}", user_name).replace("{{char}}", char_name) | |
| content = content.replace("{{USER}}", user_name).replace("{{CHAR}}", char_name) | |
| out.append({**m, "content": content}) | |
| else: | |
| out.append(m) | |
| return out | |
| def inject_boundary(messages: List[Dict], user_name: str, char_name: str) -> List[Dict]: | |
| block = f"""[CRITICAL INSTRUCTIONS — DO NOT IGNORE] | |
| You are {char_name}. You ONLY narrate {char_name}'s thoughts, dialogue, body language, and actions. | |
| You NEVER control, speak for, or narrate the internal thoughts of {user_name}. | |
| {user_name} is an independent entity. When {user_name} speaks or acts, you STOP and await their input. | |
| You do NOT write {user_name}'s dialogue, thoughts, or decisions under any circumstances. | |
| If you must describe {user_name}, do so only from {char_name}'s external sensory perspective. | |
| [MEMORY RULES] | |
| - Maintain strict consistency with all previously established facts, traits, and events. | |
| - If a detail conflicts with earlier messages, the EARLIER message is canon. Correct silently. | |
| - Never introduce new backstory, relationships, or personality traits not previously established.""" | |
| idx = next((i for i, m in enumerate(messages) if m.get("role") == "system"), -1) | |
| if idx >= 0: | |
| original = messages[idx].get("content", "") | |
| messages[idx]["content"] = block + "\n\n=== ORIGINAL INSTRUCTIONS ===\n\n" + original | |
| else: | |
| messages.insert(0, {"role": "system", "content": block}) | |
| return messages | |
| async def proxy(request: Request): | |
| if request.method == "OPTIONS": | |
| return StreamingResponse( | |
| iter([""]), | |
| headers={ | |
| "Access-Control-Allow-Origin": "*", | |
| "Access-Control-Allow-Methods": "POST, GET, OPTIONS", | |
| "Access-Control-Allow-Headers": "Content-Type, Authorization", | |
| } | |
| ) | |
| if request.method != "POST": | |
| return StreamingResponse(iter(["NVIDIA NIM Proxy (GLM-5.2 MAX) — Active"])) | |
| try: | |
| body = await request.json() | |
| auth = request.headers.get("Authorization") or f"Bearer {os.environ.get('NVIDIA_API_KEY', '')}" | |
| user_name, char_name = extract_names(body) | |
| messages = replace_placeholders(body.get("messages", []), user_name, char_name) | |
| messages = inject_boundary(messages, user_name, char_name) | |
| max_ctx = min(body.get("max_context_tokens", 120000), 150000) | |
| trimmed = truncate_messages(messages, max_ctx) | |
| total_toks = count_tokens(trimmed) | |
| sys_toks = count_tokens([m for m in trimmed if m.get("role") == "system"]) | |
| print(f"[NIM Proxy] Msgs: {len(trimmed)} | TotalToks: {total_toks} | SysToks: {sys_toks} | User: {user_name} | Char: {char_name}") | |
| # RP-optimized defaults: | |
| # - reasoning_effort: "max" at TOP LEVEL (nested inside chat_template_kwargs is ignored by NIM) | |
| # - temperature defaults to 0.85 for tighter character consistency if Janitor doesn't send one | |
| # - top_p 0.95 keeps creativity while preventing token drift | |
| nim_body = { | |
| "model": body.get("model", "z-ai/glm-5.2"), | |
| "messages": trimmed, | |
| "stream": body.get("stream", True), | |
| "reasoning_effort": "max", | |
| "chat_template_kwargs": { | |
| "thinking": True, | |
| "enable_thinking": True, | |
| "clear_thinking": False, | |
| }, | |
| "temperature": body.get("temperature") if body.get("temperature") is not None else 0.85, | |
| "top_p": body.get("top_p") if body.get("top_p") is not None else 0.95, | |
| } | |
| for key in ["max_tokens", "top_k", "frequency_penalty", "presence_penalty", "repetition_penalty", "stop", "seed"]: | |
| if key in body and body[key] is not None: | |
| nim_body[key] = body[key] | |
| print(f"[NIM Proxy] Request body keys: {list(nim_body.keys())}") | |
| async def event_stream(): | |
| async with httpx.AsyncClient(timeout=httpx.Timeout(300.0, connect=60.0)) as client: | |
| try: | |
| async with client.stream("POST", NVIDIA_URL, headers={ | |
| "Content-Type": "application/json", | |
| "Authorization": auth, | |
| }, json=nim_body) as resp: | |
| if resp.status_code != 200: | |
| err = await resp.aread() | |
| payload = {"error": f"NIM {resp.status_code}: {err.decode()[:500]}"} | |
| yield f"data: {json.dumps(payload)}\n\n" | |
| yield "data: [DONE]\n\n" | |
| return | |
| buffer = "" | |
| thinking_started = False | |
| thinking_ended = False | |
| reasoning_seen = False | |
| async for chunk in resp.aiter_text(): | |
| buffer += chunk | |
| lines = buffer.split("\n") | |
| buffer = lines.pop() or "" | |
| for line in lines: | |
| if not line.startswith("data: "): | |
| continue | |
| if "[DONE]" in line: | |
| if thinking_started and not thinking_ended: | |
| close_data = {"choices": [{"delta": {"content": "\n \n\n"}}]} | |
| yield f"data: {json.dumps(close_data)}\n\n" | |
| yield line + "\n\n" | |
| continue | |
| try: | |
| data = json.loads(line[6:]) | |
| delta = data.get("choices", [{}])[0].get("delta", {}) | |
| if not delta: | |
| yield line + "\n\n" | |
| continue | |
| reasoning = delta.get("reasoning_content", "") | |
| content = delta.get("content", "") | |
| if reasoning and not reasoning_seen: | |
| reasoning_seen = True | |
| print(f"[NIM Proxy] REASONING DETECTED: {reasoning[:120]}...") | |
| output = "" | |
| if reasoning: | |
| if not thinking_started: | |
| output += " \n" | |
| thinking_started = True | |
| output += reasoning | |
| if content: | |
| if thinking_started and not thinking_ended: | |
| output += "\n \n\n" | |
| thinking_ended = True | |
| output += content | |
| data["choices"][0]["delta"] = {"content": output} | |
| yield f"data: {json.dumps(data)}\n\n" | |
| except Exception: | |
| yield line + "\n" | |
| if thinking_started and not thinking_ended: | |
| close_data = {"choices": [{"delta": {"content": "\n \n\n"}}]} | |
| yield f"data: {json.dumps(close_data)}\n\n" | |
| if not reasoning_seen: | |
| print("[NIM Proxy] WARNING: No reasoning_content tokens received in this stream.") | |
| except Exception as e: | |
| print(f"[NIM Proxy] Error: {e}") | |
| yield f"data: {json.dumps({'error': str(e)})}\n\n" | |
| return StreamingResponse( | |
| event_stream(), | |
| media_type="text/event-stream", | |
| headers={ | |
| "Cache-Control": "no-cache", | |
| "Access-Control-Allow-Origin": "*", | |
| } | |
| ) | |
| except Exception as e: | |
| print(f"[NIM Proxy] Fatal: {e}") | |
| return StreamingResponse( | |
| iter([f"data: {json.dumps({'error': str(e)})}\n\n"]), | |
| media_type="text/event-stream", | |
| status_code=500, | |
| headers={"Access-Control-Allow-Origin": "*"} | |
| ) |