The provided Python Flask code is a backend service that doesn't require HTML for its core functionality. It's designed to serve an API endpoint that can be accessed programmatically to perform text summarization. However, if you want to create a user interface where users can input text and receive summaries, you would indeed need to create an HTML frontend that interacts with this backend service.
Let's create a simple HTML form that allows users to submit text to the Flask backend for summarization. You can serve this HTML directly from the Flask application.
Here's what you need to add to your Flask app to serve the HTML form:
# render_template is used to render HTML templates
from flask import Flask, request, jsonify, render_template
from transformers import pipeline
app = Flask(__name__)
# Load the summarization pipeline
summarizer = pipeline("summarization")
@app.route('/')
def index():
# When we open the root URL, Flask will render the 'index.html' template
return render_template('index.html')
@app.route('/summarize', methods=['POST'])
def summarize_text():
# ... existing code for the '/summarize' endpoint ...
if __name__ == '__main__':
app.run(debug=True)
And your HTML file, named index.html, placed in a folder called templates in the root directory of your Flask project, would look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Text Summarization</title>
</head>
<body>
<h1>Text Summarization Service</h1>
<form action="/summarize" method="post">
<textarea name="text" rows="10" cols="50" placeholder="Enter text to summarize..."></textarea>
<br>
<input type="submit" value="Summarize">
</form>
</body>
</html>
In this HTML form:
- A
textarea field allows users to input text.
- Submitting the form makes a POST request to the
/summarize endpoint.
You will also need to adjust the /summarize endpoint in your Flask application to handle form data:
@app.route('/summarize', methods=['POST'])
def summarize_text():
# Get the text to summarize from the form data
text_to_summarize = request.form['text']
if not text_to_summarize:
return jsonify({"error": "No text provided for summarization."}), 400
# Summarize the text
try:
summary = summarizer(text_to_summarize, max_length=150, min_length=30, do_sample=False)
except Exception as e:
return jsonify({"error": str(e)}), 500
# Return the summarized text
return jsonify({"summary": summary[0]['summary_text']}), 200
Now you have a simple web interface that sends a summarization request to your Flask backend and displays the result. You can further enhance this by adding CSS to style your form, JavaScript to handle the response without page reloads, and proper error handling to improve user experience.