Update app.py
Browse files
app.py
CHANGED
@@ -1,40 +1,53 @@
|
|
1 |
-
import
|
2 |
-
from transformers import DistilBertTokenizerFast, DistilBertForQuestionAnswering
|
3 |
-
import json
|
4 |
import streamlit as st
|
5 |
from transformers import pipeline
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
model = DistilBertForQuestionAnswering.from_pretrained(model_name)
|
10 |
|
11 |
-
def
|
12 |
-
return
|
13 |
|
14 |
-
|
15 |
-
|
16 |
-
response = model(prompt, max_length=50, do_sample=True)
|
17 |
-
return response[0]['generated_text'].strip()
|
18 |
-
except Exception as e:
|
19 |
-
print(f"Error while generating response: {str(e)}")
|
20 |
-
return "Sorry, I cannot respond right now."
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
|
|
27 |
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
|
|
|
|
2 |
import streamlit as st
|
3 |
from transformers import pipeline
|
4 |
|
5 |
+
# Initialize the chat history
|
6 |
+
history = []
|
|
|
7 |
|
8 |
+
def clean_text(text):
|
9 |
+
return re.sub('[^a-zA-Z\s]', '', text).strip()
|
10 |
|
11 |
+
# Load DistilBert model
|
12 |
+
model = pipeline("question-answering", model="distilbert-base-cased")
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
+
def generate_response(user_input):
|
15 |
+
# Add user input to history
|
16 |
+
history.append((user_input, ""))
|
17 |
+
|
18 |
+
if not history:
|
19 |
+
return ""
|
20 |
|
21 |
+
last_user_message = history[-1][0]
|
22 |
+
user_input = clean_text(last_user_message)
|
23 |
+
|
24 |
+
if len(user_input) > 0:
|
25 |
+
result = model(question=user_input, context="Placeholder text")
|
26 |
+
answer = result['answer']
|
27 |
+
history[-1] = (last_user_message, answer)
|
28 |
+
|
29 |
+
return f"AI: {answer}"
|
30 |
+
|
31 |
+
st.title("Simple Chat App using DistilBert Model (HuggingFace & Streamlit)")
|
32 |
+
|
33 |
+
for i in range(len(history)):
|
34 |
+
message = history[i][0]
|
35 |
+
response = history[i][1]
|
36 |
+
|
37 |
+
if i % 2 == 0:
|
38 |
+
col1, col2 = st.beta_columns([0.8, 0.2])
|
39 |
+
with col1:
|
40 |
+
st.markdown(f">> {message}")
|
41 |
+
with col2:
|
42 |
+
st.write("")
|
43 |
+
else:
|
44 |
+
col1, col2 = st.beta_columns([0.8, 0.2])
|
45 |
+
with col1:
|
46 |
+
st.markdown(f" {response}")
|
47 |
+
with col2:
|
48 |
+
st.button("Clear")
|
49 |
+
|
50 |
+
new_message = st.text_area("Type something...")
|
51 |
+
if st.button("Submit"):
|
52 |
+
generated_response = generate_response(new_message)
|
53 |
+
st.markdown(generated_response)
|