Upload ai_text_chatbot.py
Browse files- ai_text_chatbot.py +49 -0
ai_text_chatbot.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import spacy
|
3 |
+
from transformers import pipeline
|
4 |
+
|
5 |
+
# Load spaCy's English model
|
6 |
+
nlp = spacy.load("en_core_web_sm")
|
7 |
+
|
8 |
+
# Basic preprocessing: lowercasing, removing special characters
|
9 |
+
def preprocess_text(text):
|
10 |
+
doc = nlp(text.lower()) # Tokenize and lowercase the text
|
11 |
+
tokens = [token.text for token in doc if not token.is_punct] # Remove punctuation
|
12 |
+
return tokens
|
13 |
+
|
14 |
+
# Load pre-trained question-answering model
|
15 |
+
qa_model = pipeline("question-answering", model="distilbert-base-uncased-distilled-squad")
|
16 |
+
|
17 |
+
# Function to answer question
|
18 |
+
def answer_question(question, context):
|
19 |
+
result = qa_model(question=question, context=context)
|
20 |
+
return result['answer']
|
21 |
+
|
22 |
+
# Streamlit App Layout
|
23 |
+
st.title("Question Answering App")
|
24 |
+
st.write("Upload a text file, ask a question, and get an answer from the text!")
|
25 |
+
|
26 |
+
# File uploader
|
27 |
+
uploaded_file = st.file_uploader("Upload a text file", type=["txt"])
|
28 |
+
|
29 |
+
if uploaded_file is not None:
|
30 |
+
# Read file
|
31 |
+
data = uploaded_file.read().decode('utf-8')
|
32 |
+
|
33 |
+
# Show the content of the file
|
34 |
+
st.write("### File Content")
|
35 |
+
st.write(data)
|
36 |
+
|
37 |
+
# Preprocess the text data
|
38 |
+
processed_data = preprocess_text(data)
|
39 |
+
|
40 |
+
# Ask question
|
41 |
+
question = st.text_input("Enter your question")
|
42 |
+
|
43 |
+
if st.button("Get Answer"):
|
44 |
+
if question:
|
45 |
+
# Get the answer from the QA model
|
46 |
+
answer = answer_question(question, data)
|
47 |
+
st.write(f"**Answer:** {answer}")
|
48 |
+
else:
|
49 |
+
st.write("Please enter a question.")
|