Pywebview

the living tribunal

Moderator
Staff member
moderator
Here is the simplified version of the walkthrough with a clean Chatbot class (bot.reply(user_text) -> str) that you can easily drop your own ELIZA logic into.



Folder Setup
Put these three files in your PyCharm project folder and run pip install pywebview:

1796478166859.png





1. avatar.html (VRM Renderer + Click-Through Hit-Testing)
Save this file as avatar.html:

Python:
html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: transparent; user-select: none; }
canvas { display: block; }
</style>
<script type="importmap">
{
"imports": {
"three": "https://jsdelivr.net",
"three/addons/": "https://jsdelivr.net",
"@pixiv/three-vrm": "https://jsdelivr.net"
}
}
</script>
</head>
<body>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { VRMLoaderPlugin, VRMUtils } from '@pixiv/three-vrm';

const renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(28, window.innerWidth / window.innerHeight, 0.1, 20);
camera.position.set(0, 1.35, 1.9);

const light = new THREE.DirectionalLight(0xffffff, 2.2);
light.position.set(1, 1.5, 1.5).normalize();
scene.add(light, new THREE.AmbientLight(0xffffff, 0.7));

let currentVrm = null;
const loader = new GLTFLoader();
loader.register((parser) => new VRMLoaderPlugin(parser));

loader.load('./model.vrm', (gltf) => {
const vrm = gltf.userData.vrm;
VRMUtils.removeUnnecessaryVertices(gltf.scene);
VRMUtils.combineSkeletons(gltf.scene);
if (vrm.meta?.metaVersion === '0') vrm.scene.rotation.y = Math.PI;

const lArm = vrm.humanoid?.getNormalizedBoneNode('leftUpperArm');
const rArm = vrm.humanoid?.getNormalizedBoneNode('rightUpperArm');
if (lArm) lArm.rotation.z = 1.15;
if (rArm) rArm.rotation.z = -1.15;

scene.add(vrm.scene);
currentVrm = vrm;
});

// Per-pixel hit detection for click-through
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
window.isHoveringModel = (normX, normY) => {
if (!currentVrm) return false;
pointer.set(normX * 2 - 1, -(normY * 2 - 1));
raycaster.setFromCamera(pointer, camera);
return raycaster.intersectObjects(currentVrm.scene.children, true).length > 0;
};

// Dragging support
let dragging = false, offsetX = 0, offsetY = 0;
window.addEventListener('mousedown', (e) => {
if (e.button === 0 && window.pywebview) {
dragging = true;
offsetX = e.screenX - window.screenX;
offsetY = e.screenY - window.screenY;
}
});
window.addEventListener('mousemove', (e) => {
if (dragging && window.pywebview) {
window.pywebview.api.move_window(Math.round(e.screenX - offsetX), Math.round(e.screenY - offsetY));
}
});
window.addEventListener('mouseup', () => dragging = false);

// Speaking animation trigger
let speakUntil = 0;
window.startSpeaking = (seconds) => { speakUntil = performance.now() + seconds * 1000; };

const clock = new THREE.Clock();
const vowels = ['aa', 'ih', 'ou', 'ee', 'oh'];
let nextBlink = performance.now() + 2500;

function animate() {
requestAnimationFrame(animate);
const delta = clock.getDelta();
const now = performance.now();

if (currentVrm) {
const exp = currentVrm.expressionManager;
const spine = currentVrm.humanoid?.getNormalizedBoneNode('spine');
if (spine) spine.rotation.x = Math.sin(now * 0.002) * 0.02;

// Auto blink
if (now > nextBlink) {
const phase = (now - nextBlink) / 150;
if (phase < 1.0) exp.setValue('blink', Math.sin(phase * Math.PI));
else { exp.setValue('blink', 0); nextBlink = now + 2500 + Math.random() * 2500; }
}

// Vowel mouth animation
const activeVowel = now < speakUntil ? vowels[Math.floor(now / 130) % vowels.length] : null;
const openness = (Math.sin(now * 0.025) + 1) * 0.45;
for (const v of vowels) exp.setValue(v, v === activeVowel ? openness : 0);

currentVrm.update(delta);
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>



השתמש בקוד בזהירות.










2. main.py (Simplified with a Chatbot Object)
Save this file as main.py and run it in PyCharm:


python

import ctypes
import threading
import time
import webview

# --- 1. SIMPLE CHATBOT OBJECT (Replace with your ELIZA code) ---
class Chatbot:
def reply(self, text: str) -> str:
return f"You said: {text}"


# --- 2. WINDOWS CLICK-THROUGH & DRAG HELPERS ---
user32 = ctypes.windll.user32

class RECT(ctypes.Structure):
_fields_ = [("left", ctypes.c_long), ("top", ctypes.c_long),
("right", ctypes.c_long), ("bottom", ctypes.c_long)]

class POINT(ctypes.Structure):
_fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]

class WindowAPI:
def __init__(self):
self.window = None

def move_window(self, x: int, y: int):
if self.window:
self.window.move(x, y)

def mouse_passthrough_worker(window, title: str):
time.sleep(1.5)
hwnd = user32.FindWindowW(None, title)
if not hwnd:
return

GWL_EXSTYLE, WS_EX_LAYERED, WS_EX_TRANSPARENT = -20, 0x00080000, 0x00000020
rect, pt = RECT(), POINT()
is_passthrough = None

while True:
try:
user32.GetWindowRect(hwnd, ctypes.byref(rect))
user32.GetCursorPos(ctypes.byref(pt))
w, h = rect.right - rect.left, rect.bottom - rect.top

if rect.left <= pt.x <= rect.right and rect.top <= pt.y <= rect.bottom and w > 0 and h > 0:
nx, ny = (pt.x - rect.left) / w, (pt.y - rect.top) / h
hovering = bool(window.evaluate_js(f"window.isHoveringModel({nx:.4f}, {ny:.4f})"))
should_passthrough = not hovering
else:
should_passthrough = True

if should_passthrough != is_passthrough:
style = user32.GetWindowLongW(hwnd, GWL_EXSTYLE)
new_style = (style | WS_EX_LAYERED | WS_EX_TRANSPARENT) if should_passthrough else ((style | WS_EX_LAYERED) & ~WS_EX_TRANSPARENT)
user32.SetWindowLongW(hwnd, GWL_EXSTYLE, new_style)
is_passthrough = should_passthrough
except Exception:
break
time.sleep(0.03)


# --- 3. CHAT LOOP ---
def run_chat(window, bot: Chatbot):
time.sleep(2.0)
print("Chatbot ready! Type 'quit' to exit.\n")

while True:
user_msg = input("You: ")
if user_msg.strip().lower() == "quit":
window.destroy()
break

bot_reply = bot.reply(user_msg)
print("Bot:", bot_reply)

duration = max(1.0, len(bot_reply) * 0.06)
window.evaluate_js(f"window.startSpeaking({duration:.2f})")


# --- 4. START APP ---
if __name__ == "__main__":
TITLE = "Python VRM Mate"
api = WindowAPI()
bot = Chatbot()

window = webview.create_window(
TITLE, "avatar.html",
width=420, height=620,
frameless=True, transparent=True, on_top=True,
js_api=api
)
api.window = window

threading.Thread(target=mouse_passthrough_worker, args=(window, TITLE), daemon=True).start()
threading.Thread(target=run_chat, args=(window, bot), daemon=True).start()
webview.start()



השתמש בקוד בזהירות.










How to Use Your Chatbot
Simply swap your ELIZA logic into the Chatbot.reply(self, text: str) -> str method at the top of main.py. Whenever bot.reply(user_msg) returns a string, the avatar automatically animates its mouth for the length of that reply while leaving the transparent background click-through.


Let me know if you want to:
Bundle the Three.js files locally so it doesn't need internet access on startupAdd a speech bubble above the avatar's head to display bot_reply on screen
 
Top