Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import BertConfig, BertForSequenceClassification, BertTokenizer
|
| 4 |
+
import numpy as np
|
| 5 |
+
import requests
|
| 6 |
+
from io import BytesIO
|
| 7 |
+
|
| 8 |
+
# Load the model and tokenizer
|
| 9 |
+
def load_model():
|
| 10 |
+
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
| 11 |
+
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=7)
|
| 12 |
+
model_state_dict = torch.load('sentiment7_model_acc8878.pth', map_location=torch.device('cpu') # cpu 사용
|
| 13 |
+
model.load_state_dict(model_state_dict)
|
| 14 |
+
model.eval()
|
| 15 |
+
return model, tokenizer
|
| 16 |
+
|
| 17 |
+
model, tokenizer = load_model()
|
| 18 |
+
|
| 19 |
+
# Define the inference function
|
| 20 |
+
def inference(input_doc):
|
| 21 |
+
inputs = tokenizer(input_doc, return_tensors='pt')
|
| 22 |
+
outputs = model(**inputs)
|
| 23 |
+
probs = torch.softmax(outputs.logits, dim=1).squeeze().tolist()
|
| 24 |
+
class_idx = {'공포': 0, '놀람': 1, '분노': 2, '슬픔': 3, '중립': 4, '행복': 5, '혐오': 6}
|
| 25 |
+
return {class_name: prob for class_name, prob in zip(class_idx, probs)}
|
| 26 |
+
|
| 27 |
+
# Set up the Streamlit interface
|
| 28 |
+
st.title('Sentiment Analysis with BERT')
|
| 29 |
+
user_input = st.text_area("Enter text here:")
|
| 30 |
+
if st.button('Analyze'):
|
| 31 |
+
result = inference(user_input)
|
| 32 |
+
st.write(result)
|
| 33 |
+
|