Spaces:
Sleeping
Sleeping
import os | |
os.environ['TRANSFORMERS_CACHE'] = '/app/cache' | |
# Import the necessary modules | |
from flask import Flask, request, render_template | |
from transformers import pipeline | |
# Create a Flask app | |
app = Flask(__name__) | |
# Create a text classification pipeline using a pretrained model | |
classifier = pipeline("text-classification", model="KoalaAI/Text-Moderation") | |
def home(): | |
# Return a simple HTML page | |
return "<html><head><title>Text Classification</title></head><body><h1>Text Classification with Huggingface</h1></body></html>" | |
# Import the xml module | |
import xml.etree.ElementTree as ET | |
# Define a route for the classification result | |
def classify(): | |
# Get the text from the web form | |
text = request.form.get("text") | |
# Perform the text classification | |
result = classifier(text)[0] | |
# Extract the label and the score | |
label = result["label"] | |
score = result["score"] | |
# Create a root element for the XML response | |
root = ET.Element("result") | |
# Add sub-elements for the label and the score | |
ET.SubElement(root, "label").text = label | |
ET.SubElement(root, "score").text = str(score) | |
# Convert the XML element to a byte string | |
xml_string = ET.tostring(root) | |
# Return the XML string as the response with the appropriate mimetype | |
return app.response_class(xml_string, mimetype="application/xml") | |
# Run the app in debug mode | |
if __name__ == "__main__": | |
app.run(host="0.0.0.0", port=7860, debug=False) |