LiveK / server.py
SakibAhmed's picture
Update server.py
c1b4ab5 verified
# server.py
import os
import uuid
import subprocess
import flask
from flask_cors import CORS
from dotenv import load_dotenv
from livekit import api
load_dotenv()
LIVEKIT_URL = os.environ.get("LIVEKIT_URL")
LIVEKIT_API_KEY = os.environ.get("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET = os.environ.get("LIVEKIT_API_SECRET")
ROOM_NAME = "rajesh-portfolio-room"
if not all([LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET]):
raise EnvironmentError("LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET must be set")
app = flask.Flask(__name__, template_folder="templates")
CORS(app, resources={r"/get-token": {"origins": "*"}})
@app.route("/")
def index():
return flask.render_template("index.html")
@app.route("/get-token", methods=["GET"])
def get_token():
identity = f"user-{uuid.uuid4()}"
token = (
api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
.with_identity(identity)
.with_name(f"Visitor-{identity}")
.with_grants(api.VideoGrants(room_join=True, room=ROOM_NAME))
)
return flask.jsonify({"token": token.to_jwt(), "livekitUrl": LIVEKIT_URL})
# Start agent as subprocess before Flask starts
agent_process = None
if __name__ == "__main__":
print("=" * 60)
print("Starting LiveKit Agent worker...")
print("=" * 60)
# Start agent as non-blocking subprocess
agent_process = subprocess.Popen(
["python", "app.py"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1
)
print("[AGENT] Process started with PID:", agent_process.pid)
print("=" * 60)
print("Starting Flask server...")
print("=" * 60)
# Run Flask (this blocks)
app.run(host="0.0.0.0", port=7860)