Nikhil0987 commited on
Commit
742b941
·
verified ·
1 Parent(s): f222b0b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -29
app.py CHANGED
@@ -1,36 +1,32 @@
1
- import streamlit as st
2
- import transformers
3
- import torch
4
  from transformers import DistilBertTokenizer, DistilBertForSequenceClassification
5
 
6
- # Load tokenizer and model
7
- tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
8
- model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased')
 
 
 
9
 
10
- # Define a function to preprocess user input
11
- def preprocess_input(text):
12
- encoded_input = tokenizer(text, return_tensors='pt')
13
- return encoded_input
14
 
15
- # Define a function to generate response based on user input
16
- def generate_response(user_input):
17
- encoded_input = preprocess_input(user_input)
18
- outputs = model(**encoded_input)
19
- # Extract relevant information from model outputs (e.g., predicted class)
20
- # Based on the extracted information, formulate a response using predefined responses or logic
21
- response = "I'm still under development, but I understand you said: {}".format(user_input)
22
- return response
23
 
24
- # Start the chat loop
25
- while True:
26
- # Get user input
27
- uinput = st.text_input("Enter your input: ")
28
 
29
- if uinput.lower() == "quit":
30
- break
 
 
31
 
32
-
33
- # Generate response based on user input
34
-
35
- bot_response = generate_response(line) # Assuming generate_response is defined elsewhere
36
- print("Bot:", bot_response)
 
1
+ import streamlit as st
2
+ import torch
 
3
  from transformers import DistilBertTokenizer, DistilBertForSequenceClassification
4
 
5
+ # Load the model and tokenizer
6
+ @st.cache_resource # Cache model for efficiency
7
+ def load_model():
8
+ tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
9
+ model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased')
10
+ return tokenizer, model
11
 
12
+ tokenizer, model = load_model()
 
 
 
13
 
14
+ # Input/Output areas
15
+ st.title("Simple Sentiment Chatbot")
16
+ user_input = st.text_input("Enter your message:")
 
 
 
 
 
17
 
18
+ # Preprocess and generate response when the user hits Enter
19
+ if user_input:
20
+ if user_input.lower() == "quit":
21
+ st.stop() # End the Streamlit app
22
 
23
+ encoded_input = tokenizer(user_input, return_tensors='pt')
24
+ outputs = model(**encoded_input)
25
+ logits = outputs.logits
26
+ predicted_class_id = logits.argmax(-1).item()
27
 
28
+ # Example sentiment mapping (you might have your own)
29
+ sentiment_map = {0: "negative", 1: "neutral", 2: "positive"}
30
+ sentiment = sentiment_map[predicted_class_id]
31
+
32
+ st.write(f"Bot: I sense a {sentiment} sentiment in your message.")