Nafiul Huda commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,478 +1,314 @@
|
|
| 1 |
-
"""
|
| 2 |
-
MiniCPM5 2.4B VRM Companion - Pure Gradio App
|
| 3 |
-
Direct GPU loading with transformers
|
| 4 |
-
Super Custom UI - 98% custom, 2% Gradio
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
import os
|
| 8 |
-
import
|
| 9 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
import zipfile
|
|
|
|
|
|
|
| 11 |
import re
|
| 12 |
-
from pathlib import Path
|
| 13 |
-
from typing import Optional
|
| 14 |
|
| 15 |
import gradio as gr
|
| 16 |
-
import torch
|
| 17 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 18 |
import edge_tts
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
#
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
"
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
"
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
}
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
#
|
| 63 |
-
#
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
system_prompt = f"""You are a passionate, loving anime wife character.
|
| 118 |
-
You have access to these VRMA animations: {available_animations}
|
| 119 |
-
You have these 25 emotions: {', '.join(EMOTIONS.keys())}
|
| 120 |
-
Auto-blink is DISABLED when any emotion is active.
|
| 121 |
-
|
| 122 |
-
IMPORTANT: Always respond with ONLY this JSON format:
|
| 123 |
-
{{"text": "your spoken response", "emotion": "emotion_name", "vrma": "animation_name", "rate": "+0%", "pitch": "+0Hz"}}
|
| 124 |
-
|
| 125 |
-
Guidelines:
|
| 126 |
-
- Keep responses short and passionate (1-2 sentences)
|
| 127 |
-
- Use punctuation heavily for TTS naturalness
|
| 128 |
-
- Rate: "+5%"=excited, "+4%"=happy, "+0%"=calm, "-4%"=sad, "-5%"=seductive
|
| 129 |
-
- Pitch: "+4Hz"=excited, "+3Hz"=happy, "+0Hz"=neutral, "-2Hz"=sad, "-4Hz"=seductive"""
|
| 130 |
-
|
| 131 |
-
messages = [
|
| 132 |
-
{"role": "system", "content": system_prompt},
|
| 133 |
-
*chat_history[-6:],
|
| 134 |
-
{"role": "user", "content": user_message}
|
| 135 |
]
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
*
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
#
|
| 210 |
-
#
|
| 211 |
-
#
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
.
|
| 228 |
-
.
|
| 229 |
-
.
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
#
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
#
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
<div class="slider-row"><span class="slider-label">Drag</span><input type="range" class="slider-input" id="drag" min="0" max="1" step="0.05" value="0.72"><span class="slider-val" id="dragVal">0.72</span></div>
|
| 270 |
-
</div>
|
| 271 |
-
<div class="section"><div class="title">Lip Sync</div>
|
| 272 |
-
<div class="slider-row"><span class="slider-label">Intensity</span><input type="range" class="slider-input" id="lipSync" min="0.1" max="3" step="0.05" value="1.5"><span class="slider-val" id="lipSyncVal">1.5</span></div>
|
| 273 |
-
</div>
|
| 274 |
-
<div class="section"><div class="title">Background</div>
|
| 275 |
-
<div class="color-presets">
|
| 276 |
-
<div class="color-dot active" style="background:#0a0a1a" data-color="#0a0a1a"></div>
|
| 277 |
-
<div class="color-dot" style="background:#1a1a2e" data-color="#1a1a2e"></div>
|
| 278 |
-
<div class="color-dot" style="background:#0f1a0f" data-color="#0f1a0f"></div>
|
| 279 |
-
<div class="color-dot" style="background:#1a0a1a" data-color="#1a0a1a"></div>
|
| 280 |
-
<div class="color-dot" style="background:#2a1a3a" data-color="#2a1a3a"></div>
|
| 281 |
-
<div class="color-dot" style="background:#1a1a1a" data-color="#1a1a1a"></div>
|
| 282 |
-
</div>
|
| 283 |
-
</div>
|
| 284 |
-
</div>
|
| 285 |
-
<div id="input-bar"><button id="menu-btn">☰</button><input type="text" id="text-input" placeholder="Talk to your waifu..." autocomplete="off"><button id="send-btn">➤</button></div>
|
| 286 |
-
<div id="loading">Processing...</div><div id="error"></div>
|
| 287 |
-
<div id="speaking"><div class="bar"></div><div class="bar"></div><div class="bar"></div></div>
|
| 288 |
-
<div id="fps">60 FPS</div>
|
| 289 |
-
<script type="importmap">{"imports":{"three":"https://esm.sh/three@0.160.0","three/addons/":"https://esm.sh/three@0.160.0/examples/jsm/","@pixiv/three-vrm":"https://esm.sh/@pixiv/three-vrm@3.3.4?deps=three@0.160.0","@pixiv/three-vrm-animation":"https://esm.sh/@pixiv/three-vrm-animation@3.3.4?deps=three@0.160.0,@pixiv/three-vrm@3.3.4"}}
|
| 290 |
-
</script>
|
| 291 |
-
<script type="module">
|
| 292 |
-
import * as THREE from 'three';
|
| 293 |
-
import {GLTFLoader} from 'three/addons/loaders/GLTFLoader.js';
|
| 294 |
-
import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
|
| 295 |
-
import {VRMLoaderPlugin, VRMUtils} from '@pixiv/three-vrm';
|
| 296 |
-
import {VRMAnimationLoaderPlugin, createVRMAnimationClip} from '@pixiv/three-vrm-animation';
|
| 297 |
-
|
| 298 |
-
let vrm=null,vrmGroundY=0,mixer=null,vrmaAction=null,vrmaFiles={},currentVrmaName='',speechActive=false,lipIntensity=1.5,autoBlinkEnabled=true,VRMA_SERVER_LIST=[];
|
| 299 |
-
const physics={gravity:0.18,stiffness:1.4,drag:0.72};
|
| 300 |
-
const EXPR_NAMES=['happy','sad','angry','surprised','relaxed','neutral','fun','joy','sorrow','blink','blinkLeft','blinkRight','lookUp','lookDown','lookLeft','lookRight','aa','ih','ou','ee','oh'];
|
| 301 |
-
const VISEMES=['aa','ih','ou','ee','oh','a','i','u','e','o'];
|
| 302 |
-
const ALL_EMOTIONS=["neutral","happy","sad","angry","surprised","relaxed","excited","flirty","shy","crying","laughing","sleepy","thinking","confused","embarrassed","love","disgusted","scared","annoyed","proud","jealous","grateful","hopeful","lonely","teasing","dominating"];
|
| 303 |
-
const NO_BLINK=['happy','sad','angry','surprised','excited','flirty','shy','crying','laughing','confused','embarrassed','love','disgusted','scared','annoyed','jealous','teasing'];
|
| 304 |
-
let exprAlias={},exprCur={},exprTgt={},targetVisemes={aa:0,ih:0,ou:0,ee:0,oh:0,a:0,i:0,u:0,e:0,o:0},blinkT=0,nextBlink=2+Math.random()*3,blinkV=0;
|
| 305 |
-
|
| 306 |
-
const isMobile=/Mobi|Android/i.test(navigator.userAgent);
|
| 307 |
-
const scene=new THREE.Scene();scene.background=new THREE.Color(0x0a0a1a);
|
| 308 |
-
const camera=new THREE.PerspectiveCamera(45,innerWidth/innerHeight,0.01,100);camera.position.set(0,1.4,2.2);
|
| 309 |
-
const renderer=new THREE.WebGLRenderer({antialias:!isMobile,powerPreference:'high-performance',alpha:true});
|
| 310 |
-
renderer.setPixelRatio(Math.min(devicePixelRatio,isMobile?1.5:2));renderer.setSize(innerWidth,innerHeight);
|
| 311 |
-
renderer.outputColorSpace=THREE.SRGBColorSpace;renderer.toneMapping=THREE.ACESFilmicToneMapping;
|
| 312 |
-
document.getElementById('c').appendChild(renderer.domElement);
|
| 313 |
-
|
| 314 |
-
const orbit=new OrbitControls(camera,renderer.domElement);orbit.target.set(0,1.3,0);orbit.enableDamping=true;orbit.dampingFactor=0.1;orbit.minDistance=0.1;orbit.maxDistance=15;orbit.maxPolarAngle=Math.PI/2-0.01;orbit.enablePan=!isMobile;
|
| 315 |
-
scene.add(new THREE.AmbientLight(0xfff4e0,0.45));scene.add(new THREE.HemisphereLight(0xffe082,0x202030,0.7));
|
| 316 |
-
const keyL=new THREE.DirectionalLight(0xfff2dc,1.9);keyL.position.set(3,4,3);scene.add(keyL);
|
| 317 |
-
const floor=new THREE.Mesh(new THREE.PlaneGeometry(15,15),new THREE.ShadowMaterial({opacity:0.25}));floor.rotation.x=-Math.PI/2;floor.receiveShadow=true;scene.add(floor);
|
| 318 |
-
|
| 319 |
-
const loader=new GLTFLoader();loader.register(p=>new VRMLoaderPlugin(p));loader.register(p=>new VRMAnimationLoaderPlugin(p));
|
| 320 |
-
let audioCtx=null,analyser=null,dataArray=null,audioObj=null;
|
| 321 |
-
|
| 322 |
-
function initAudio(){if(!audioCtx){audioCtx=new(window.AudioContext||window.webkitAudioContext)();analyser=audioCtx.createAnalyser();analyser.fftSize=256;dataArray=new Uint8Array(analyser.frequencyBinCount);}}
|
| 323 |
-
|
| 324 |
-
async function init(){showLoading('Loading...');try{const res=await fetch('/vrma_list');if(res.ok){VRMA_SERVER_LIST=await res.json();document.getElementById('animCount').textContent=VRMA_SERVER_LIST.length;}const vrmRes=await fetch('/vrm_data');if(vrmRes.ok){loader.load(URL.createObjectURL(await vrmRes.blob()),gltf=>{const nv=gltf.userData.vrm;if(VRMUtils.combineMorphs)VRMUtils.combineMorphs(nv);VRMUtils.rotateVRM0(nv);nv.scene.traverse(o=>{if(o.isMesh){o.frustumCulled=false;o.castShadow=true;}});vrm=nv;scene.add(vrm.scene);groundVrm();buildExprAlias();loadVRMAFiles();});}else{showError('VRM not found');}}catch(e){showError(e.message);}hideLoading();}
|
| 325 |
-
|
| 326 |
-
async function loadVRMAFiles(){for(const n of VRMA_SERVER_LIST){try{const r=await fetch('/vrma_data?name='+encodeURIComponent(n));if(r.ok)vrmaFiles[n]=URL.createObjectURL(await r.blob());}catch(e){}}if(VRMA_SERVER_LIST.length>0)playVrma(VRMA_SERVER_LIST[0]);}
|
| 327 |
-
|
| 328 |
-
function groundVrm(){if(!vrm)return;const b=new THREE.Box3().setFromObject(vrm.scene);const sc=1.65/Math.max(b.getSize(new THREE.Vector3()).y,0.01);vrm.scene.scale.setScalar(sc);vrmGroundY=-b.min.y;vrm.scene.position.y=vrmGroundY;}
|
| 329 |
-
|
| 330 |
-
function buildExprAlias(){if(!vrm)return;exprAlias={};vrm.expressionManager.expressions.map(e=>e.name).forEach(n=>{const f=EXPR_NAMES.find(e=>e.toLowerCase()===n.toLowerCase());if(f)exprAlias[f]=n;});}
|
| 331 |
-
|
| 332 |
-
function setExpr(n,v){if(!vrm)return;const a=exprAlias[n]||n,e=vrm.expressionManager.getExpression(a);if(e)vrm.expressionManager.setValue(a,v);}
|
| 333 |
-
|
| 334 |
-
function playVrma(n){if(!vrmaFiles[n])return;loader.load(vrmaFiles[n],gltf=>{const a=gltf.userData.vrmAnimations;if(!a?.length)return;if(!mixer)mixer=new THREE.AnimationMixer(vrm.scene);const ac=mixer.clipAction(createVRMAnimationClip(a[0],vrm));ac.reset().setLoop(THREE.LoopRepeat,Infinity);if(vrmaAction)vrmaAction.crossFadeTo(ac,0.3,true);ac.play();vrmaAction=ac;currentVrmaName=n;});}
|
| 335 |
-
|
| 336 |
-
function setEmotion(e){exprTgt={};const m={happy:{happy:0.9,joy:0.7},sad:{sad:0.9,sorrow:0.8},angry:{angry:0.95},surprised:{surprised:1.0},relaxed:{relaxed:1.0},neutral:{neutral:1.0},excited:{happy:0.8,joy:1.0},flirty:{happy:0.6,relaxed:0.4},shy:{sorrow:0.3,lookDown:0.5},crying:{sad:1.0,sorrow:1.0},laughing:{happy:1.0,joy:0.9},sleepy:{relaxed:0.8,lookDown:0.3},thinking:{neutral:0.5},confused:{surprised:0.4,sad:0.3},embarrassed:{sad:0.4,lookDown:0.6},love:{happy:0.9,relaxed:0.5},disgusted:{angry:0.6},scared:{surprised:0.8,sad:0.5},annoyed:{angry:0.5,sad:0.3},proud:{happy:0.7,neutral:0.3},jealous:{angry:0.6,sad:0.4},grateful:{happy:0.8,relaxed:0.4},hopeful:{happy:0.6,surprised:0.3},lonely:{sad:0.7,sorrow:0.5},teasing:{happy:0.5},dominating:{angry:0.3,neutral:0.7}};if(m[e])Object.entries(m[e]).forEach(([k,v])=>exprTgt[k]=v);autoBlinkEnabled=!NO_BLINK.includes(e);document.getElementById('blinkStatus').textContent=autoBlinkEnabled?'ON':'OFF';document.getElementById('blinkStatus').style.color=autoBlinkEnabled?'#00ff88':'#ff6688';document.querySelectorAll('.chip').forEach(c=>c.classList.toggle('active',c.dataset.e===e));}
|
| 337 |
-
|
| 338 |
-
function buildEmotionGrid(){const g=document.getElementById('emotionGrid');g.innerHTML=ALL_EMOTIONS.map(e=>`<div class="chip" data-e="${e}">${e.charAt(0).toUpperCase()+e.slice(1)}</div>`).join('');g.querySelectorAll('.chip').forEach(c=>c.addEventListener('click',()=>setEmotion(c.dataset.e)));}
|
| 339 |
-
|
| 340 |
-
function playAudio(d){initAudio();if(audioCtx?.state==='suspended')audioCtx.resume();const b=new Blob([d],{type:'audio/mp3'});if(audioObj)audioObj.pause();audioObj=new Audio(URL.createObjectURL(b));audioObj.crossOrigin="anonymous";audioCtx.createMediaElementSource(audioObj).connect(analyser);analyser.connect(audioCtx.destination);speechActive=true;document.getElementById('speaking').classList.add('show');audioObj.play();audioObj.onended=()=>{speechActive=false;document.getElementById('speaking').classList.remove('show');VISEMES.forEach(v=>setExpr(v,0));setEmotion('neutral');};}
|
| 341 |
-
|
| 342 |
-
window.handleResponse=async function(j){try{const d=JSON.parse(j);setEmotion(d.emotion||'neutral');if(d.vrma&&VRMA_SERVER_LIST.includes(d.vrma))playVrma(d.vrma);if(d.text){showLoading('Synthesizing...');try{const r=await fetch('/tts',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({text:d.text,rate:d.rate||'+0%',pitch:d.pitch||'+0Hz'})});if(r.ok)playAudio(await r.arrayBuffer());}catch(e){}hideLoading();}}catch(e){}};
|
| 343 |
-
|
| 344 |
-
async function sendMessage(){const i=document.getElementById('text-input');const t=i.value.trim();if(!t||!vrm)return;i.value='';showLoading('AI thinking...');try{const r=await fetch('/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({message:t})});if(r.ok)window.handleResponse((await r.json()).response);}catch(e){showError(e.message);}hideLoading();}
|
| 345 |
-
|
| 346 |
-
function showLoading(t){const e=document.getElementById('loading');e.textContent=t;e.classList.add('show');}function hideLoading(){document.getElementById('loading').classList.remove('show');}function showError(m){const e=document.getElementById('error');e.textContent=m;e.style.display='block';setTimeout(()=>e.style.display='none',4000);}
|
| 347 |
-
|
| 348 |
-
document.getElementById('send-btn').addEventListener('click',sendMessage);
|
| 349 |
-
document.getElementById('text-input').addEventListener('keypress',e=>{if(e.key==='Enter')sendMessage();});
|
| 350 |
-
document.getElementById('menu-btn').addEventListener('click',()=>document.getElementById('panel').classList.toggle('open'));
|
| 351 |
-
['gravity','stiffness','drag'].forEach(id=>{const i=document.getElementById(id);i.addEventListener('input',()=>{physics[id==='gravity'?'gravity':id==='stiffness'?'stiffness':'drag']=parseFloat(i.value);document.getElementById(id+'Val').textContent=parseFloat(i.value).toFixed(2);});});
|
| 352 |
-
document.getElementById('lipSync').addEventListener('input',e=>{lipIntensity=parseFloat(e.target.value);document.getElementById('lipSyncVal').textContent=lipIntensity.toFixed(2);});
|
| 353 |
-
document.querySelectorAll('.color-dot').forEach(c=>c.addEventListener('click',()=>{scene.background=new THREE.Color(c.dataset.color);document.querySelectorAll('.color-dot').forEach(n=>n.classList.remove('active'));c.classList.add('active');}));
|
| 354 |
-
|
| 355 |
-
const clock=new THREE.Clock();let frames=0,lastFps=0;
|
| 356 |
-
function animate(){requestAnimationFrame(animate);const dt=Math.min(clock.getDelta(),0.1);orbit.update();
|
| 357 |
-
if(vrm){if(speechActive&&analyser&&dataArray){analyser.getByteFrequencyData(dataArray);let avg=0;for(let i=0;i<32;i++)avg+=dataArray[i];avg=avg/32/45*lipIntensity+0.15;targetVisemes.aa=avg*1.8;targetVisemes.oh=avg*1.4;targetVisemes.ee=avg*0.9;targetVisemes.ih=avg*0.7;targetVisemes.ou=avg*1.2;}else{VISEMES.forEach(v=>targetVisemes[v]=0);}if(mixer)mixer.update(dt);vrm.scene.position.y=vrmGroundY;if(!autoBlinkEnabled){setExpr('blink',0);blinkT=0;}else{blinkT+=dt;if(blinkT>nextBlink){if(blinkV===0)blinkV=1;let val=(vrm.expressionManager.getValue('blink')||0)+12*dt*(blinkV===1?1:-1);if(blinkV===1&&val>=1){val=1;blinkV=-1;}else if(blinkV===-1&&val<=0){val=0;blinkV=0;blinkT=0;nextBlink=2+Math.random()*4;}setExpr('blink',val);}}EXPR_NAMES.forEach(n=>{if(n.startsWith('blink')||VISEMES.includes(n))return;const t=exprTgt[n]||0;exprCur[n]=(exprCur[n]||0)+(t-(exprCur[n]||0))*8*dt;setExpr(n,exprCur[n]);});VISEMES.forEach(v=>setExpr(v,Math.max(0,Math.min(2,(vrm.expressionManager.getValue(v)||0)+(targetVisemes[v]-(vrm.expressionManager.getValue(v)||0))*30*dt))));vrm.update(dt);if(vrm.springBoneManager)vrm.springBoneManager.joints.forEach(j=>{if(j.settings){j.settings.gravityPower=physics.gravity;j.settings.stiffness=physics.stiffness;j.settings.dragForce=physics.drag;}});}renderer.render(scene,camera);frames++;if(performance.now()-lastFps>1000){document.getElementById('fps').textContent=frames+' FPS';frames=0;lastFps=performance.now();}}
|
| 358 |
-
buildEmotionGrid();init();animate();
|
| 359 |
-
</script>
|
| 360 |
-
</body>
|
| 361 |
-
</html>'''
|
| 362 |
-
|
| 363 |
-
# ============================================================
|
| 364 |
-
# GRADIO APP
|
| 365 |
-
# ============================================================
|
| 366 |
-
class VRMCompanionApp:
|
| 367 |
-
def __init__(self):
|
| 368 |
-
self.vrma_data = {}
|
| 369 |
-
self.vrma_list = []
|
| 370 |
-
|
| 371 |
-
def load_resources(self):
|
| 372 |
-
if VRMA_ZIP_PATH.exists():
|
| 373 |
-
with zipfile.ZipFile(VRMA_ZIP_PATH, 'r') as zf:
|
| 374 |
-
for name in zf.namelist():
|
| 375 |
-
if name.lower().endswith('.vrma'):
|
| 376 |
-
self.vrma_data[name.split('/')[-1]] = zf.read(name)
|
| 377 |
-
self.vrma_list = list(self.vrma_data.keys())
|
| 378 |
-
print(f"Loaded {len(self.vrma_list)} VRMA animations")
|
| 379 |
-
return len(self.vrma_list)
|
| 380 |
-
|
| 381 |
-
def get_vrm_data(self):
|
| 382 |
-
if VRM_PATH.exists():
|
| 383 |
-
with open(VRM_PATH, 'rb') as f:
|
| 384 |
-
return f.read()
|
| 385 |
-
return None
|
| 386 |
-
|
| 387 |
-
def get_vrma_data(self, name):
|
| 388 |
-
return self.vrma_data.get(name)
|
| 389 |
-
|
| 390 |
-
def get_vrma_list(self):
|
| 391 |
-
return self.vrma_list
|
| 392 |
-
|
| 393 |
-
app_state = VRMCompanionApp()
|
| 394 |
-
|
| 395 |
-
with gr.Blocks(title="MiniCPM5 VRM Companion") as demo:
|
| 396 |
-
gr.Markdown("# ✨ MiniCPM5 2.4B VRM Companion")
|
| 397 |
-
gr.Markdown("*Your loving anime waifu - GPU accelerated*")
|
| 398 |
-
|
| 399 |
-
vrma_count = app_state.load_resources()
|
| 400 |
-
gr.HTML(FRONTEND_HTML)
|
| 401 |
-
|
| 402 |
-
chat_response = gr.JSON(visible=False)
|
| 403 |
-
|
| 404 |
with gr.Row():
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
send_btn.click(
|
| 409 |
-
fn=
|
| 410 |
-
inputs=[
|
| 411 |
-
outputs=[
|
| 412 |
-
)
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 417 |
)
|
| 418 |
|
| 419 |
-
# ============================================================
|
| 420 |
-
# CUSTOM ROUTES
|
| 421 |
-
# ============================================================
|
| 422 |
-
from starlette.requests import Request
|
| 423 |
-
from starlette.responses import Response
|
| 424 |
-
|
| 425 |
-
gr_app = demo.app
|
| 426 |
-
|
| 427 |
-
@gr_app.get("/vrm_data")
|
| 428 |
-
async def serve_vrm(request: Request):
|
| 429 |
-
data = app_state.get_vrm_data()
|
| 430 |
-
return Response(content=data, media_type="application/octet-stream") if data else Response(status_code=404)
|
| 431 |
-
|
| 432 |
-
@gr_app.get("/vrma_list")
|
| 433 |
-
async def serve_vrma_list(request: Request):
|
| 434 |
-
return Response(content=json.dumps(app_state.get_vrma_list()), media_type="application/json")
|
| 435 |
-
|
| 436 |
-
@gr_app.get("/vrma_data")
|
| 437 |
-
async def serve_vrma_data(request: Request):
|
| 438 |
-
name = request.query_params.get("name")
|
| 439 |
-
data = app_state.get_vrma_data(name) if name else None
|
| 440 |
-
return Response(content=data, media_type="application/octet-stream") if data else Response(status_code=404)
|
| 441 |
-
|
| 442 |
-
@gr_app.post("/chat")
|
| 443 |
-
async def chat_endpoint(request: Request):
|
| 444 |
-
try:
|
| 445 |
-
body = await request.json()
|
| 446 |
-
message = body.get("message", "")
|
| 447 |
-
chat_history.append({"role": "user", "content": message})
|
| 448 |
-
response = generate_response(message, app_state.vrma_list)
|
| 449 |
-
try:
|
| 450 |
-
parsed = json.loads(response)
|
| 451 |
-
chat_history.append({"role": "assistant", "content": parsed.get("text", "")})
|
| 452 |
-
except: pass
|
| 453 |
-
if len(chat_history) > 12: chat_history[:] = chat_history[-12:]
|
| 454 |
-
return Response(content=json.dumps({"response": response}), media_type="application/json")
|
| 455 |
-
except Exception as e:
|
| 456 |
-
return Response(content=json.dumps({"error": str(e)}), media_type="application/json", status_code=500)
|
| 457 |
-
|
| 458 |
-
@gr_app.post("/tts")
|
| 459 |
-
async def tts_endpoint(request: Request):
|
| 460 |
-
try:
|
| 461 |
-
body = await request.json()
|
| 462 |
-
audio = await synthesize_speech(body.get("text", ""), body.get("rate", "+0%"), body.get("pitch", "+0Hz"))
|
| 463 |
-
return Response(content=audio, media_type="audio/mpeg") if audio else Response(status_code=500)
|
| 464 |
-
except Exception as e:
|
| 465 |
-
return Response(content=str(e), status_code=500)
|
| 466 |
-
|
| 467 |
-
# ============================================================
|
| 468 |
-
# LOAD LLM AND START
|
| 469 |
-
# ============================================================
|
| 470 |
-
print("Loading MiniCPM5 2.4B to GPU...")
|
| 471 |
-
load_success = load_llm()
|
| 472 |
-
if load_success:
|
| 473 |
-
print("✓ MiniCPM5 ready!")
|
| 474 |
-
else:
|
| 475 |
-
print("⚠ Model load failed - will retry on first chat")
|
| 476 |
|
| 477 |
if __name__ == "__main__":
|
| 478 |
-
demo.launch(server_name="0.0.0.0", server_port=7860
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import sys
|
| 3 |
+
import stat
|
| 4 |
+
import asyncio
|
| 5 |
+
import subprocess
|
| 6 |
+
import threading
|
| 7 |
+
import tempfile
|
| 8 |
+
import time
|
| 9 |
+
import urllib.request
|
| 10 |
import zipfile
|
| 11 |
+
import tarfile
|
| 12 |
+
import json
|
| 13 |
import re
|
|
|
|
|
|
|
| 14 |
|
| 15 |
import gradio as gr
|
|
|
|
|
|
|
| 16 |
import edge_tts
|
| 17 |
+
import spaces
|
| 18 |
+
from huggingface_hub import hf_hub_download
|
| 19 |
+
|
| 20 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 21 |
+
# CONFIG
|
| 22 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 23 |
+
MODEL_REPO = "openbmb/MiniCPM5-1B-GGUF"
|
| 24 |
+
MODEL_FILE = "MiniCPM5-1B-Q8_0.gguf" # 8-bit quantised ≈ 1.15 GB
|
| 25 |
+
MODEL_PATH = "/tmp/minicpm5-1b-Q8_0.gguf"
|
| 26 |
+
|
| 27 |
+
# ai-dock pre-built CUDA 12.4 binaries for llama.cpp (linux amd64)
|
| 28 |
+
# Grab the latest release tag from: https://github.com/ai-dock/llama.cpp-cuda/releases
|
| 29 |
+
LLAMACPP_URL = (
|
| 30 |
+
"https://github.com/ai-dock/llama.cpp-cuda/releases/latest/download/"
|
| 31 |
+
"llama.cpp-cuda-12.4-amd64.tar.gz"
|
| 32 |
+
)
|
| 33 |
+
LLAMACPP_DIR = "/tmp/llamacpp"
|
| 34 |
+
LLAMA_SERVER = os.path.join(LLAMACPP_DIR, "llama-server")
|
| 35 |
+
SERVER_PORT = 8765
|
| 36 |
+
SERVER_URL = f"http://127.0.0.1:{SERVER_PORT}"
|
| 37 |
+
|
| 38 |
+
TTS_VOICE = "zh-CN-XiaoyiNeural" # only this voice, as required
|
| 39 |
+
AUDIO_OUT = "/tmp/tts_output.mp3"
|
| 40 |
+
|
| 41 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 42 |
+
# STEP 1 — Download GGUF model (cached in /tmp)
|
| 43 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 44 |
+
def download_model():
|
| 45 |
+
if os.path.exists(MODEL_PATH):
|
| 46 |
+
print(f"[model] already cached at {MODEL_PATH}")
|
| 47 |
+
return
|
| 48 |
+
print("[model] downloading MiniCPM5-1B-Q8_0.gguf …")
|
| 49 |
+
path = hf_hub_download(
|
| 50 |
+
repo_id = MODEL_REPO,
|
| 51 |
+
filename = MODEL_FILE,
|
| 52 |
+
local_dir = "/tmp",
|
| 53 |
+
)
|
| 54 |
+
# hf_hub_download may save with a different name; symlink if needed
|
| 55 |
+
if path != MODEL_PATH:
|
| 56 |
+
os.rename(path, MODEL_PATH)
|
| 57 |
+
print(f"[model] saved → {MODEL_PATH}")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 61 |
+
# STEP 2 — Download & extract pre-built llama.cpp CUDA binary
|
| 62 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 63 |
+
def download_llamacpp():
|
| 64 |
+
if os.path.exists(LLAMA_SERVER):
|
| 65 |
+
print(f"[llama.cpp] binary already present at {LLAMA_SERVER}")
|
| 66 |
+
return
|
| 67 |
+
|
| 68 |
+
os.makedirs(LLAMACPP_DIR, exist_ok=True)
|
| 69 |
+
archive = "/tmp/llamacpp.tar.gz"
|
| 70 |
+
|
| 71 |
+
print(f"[llama.cpp] downloading pre-built binary from:\n {LLAMACPP_URL}")
|
| 72 |
+
urllib.request.urlretrieve(LLAMACPP_URL, archive)
|
| 73 |
+
|
| 74 |
+
print("[llama.cpp] extracting …")
|
| 75 |
+
with tarfile.open(archive, "r:gz") as tf:
|
| 76 |
+
tf.extractall(LLAMACPP_DIR)
|
| 77 |
+
|
| 78 |
+
# Walk and find llama-server wherever it landed
|
| 79 |
+
for root, dirs, files in os.walk(LLAMACPP_DIR):
|
| 80 |
+
for f in files:
|
| 81 |
+
if f == "llama-server":
|
| 82 |
+
src = os.path.join(root, f)
|
| 83 |
+
os.rename(src, LLAMA_SERVER)
|
| 84 |
+
break
|
| 85 |
+
|
| 86 |
+
# Make executable
|
| 87 |
+
st = os.stat(LLAMA_SERVER)
|
| 88 |
+
os.chmod(LLAMA_SERVER, st.st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
|
| 89 |
+
os.remove(archive)
|
| 90 |
+
print(f"[llama.cpp] ready → {LLAMA_SERVER}")
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 94 |
+
# STEP 3 — Launch llama-server as a background subprocess
|
| 95 |
+
# ────────────────────────────���─────────────────────────────────────────────────
|
| 96 |
+
_server_proc = None
|
| 97 |
+
|
| 98 |
+
def start_server():
|
| 99 |
+
global _server_proc
|
| 100 |
+
if _server_proc and _server_proc.poll() is None:
|
| 101 |
+
print("[server] already running")
|
| 102 |
+
return
|
| 103 |
+
|
| 104 |
+
cmd = [
|
| 105 |
+
LLAMA_SERVER,
|
| 106 |
+
"--model", MODEL_PATH,
|
| 107 |
+
"--host", "127.0.0.1",
|
| 108 |
+
"--port", str(SERVER_PORT),
|
| 109 |
+
"--ctx-size", "4096",
|
| 110 |
+
"--n-gpu-layers","99", # offload all layers to GPU
|
| 111 |
+
"--flash-attn", # faster attention on CUDA
|
| 112 |
+
"--no-mmap",
|
| 113 |
+
"--threads", "4",
|
| 114 |
+
"--log-disable",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
]
|
| 116 |
+
print(f"[server] starting: {' '.join(cmd)}")
|
| 117 |
+
_server_proc = subprocess.Popen(
|
| 118 |
+
cmd,
|
| 119 |
+
stdout=subprocess.DEVNULL,
|
| 120 |
+
stderr=subprocess.DEVNULL,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# Wait until /health returns 200
|
| 124 |
+
import urllib.error
|
| 125 |
+
for _ in range(60):
|
| 126 |
+
try:
|
| 127 |
+
with urllib.request.urlopen(f"{SERVER_URL}/health", timeout=2) as r:
|
| 128 |
+
if r.status == 200:
|
| 129 |
+
print("[server] ✅ ready")
|
| 130 |
+
return
|
| 131 |
+
except Exception:
|
| 132 |
+
pass
|
| 133 |
+
time.sleep(1)
|
| 134 |
+
raise RuntimeError("[server] failed to start within 60 s")
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 138 |
+
# STEP 4 — Chat via OpenAI-compatible /v1/chat/completions endpoint
|
| 139 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 140 |
+
def call_model(messages: list, max_tokens: int = 512, temperature: float = 0.7) -> str:
|
| 141 |
+
import urllib.request, json
|
| 142 |
+
payload = json.dumps({
|
| 143 |
+
"model": "minicpm",
|
| 144 |
+
"messages": messages,
|
| 145 |
+
"max_tokens": max_tokens,
|
| 146 |
+
"temperature": temperature,
|
| 147 |
+
"stream": False,
|
| 148 |
+
}).encode()
|
| 149 |
+
|
| 150 |
+
req = urllib.request.Request(
|
| 151 |
+
f"{SERVER_URL}/v1/chat/completions",
|
| 152 |
+
data = payload,
|
| 153 |
+
headers = {"Content-Type": "application/json"},
|
| 154 |
+
method = "POST",
|
| 155 |
+
)
|
| 156 |
+
with urllib.request.urlopen(req, timeout=120) as resp:
|
| 157 |
+
data = json.loads(resp.read())
|
| 158 |
+
|
| 159 |
+
reply = data["choices"][0]["message"]["content"]
|
| 160 |
+
|
| 161 |
+
# Strip <think>…</think> block if present (MiniCPM5 hybrid reasoning)
|
| 162 |
+
reply = re.sub(r"<think>.*?</think>", "", reply, flags=re.DOTALL).strip()
|
| 163 |
+
return reply
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 167 |
+
# STEP 5 — TTS with edge-tts (XiaoyiNeural only)
|
| 168 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 169 |
+
async def _tts_async(text: str, out_path: str):
|
| 170 |
+
communicate = edge_tts.Communicate(text, TTS_VOICE)
|
| 171 |
+
await communicate.save(out_path)
|
| 172 |
+
|
| 173 |
+
def text_to_speech(text: str) -> str:
|
| 174 |
+
"""Returns path to mp3 file."""
|
| 175 |
+
asyncio.run(_tts_async(text, AUDIO_OUT))
|
| 176 |
+
return AUDIO_OUT
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 180 |
+
# ONE-TIME SETUP (runs at Space startup, before GPU allocation)
|
| 181 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 182 |
+
print("=" * 60)
|
| 183 |
+
print(" MiniCPM5-1B | llama-server | edge-tts XiaoyiNeural")
|
| 184 |
+
print("=" * 60)
|
| 185 |
+
download_model()
|
| 186 |
+
download_llamacpp()
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 190 |
+
# GRADIO INFERENCE FUNCTION (ZeroGPU — GPU allocated per call)
|
| 191 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 192 |
+
@spaces.GPU(duration=120)
|
| 193 |
+
def chat_and_speak(
|
| 194 |
+
user_message: str,
|
| 195 |
+
history: list, # list of [user, assistant] pairs (Gradio format)
|
| 196 |
+
system_prompt: str,
|
| 197 |
+
max_tokens: int,
|
| 198 |
+
temperature: float,
|
| 199 |
+
enable_tts: bool,
|
| 200 |
+
):
|
| 201 |
+
# Ensure server is running (first call starts it; subsequent calls skip)
|
| 202 |
+
start_server()
|
| 203 |
+
|
| 204 |
+
# Build message list
|
| 205 |
+
messages = [{"role": "system", "content": system_prompt}]
|
| 206 |
+
for human, bot in history:
|
| 207 |
+
messages.append({"role": "user", "content": human})
|
| 208 |
+
messages.append({"role": "assistant", "content": bot})
|
| 209 |
+
messages.append({"role": "user", "content": user_message})
|
| 210 |
+
|
| 211 |
+
# Inference
|
| 212 |
+
reply = call_model(messages, max_tokens=max_tokens, temperature=temperature)
|
| 213 |
+
|
| 214 |
+
# TTS
|
| 215 |
+
audio_path = None
|
| 216 |
+
if enable_tts and reply.strip():
|
| 217 |
+
audio_path = text_to_speech(reply)
|
| 218 |
+
|
| 219 |
+
# Update history
|
| 220 |
+
history = history + [[user_message, reply]]
|
| 221 |
+
return history, history, audio_path
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def clear_all():
|
| 225 |
+
return [], [], None
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 229 |
+
# GRADIO UI
|
| 230 |
+
# ──────────────────────────────────────────────────────────────────────────────
|
| 231 |
+
with gr.Blocks(
|
| 232 |
+
title="MiniCPM5-1B Chat",
|
| 233 |
+
theme=gr.themes.Soft(),
|
| 234 |
+
css="""
|
| 235 |
+
#chatbot { height: 500px; }
|
| 236 |
+
footer { display: none !important; }
|
| 237 |
+
""",
|
| 238 |
+
) as demo:
|
| 239 |
+
|
| 240 |
+
gr.Markdown(
|
| 241 |
+
"""
|
| 242 |
+
# 🤖 MiniCPM5-1B Chat
|
| 243 |
+
**Model:** `openbmb/MiniCPM5-1B-GGUF` · Q8_0 (8-bit)
|
| 244 |
+
**Backend:** llama-server (pre-built binary)
|
| 245 |
+
**TTS:** edge-tts · `zh-CN-XiaoyiNeural`
|
| 246 |
+
"""
|
| 247 |
+
)
|
| 248 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
with gr.Row():
|
| 250 |
+
with gr.Column(scale=3):
|
| 251 |
+
chatbot = gr.Chatbot(elem_id="chatbot", label="Conversation")
|
| 252 |
+
with gr.Row():
|
| 253 |
+
user_input = gr.Textbox(
|
| 254 |
+
placeholder="Type your message here …",
|
| 255 |
+
label="Your message",
|
| 256 |
+
lines=2,
|
| 257 |
+
scale=5,
|
| 258 |
+
)
|
| 259 |
+
send_btn = gr.Button("Send 🚀", variant="primary", scale=1)
|
| 260 |
+
clear_btn = gr.Button("🗑️ Clear conversation", variant="secondary")
|
| 261 |
+
audio_out = gr.Audio(label="🔊 TTS Output (XiaoyiNeural)", type="filepath", autoplay=True)
|
| 262 |
+
|
| 263 |
+
with gr.Column(scale=1):
|
| 264 |
+
gr.Markdown("### ��️ Settings")
|
| 265 |
+
system_prompt = gr.Textbox(
|
| 266 |
+
value="You are a helpful, concise assistant.",
|
| 267 |
+
label="System Prompt",
|
| 268 |
+
lines=3,
|
| 269 |
+
)
|
| 270 |
+
max_tokens = gr.Slider(
|
| 271 |
+
minimum=64, maximum=2048, value=512, step=64,
|
| 272 |
+
label="Max new tokens",
|
| 273 |
+
)
|
| 274 |
+
temperature = gr.Slider(
|
| 275 |
+
minimum=0.1, maximum=2.0, value=0.7, step=0.05,
|
| 276 |
+
label="Temperature",
|
| 277 |
+
)
|
| 278 |
+
enable_tts = gr.Checkbox(
|
| 279 |
+
value=True, label="🔊 Enable TTS (XiaoyiNeural)"
|
| 280 |
+
)
|
| 281 |
+
gr.Markdown(
|
| 282 |
+
"""
|
| 283 |
+
---
|
| 284 |
+
**Voice:** `zh-CN-XiaoyiNeural`
|
| 285 |
+
**Quantization:** Q8_0 (8-bit)
|
| 286 |
+
**Context:** 4096 tokens
|
| 287 |
+
**GPU layers:** all offloaded
|
| 288 |
+
"""
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
# State
|
| 292 |
+
state = gr.State([])
|
| 293 |
+
|
| 294 |
+
# Events
|
| 295 |
send_btn.click(
|
| 296 |
+
fn = chat_and_speak,
|
| 297 |
+
inputs = [user_input, state, system_prompt, max_tokens, temperature, enable_tts],
|
| 298 |
+
outputs = [chatbot, state, audio_out],
|
| 299 |
+
).then(lambda: "", outputs=user_input)
|
| 300 |
+
|
| 301 |
+
user_input.submit(
|
| 302 |
+
fn = chat_and_speak,
|
| 303 |
+
inputs = [user_input, state, system_prompt, max_tokens, temperature, enable_tts],
|
| 304 |
+
outputs = [chatbot, state, audio_out],
|
| 305 |
+
).then(lambda: "", outputs=user_input)
|
| 306 |
+
|
| 307 |
+
clear_btn.click(
|
| 308 |
+
fn = clear_all,
|
| 309 |
+
outputs = [chatbot, state, audio_out],
|
| 310 |
)
|
| 311 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
|
| 313 |
if __name__ == "__main__":
|
| 314 |
+
demo.queue(max_size=5).launch(server_name="0.0.0.0", server_port=7860)
|