We will serve a basic HTML page that allows users to input text and see the results.
from fastapi.responses import HTMLResponse
@app.get("/", response_class=HTMLResponse)
def home():
html_content = """
<html>
<head>
<title>AI Sentiment Analysis</title>
</head>
<body>
<h1>Enter text for Sentiment Analysis</h1>
<form action="/analyze/" method="post" id="form">
<textarea name="text" rows="4" cols="50"></textarea><br>
<button type="submit">Analyze</button>
</form>
<div id="result"></div>
<script>
const form = document.getElementById('form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(form);
const response = await fetch('/analyze/', {
method: 'POST',
body: JSON.stringify({ text: formData.get('text') }),
headers: {
'Content-Type': 'application/json'
}
});
const result = await response.json();
document.getElementById('result').innerText = 'Sentiment: ' + result.sentiment.label;
});
</script>
</body>
</html>
"""
return HTMLResponse(content=html_content)