File size: 4,280 Bytes
16c0037
 
 
 
 
 
 
 
 
 
 
 
 
9aa1cd7
16c0037
9aa1cd7
 
 
 
 
 
 
 
 
 
 
 
16c0037
 
 
 
 
 
 
 
 
9aa1cd7
16c0037
9aa1cd7
16c0037
 
9aa1cd7
 
16c0037
 
9aa1cd7
 
 
16c0037
9aa1cd7
 
 
 
 
 
 
 
16c0037
9aa1cd7
16c0037
9aa1cd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16c0037
9aa1cd7
16c0037
 
 
 
 
9aa1cd7
 
 
 
 
 
 
 
 
16c0037
9aa1cd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2ea3df
9aa1cd7
c2ea3df
9aa1cd7
 
16c0037
 
9aa1cd7
 
 
16c0037
9aa1cd7
16c0037
 
 
 
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
"""
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 pydantic.v1.error_wrappers import ValidationError
from openai import AuthenticationError

from qa_generator.file_parser import File
from qa_generator.qa_generator import generate_questions
from qa_generator.constants import QuestionType, DifficultyLevel


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)


def main():
    """
    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(uploaded_file)
                except Exception as e:
                    print(e)
                    st.error(
                        f"Could not process the uploaded file. Try again or different file"
                    )
                    return
            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. \n{err}"
                    )
                    return
            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()