Spaces:
Runtime error
Runtime error
from fastapi import FastAPI, WebSocket | |
from fastapi.responses import HTMLResponse | |
import os | |
app = FastAPI() | |
html = """ | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Chat</title> | |
</head> | |
<body> | |
<h1>WebSocket Chat</h1> | |
<form action="" onsubmit="sendMessage(event)"> | |
<input type="text" id="messageText" autocomplete="off"/> | |
<button>Send</button> | |
</form> | |
<ul id='messages'> | |
</ul> | |
<script> | |
// var ws = new WebSocket("ws://localhost:8000/api/ws"); | |
var ws = new WebSocket("wss://cahya-indonesian-whisperer.hf.space/api/ws"); | |
ws.onmessage = function(event) { | |
var messages = document.getElementById('messages') | |
var message = document.createElement('li') | |
var content = document.createTextNode(event.data) | |
message.appendChild(content) | |
messages.appendChild(message) | |
}; | |
function sendMessage(event) { | |
var input = document.getElementById("messageText") | |
ws.send(input.value) | |
input.value = '' | |
event.preventDefault() | |
} | |
</script> | |
</body> | |
</html> | |
""" | |
async def get(): | |
return HTMLResponse(html) | |
async def env(): | |
environment_variables = "<h3>Environment Variables</h3>" | |
for name, value in os.environ.items(): | |
environment_variables += f"{name}: {value}<br>" | |
return HTMLResponse(environment_variables) | |
async def websocket_endpoint(websocket: WebSocket): | |
await websocket.accept() | |
while True: | |
data = await websocket.receive_text() | |
await websocket.send_text(f"Message text was: {data}") | |