-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
169 lines (138 loc) · 5.39 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
"""
This module contains the Question and Answer Generation App.
The app allows users to upload a PDF file, specify the number of questions to generate,
choose whether to generate answers as well, and provide focus keywords for question generation.
The app processes the PDF file, generates questions based on the text content, and displays
the generated questions along with their corresponding answers (if generated).
Example:
$ streamlit run app.py
"""
import os
import streamlit as st
from openai import AuthenticationError
from pydantic.v1.error_wrappers import ValidationError
from streamlit.runtime.uploaded_file_manager import UploadedFile
from qa_generator.about import about_content
from qa_generator.constants import DifficultyLevel, QuestionType
from qa_generator.file_parser import File
from qa_generator.qa_generator import generate_questions
curent_file_path = os.path.dirname(os.path.abspath(__file__))
os.environ["DATA_DIR"] = os.path.join(curent_file_path, ".data")
os.makedirs(os.environ["DATA_DIR"], exist_ok=True)
st.set_page_config(
page_title="QA Generator",
page_icon="📚",
layout="centered",
initial_sidebar_state="auto",
menu_items={
"Report a bug": "https://github.com/NanthagopalEswaran/QA_Generator/issues",
"Get help": "https://huggingface.co/spaces/NandyG/QA_Generator/discussions",
"About": about_content,
},
)
def save_to_temp_file(file_obj: UploadedFile):
"""
Save the contents of an uploaded file to a temporary file.
Args:
file_obj (UploadedFile): The uploaded file object.
Returns:
str: The path of the temporary file where the contents are saved.
"""
file_path = os.path.join(os.environ["DATA_DIR"], f"{file_obj.file_id}.{file_obj.name}")
with open(file_path, "wb") as temp_file:
content = file_obj.read()
temp_file.write(content)
print(f"file saved to {file_path}")
return file_path
def delete_temp_file(file_path: str):
"""
Delete the temporary file.
Args:
file_path (str): The path of the temporary file to delete.
"""
if os.path.exists(file_path):
os.remove(file_path)
def main(): # noqa: C901
"""
Main function that runs the Question and Answer Generation App.
"""
st.title("Question and Answer Generation App")
uploaded_file = st.file_uploader(
"Upload a File",
accept_multiple_files=False,
type=["pdf", "docx", "md", "txt", "rst"],
)
openai_api_key = st.text_input("OpenAI API Key", type="password")
st.write("---") # Add a separator
num_questions = st.number_input("Number of questions to generate", min_value=1, value=10)
question_type = QuestionType(
st.selectbox(
"Question type",
[value.value for value in QuestionType if value != QuestionType.FILL_IN_THE_BLANK],
)
)
num_options = 0
if question_type:
# Get no. of options for multiple choice questions
if question_type == QuestionType.MULTIPLE_CHOICE:
num_options = st.number_input(
"Number of options for multiple choice questions",
min_value=2,
value=4,
)
# topics = st.text_input("Topics (comma-separated)").split(",")
topics = []
# Difficulty level
difficulty = DifficultyLevel(
st.selectbox(
"Difficulty level",
[value.value for value in DifficultyLevel],
)
)
generate_answers = st.checkbox("Generate answers as well?")
st.write("---") # Add a separator
if st.button("Generate", use_container_width=True):
if uploaded_file is not None:
with st.spinner("Processing the uploaded file..."):
try:
file = File(save_to_temp_file(uploaded_file))
except Exception as e:
print(e)
st.error("Could not process the uploaded file. Try again or different file")
return
finally:
delete_temp_file(file.file_path)
with st.spinner("Generating questions..."):
os.environ["OPENAI_API_KEY"] = openai_api_key
try:
results = generate_questions(
file,
num_questions,
topics,
question_type,
num_options,
difficulty,
generate_answers,
)
except ValidationError as err:
if "openai_api_key" in err.json():
st.error("Please provide an OpenAI API key.")
return
raise
except AuthenticationError:
st.error("Invalid OpenAI API key.")
return
except Exception as err:
st.error(
f"Unexpected error occured while generating questions. please try again. {err}"
)
raise
st.write("---") # Add a separator
st.header("Generated Questions")
for i, result in enumerate(results):
st.text(f"Q{i+1}")
st.json(result.json(), expanded=True)
else:
st.error("Please upload a file.")
if __name__ == "__main__":
main()