Upload 3 files
Browse files- Dockerfile +19 -0
- app.py +85 -0
- requirements.txt +4 -0
Dockerfile
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.9
|
| 2 |
+
|
| 3 |
+
# Set the working directory to /code
|
| 4 |
+
WORKDIR /code
|
| 5 |
+
|
| 6 |
+
# Copy the requirements file into the container at /code
|
| 7 |
+
COPY ./requirements.txt /code/requirements.txt
|
| 8 |
+
|
| 9 |
+
# Install the dependencies
|
| 10 |
+
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
|
| 11 |
+
|
| 12 |
+
# Copy the rest of the application code
|
| 13 |
+
COPY . .
|
| 14 |
+
|
| 15 |
+
# Expose port 7860 (required by Hugging Face Spaces)
|
| 16 |
+
EXPOSE 7860
|
| 17 |
+
|
| 18 |
+
# Run the application
|
| 19 |
+
CMD ["python", "app.py"]
|
app.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
from flask_cors import CORS
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import BertTokenizerFast, BertForSequenceClassification
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
app = Flask(__name__)
|
| 8 |
+
CORS(app)
|
| 9 |
+
|
| 10 |
+
# Set the device
|
| 11 |
+
device = "cpu" # HF Spaces free tier is CPU only usually, or we can check.
|
| 12 |
+
# But for safety and simplicity on free tier, let's stick to CPU or auto-detect but expect CPU.
|
| 13 |
+
if torch.cuda.is_available():
|
| 14 |
+
device = "cuda"
|
| 15 |
+
elif torch.backends.mps.is_available():
|
| 16 |
+
device = "mps"
|
| 17 |
+
else:
|
| 18 |
+
device = "cpu"
|
| 19 |
+
|
| 20 |
+
print(f"Using device: {device}")
|
| 21 |
+
|
| 22 |
+
# Load the saved model and tokenizer
|
| 23 |
+
# In HF Spaces, we will upload the model files to the root of the repository or a subfolder.
|
| 24 |
+
# Let's assume the user uploads the contents of 'saved_bert_sentiment_model3final' to the root of the Space.
|
| 25 |
+
# So the path is just "." or specific folder if they upload the folder itself.
|
| 26 |
+
# To be safe and organized, let's assume they upload the folder 'model' or just files to root.
|
| 27 |
+
# Best practice for manual upload: Upload files to root.
|
| 28 |
+
MODEL_PATH = "."
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
print("Loading model...")
|
| 32 |
+
loaded_tokenizer = BertTokenizerFast.from_pretrained(MODEL_PATH)
|
| 33 |
+
loaded_model = BertForSequenceClassification.from_pretrained(MODEL_PATH)
|
| 34 |
+
loaded_model.to(device)
|
| 35 |
+
loaded_model.eval()
|
| 36 |
+
print("Model loaded successfully!")
|
| 37 |
+
except Exception as e:
|
| 38 |
+
print(f"Error loading model: {e}")
|
| 39 |
+
# In a Space, if model fails, the app might crash or just not work.
|
| 40 |
+
|
| 41 |
+
@app.route('/')
|
| 42 |
+
def home():
|
| 43 |
+
return "Sentiment Analysis API is Running!"
|
| 44 |
+
|
| 45 |
+
@app.route('/predict', methods=['POST'])
|
| 46 |
+
def predict():
|
| 47 |
+
data = request.json
|
| 48 |
+
text = data.get('text', '')
|
| 49 |
+
|
| 50 |
+
if not text:
|
| 51 |
+
return jsonify({'error': 'No text provided'}), 400
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
tokens = loaded_tokenizer(
|
| 55 |
+
text,
|
| 56 |
+
padding="max_length",
|
| 57 |
+
truncation=True,
|
| 58 |
+
max_length=128,
|
| 59 |
+
return_tensors="pt"
|
| 60 |
+
)
|
| 61 |
+
input_ids = tokens["input_ids"].to(device)
|
| 62 |
+
attention_mask = tokens["attention_mask"].to(device)
|
| 63 |
+
|
| 64 |
+
with torch.no_grad():
|
| 65 |
+
logits = loaded_model(input_ids, attention_mask=attention_mask).logits
|
| 66 |
+
|
| 67 |
+
prediction = torch.argmax(logits, dim=1).item()
|
| 68 |
+
# 1 is Positive, 0 is Negative based on the notebook
|
| 69 |
+
sentiment = "Positive" if prediction == 1 else "Negative"
|
| 70 |
+
|
| 71 |
+
# Calculate confidence (softmax)
|
| 72 |
+
probs = torch.nn.functional.softmax(logits, dim=1)
|
| 73 |
+
confidence = probs[0][prediction].item()
|
| 74 |
+
|
| 75 |
+
return jsonify({
|
| 76 |
+
'sentiment': sentiment,
|
| 77 |
+
'confidence': confidence,
|
| 78 |
+
'label': prediction
|
| 79 |
+
})
|
| 80 |
+
except Exception as e:
|
| 81 |
+
return jsonify({'error': str(e)}), 500
|
| 82 |
+
|
| 83 |
+
if __name__ == '__main__':
|
| 84 |
+
# HF Spaces expects the app to run on port 7860
|
| 85 |
+
app.run(debug=False, host='0.0.0.0', port=7860)
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask
|
| 2 |
+
flask-cors
|
| 3 |
+
transformers
|
| 4 |
+
torch
|