YAML Metadata Warning:empty or missing yaml metadata in repo card
Check out the documentation for more information.
app.py - CO-Live Single-File Production SaaS Engine
import asyncio import json from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, Depends, Security from fastapi.responses import HTMLResponse from fastapi.security.api_key import APIKeyHeader from pydantic import BaseModel from sqlalchemy import create_engine, Column, Integer, String, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from datetime import datetime
--- 1. CONFIG & DATABASE SETUP ---
SQLALCHEMY_DATABASE_URL = "sqlite:///./co_live_single.db" engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base()
class UserModel(Base): tablename = "users" id = Column(Integer, primary_key=True, index=True) username = Column(String, unique=True, index=True) api_key = Column(String, unique=True, index=True) tier = Column(String, default="Enterprise") created_at = Column(DateTime, default=datetime.utcnow)
def init_db(): Base.metadata.create_all(bind=engine) db = SessionLocal() if not db.query(UserModel).filter(UserModel.username == "pho_thanva").first(): db.add(UserModel(username="pho_thanva", api_key="colive_live_key_9999", tier="Enterprise")) db.commit() db.close()
init_db()
--- 2. FASTAPI APP & WEBSOCKET MANAGER ---
app = FastAPI(title="CO-Live Single-File SaaS Engine", version="3.5.0") API_KEY_HEADER = APIKeyHeader(name="X-API-Key", auto_error=False)
class ConnectionManager: def init(self): self.active_connections: list[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
async def broadcast(self, message: dict):
for connection in self.active_connections:
try:
await connection.send_text(json.dumps(message, ensure_ascii=False))
except:
pass
manager = ConnectionManager()
def get_db(): db = SessionLocal() try: yield db finally: db.close()
def verify_api_key(api_key: str = Security(API_KEY_HEADER), db=Depends(get_db)): if not api_key: raise HTTPException(status_code=403, detail="Missing API Key") user = db.query(UserModel).filter(UserModel.api_key == api_key).first() if not user: raise HTTPException(status_code=401, detail="Invalid API Key") return user
--- 3. PAYLOAD SCHEMAS ---
class StreamTriggerRequest(BaseModel): api_key: str action_type: str product_name: str custom_message: str = "" target_customer: str = ""
class WebhookOrderRequest(BaseModel): api_key: str buyer_name: str product_item: str quantity: int
--- 4. API ENDPOINTS ---
@app.post("/api/v1/stream/trigger") async def trigger_stream(payload: StreamTriggerRequest, user = Depends(verify_api_key)): if payload.action_type == "intro_product": speech = f"สวัสดีครับพ่อและทุกคน! ร้าน {user.username} ขอเสนอ '{payload.product_name}' {payload.custom_message}" color = 0xf59e0b elif payload.action_type == "pitch_features": speech = f"จุดเด่น '{payload.product_name}' คือ {payload.custom_message} สั่งซื้อกันได้เลยครับ!" color = 0xef4444 elif payload.action_type == "order_alert": speech = f"🎉 ขอบคุณคุณ {payload.target_customer} มากครับที่กดสั่งซื้อ '{payload.product_name}' จำนวน {payload.custom_message} จัดส่งด่วนทันทีครับ!" color = 0x10b981 else: speech = payload.custom_message or f"กำลังสตรีมสดสินค้า {payload.product_name}" color = 0x38bdf8
broadcast_data = {
"event": "RENDER_FRAME",
"user": user.username,
"speech": speech,
"color": color,
"product": payload.product_name
}
await manager.broadcast(broadcast_data)
return {"status": "success", "data": broadcast_data}
@app.post("/api/v1/webhooks/order") async def receive_webhook_order(payload: WebhookOrderRequest, user = Depends(verify_api_key)): speech = f"🎉 กรี๊ดดด! ขอบคุณคุณ {payload.buyer_name} มากครับที่กดสั่งซื้อ '{payload.product_item}' จำนวน {payload.quantity} แพ็ก! จัดส่งด่วนทันทีครับพ่อ!" broadcast_data = { "event": "RENDER_FRAME", "user": user.username, "speech": speech, "color": 0x10b981, "product": payload.product_item } await manager.broadcast(broadcast_data) return {"status": "success", "message": "Webhook processed successfully"}
@app.websocket("/ws/broadcast") async def websocket_endpoint(websocket: WebSocket): await manager.connect(websocket) try: while True: await websocket.receive_text() except WebSocketDisconnect: manager.disconnect(websocket)
--- 5. FRONTEND 3D STUDIO (HTML/JS Single Page) ---
@app.get("/", response_class=HTMLResponse) def serve_frontend(): return """
CO-Live Studio
<div id="speech-box">Vela: "พร้อมรับสัญญาณ API สตรีมสดแล้วครับพ่อ!"</div>
<div id="canvas-container"></div>
<script>
const container = document.getElementById('canvas-container');
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
scene.add(new THREE.AmbientLight(0xffffff, 1));
const dirLight = new THREE.DirectionalLight(0xffffff, 2);
dirLight.position.set(0, 10, 10);
scene.add(dirLight);
const geometry = new THREE.BoxGeometry(1.5, 2, 1);
const material = new THREE.MeshStandardMaterial({ color: 0xf59e0b, roughness: 0.3 });
const velaAvatar = new THREE.Mesh(geometry, material);
scene.add(velaAvatar);
camera.position.z = 5;
let clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
let time = clock.getElapsedTime();
velaAvatar.position.y = Math.sin(time * 2) * 0.2;
velaAvatar.rotation.y += 0.005;
renderer.render(scene, camera);
}
animate();
function triggerStream(actionType, product, msg) {
const apiKey = document.getElementById('api-key').value;
fetch('/api/v1/stream/trigger', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-API-Key': apiKey },
body: JSON.stringify({ api_key: apiKey, action_type: actionType, product_name: product, custom_message: msg })
}).then(res => res.json()).then(data => { if(data.detail) alert("Error: " + data.detail); });
}
function triggerWebhook(product, qty, customer) {
const apiKey = document.getElementById('api-key').value;
fetch('/api/v1/webhooks/order', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-API-Key': apiKey },
body: JSON.stringify({ api_key: apiKey, buyer_name: customer, product_item: product, quantity: qty })
}).then(res => res.json()).then(data => { if(data.detail) alert("Error: " + data.detail); });
}
const wsProtocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
const ws = new WebSocket(wsProtocol + window.location.host + '/ws/broadcast');
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.event === "RENDER_FRAME") {
document.getElementById('speech-box').innerText = `Vela: "${data.speech}"`;
material.color.setHex(data.color);
}
};
</script>
"""
if name == "main": import uvicorn uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)