Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,41 +1,43 @@
|
|
| 1 |
import torch
|
| 2 |
import gradio as gr
|
| 3 |
from transformers import BertTokenizer, BertForSequenceClassification
|
|
|
|
| 4 |
|
| 5 |
-
#
|
| 6 |
-
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
tokenizer = BertTokenizer.from_pretrained("./imdb_bert_tokenizer") # 或者使用保存的分词器路径
|
| 10 |
-
|
| 11 |
-
# 使用 GPU 如果可用
|
| 12 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
|
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
|
|
|
|
| 16 |
model.to(device)
|
| 17 |
|
| 18 |
-
#
|
| 19 |
def analyze_sentiment(text):
|
| 20 |
-
#
|
| 21 |
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512).to(device)
|
| 22 |
|
| 23 |
-
#
|
| 24 |
with torch.no_grad():
|
| 25 |
outputs = model(**inputs)
|
| 26 |
logits = outputs.logits
|
| 27 |
-
prediction = torch.argmax(logits, dim=-1).item()
|
| 28 |
-
sentiment = "Positive" if prediction == 1 else "Negative"
|
| 29 |
|
| 30 |
return sentiment
|
| 31 |
|
| 32 |
-
#
|
| 33 |
-
demo = gr.Interface(
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
#
|
| 40 |
demo.launch()
|
| 41 |
|
|
|
|
| 1 |
import torch
|
| 2 |
import gradio as gr
|
| 3 |
from transformers import BertTokenizer, BertForSequenceClassification
|
| 4 |
+
import os
|
| 5 |
|
| 6 |
+
# Get absolute paths to avoid path format issues
|
| 7 |
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
| 8 |
|
| 9 |
+
# Use GPU if available
|
|
|
|
|
|
|
|
|
|
| 10 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 11 |
+
print(f"Using device: {device}")
|
| 12 |
|
| 13 |
+
# Load tokenizer and model directly from the pre-trained model
|
| 14 |
+
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
|
| 15 |
+
model = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2)
|
| 16 |
model.to(device)
|
| 17 |
|
| 18 |
+
# Define sentiment analysis function
|
| 19 |
def analyze_sentiment(text):
|
| 20 |
+
# Encode text to BERT input format
|
| 21 |
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512).to(device)
|
| 22 |
|
| 23 |
+
# Get model predictions
|
| 24 |
with torch.no_grad():
|
| 25 |
outputs = model(**inputs)
|
| 26 |
logits = outputs.logits
|
| 27 |
+
prediction = torch.argmax(logits, dim=-1).item()
|
| 28 |
+
sentiment = "Positive" if prediction == 1 else "Negative"
|
| 29 |
|
| 30 |
return sentiment
|
| 31 |
|
| 32 |
+
# Create Gradio interface
|
| 33 |
+
demo = gr.Interface(
|
| 34 |
+
fn=analyze_sentiment,
|
| 35 |
+
inputs=gr.Textbox(lines=2, placeholder="Enter a sentence here..."),
|
| 36 |
+
outputs=gr.Textbox(),
|
| 37 |
+
title="IMDB Sentiment Analysis",
|
| 38 |
+
description="Enter an English sentence to analyze its sentiment (Positive/Negative)."
|
| 39 |
+
)
|
| 40 |
|
| 41 |
+
# Launch Gradio interface
|
| 42 |
demo.launch()
|
| 43 |
|