Kelvinhjk commited on
Commit
2b77bf1
·
1 Parent(s): 96bcc84

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ from langchain.embeddings.openai import OpenAIEmbeddings
4
+ from langchain.text_splitter import CharacterTextSplitter
5
+ from langchain.vectorstores import FAISS
6
+ from transformers import TFAutoModelForQuestionAnswering, AutoTokenizer, pipeline
7
+
8
+ os.environ["OPENAI_API_KEY"] = "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"
9
+
10
+ # Read data
11
+ with open("./data/full_context.txt", "r") as file1:
12
+ doc = file1.read()
13
+
14
+ # Splitting up the text into smaller chunks for indexing
15
+ text_splitter = CharacterTextSplitter(
16
+ separator = "\n",
17
+ chunk_size = 1000,
18
+ chunk_overlap = 200, #striding over the text
19
+ length_function = len,
20
+ )
21
+ texts = text_splitter.split_text(doc)
22
+
23
+
24
+ # Download embeddings from OpenAI
25
+ embeddings = OpenAIEmbeddings()
26
+ docsearch = FAISS.from_texts(texts, embeddings)
27
+
28
+ # Load model
29
+ model_path = "/content/drive/MyDrive/Colab_Notebooks/COS30081_NLP/D_HD_Task/models/roberta_model"
30
+
31
+ model = TFAutoModelForQuestionAnswering.from_pretrained(model_path)
32
+ tokenizer = AutoTokenizer.from_pretrained('deepset/roberta-base-squad2')
33
+
34
+ # Initialize Transformer pipeline with our own model and tokenizer
35
+ question_answerer = pipeline("question-answering", model=model, tokenizer=tokenizer)
36
+
37
+ def findHighestScore(question):
38
+ docs_found = docsearch.similarity_search(question)
39
+ doc_score = 0.5
40
+ doc_answer = ''
41
+
42
+ for doc in docs_found:
43
+ doc_result = question_answerer(question=question, context = doc.page_content)
44
+ if doc_result['score'] > doc_score:
45
+ doc_score = doc_result['score']
46
+ doc_answer = doc_result['answer']
47
+
48
+ return doc_answer, doc_score
49
+
50
+
51
+ def QnAfunction(question):
52
+ answer1, score1 = findHighestScore(question)
53
+ if answer1 != '':
54
+ return answer1, score1
55
+ # print("Answer: ", answer1)
56
+ # print("Score: ", score1)
57
+
58
+ else:
59
+ return "No Answer found. Please ask question related to Bachelor of Computer Science program at Swinburne.", 0
60
+ # print("No Answer found. Please ask question related to Bachelor of Computer Science program at Swinburne.")
61
+
62
+
63
+ text = st.text_area("Ask any question about the Bachelor of Computer Science program at Swinburne: ")
64
+ if text:
65
+ ans, score = QnAfunction(text)
66
+ st.json(ans)
67
+