CoolFace
Apppublic

Sardor2203/Coursework

sourceHugging Faceupdated 6mo agoView on Hugging Face
1likes
app.py181 linesDownload Raw Back to root
1import json
2import streamlit as st
3from datetime import datetime
4
5
6version_float = 1.1
7
8# ------------------------------------------ QUESTIONS -----------------------------------------------
9
10def taking_out_questions(filename):
11    with open(filename, "r") as file:
12        reader = json.load(file)
13        return reader
14
15questions = list(taking_out_questions("survey_questions.json"))
16
17psychological_states = {
18    "Excellent Summarizing skills": (0, 10),
19    "Moderate Summarizing skills and well retention of key details": (11, 20),
20    "Basic key point retention skills ": (21, 30),
21    "Low level of reading summarization and comprehension": (31, 40),
22    "Very low level of reading summarization and comprehension": (41, 50),
23    "Critical lack of summarization and key point understanding": (51,60)
24
25}
26
27
28# ------------------------------------------ FUNCTIONS -----------------------------------------------
29
30def check_name(name: str) -> bool:
31    if len(name.strip()) == 0:
32        return False
33    index = 0
34    while index < len(name):
35        character = name[index]
36        allowed_characters = ({"-", " ", "'"})
37        if not (character in allowed_characters or character.isalpha()):
38            return False
39        index += 1
40    return True
41def validate_date_of_birth(date_of_birth: str) -> bool:
42    allowed_date = ("%d-%m-%Y", "%Y-%m-%d")
43    is_valid = False
44    for time_format in allowed_date:
45        try:
46            datetime.strptime(date_of_birth, time_format)
47            is_valid = True
48        except ValueError:
49            is_valid = is_valid
50    return is_valid
51def interpret_score(score: int) -> str:
52    for state, (lower, upper) in psychological_states.items():
53        if score in range(lower, upper+1):
54            return state
55    return "Unknown"
56
57def save_json(filename: str, data_type: dict):
58    with open(filename, "w", encoding="utf-8") as file:
59        json.dump(data_type, file, indent=2)
60
61def session_starting():
62    name = st.text_input("Your first Name")
63    surname = st.text_input("Your last Name")
64    date_of_birth = st.text_input("Date of Birth (DD-MM-YYYY or YYYY-MM-DD)")
65    studentid = st.text_input("Student ID (digits only)")
66    if st.button("Run Survey"):
67        st.session_state.survey_started = True
68    if st.session_state.survey_started:
69            survey_starting(name, surname, date_of_birth, studentid)
70            if st.button("Start Again"):
71                st.session_state.survey_started = False
72                st.rerun()
73
74def survey_starting(name, surname, date_of_birth, studentid):
75        errors = set()
76        if not check_name(name):
77            errors.add("Invalid given name.")
78        if not check_name(surname):
79            errors.add("Invalid surname.")
80        if not validate_date_of_birth(date_of_birth):
81            errors.add("Invalid date of birth format. Use DD-MM-YYYY.")
82        if not studentid.isdigit():
83            errors.add("Student ID must be digits only.")
84        if errors:
85            for e in errors:
86                st.error(e)
87        else:
88            st.success("All inputs are valid. Proceed to answer the questions below.")
89
90            total_score = 0
91            answers = []
92
93            for i in range(len((questions))):
94                q = questions[i]
95                opt_labels = [opt[0] for opt in q["Options"]]
96                choice = st.selectbox(f"Q{i + 1}. {q['Q']}", opt_labels, key=f"Q{i}")
97                score = next(score for label, score in q["Options"] if label == choice)
98                total_score += score
99                answers.append({
100                    "question": q["Q"],
101                    "selected_option": choice,
102                    "score": score
103                })
104
105            status = interpret_score(total_score)
106
107            st.markdown(f"## โœ… Your Result: {status}")
108            st.markdown(f"**Total Score:** {total_score}")
109
110            # Save results to JSON
111            record = {
112                "First_name": name,
113                "Last_name": surname,
114                "Date_of_birth": date_of_birth,
115                "Student_id": studentid,
116                "Total_score": total_score,
117                "Result": status,
118                "Answers": answers,
119                "Version": version_float
120            }
121
122            json_filename = f"{studentid}_result.json"
123            save_json(json_filename, record)
124
125            st.success(f"Your results are saved as {json_filename}")
126            st.download_button("Download your results JSON", json.dumps(record, indent=2), file_name=json_filename)
127
128
129
130# ------------------------------------------ STREAMLIT APP DATA -----------------------------------------------
131if "survey_started" not in st.session_state:
132    st.session_state.survey_started = False
133if "page" not in st.session_state:
134    st.session_state.page = "menu"
135
136# --- Name of the Survey ---
137st.set_page_config(page_title="Book Chapter Summarizing and Key Point Mastery Scale")
138st.title("๐Ÿ“ Book Chapter Summarizing and Key Point Mastery Scale")
139st.info("Please fill out your details and answer all questions honestly.")
140
141if st.session_state.page == "menu":
142    st.subheader("What would you like to do?")
143    column_1, column_2 = st.columns(2)
144    with column_1:
145        if st.button("๐Ÿ†• Start a new survey"):
146            st.session_state.page = "new_survey"
147            st.rerun()
148
149    with column_2:
150        if st.button("๐Ÿ“‚ Load existing results"):
151            st.session_state.page = "load_results"
152            st.rerun()
153
154elif st.session_state.page == "new_survey":
155    session_starting()
156
157elif st.session_state.page == "load_results":
158    st.subheader("Load Existing Results")
159
160    uploaded_file = st.file_uploader("Upload your results JSON", type="json")
161
162    if uploaded_file is not None:
163        data = json.load(uploaded_file)
164        st.write("First Name: " ,data["First_name"])
165        st.write("Last Name: ", data["Last_name"])
166        st.write("Date of birth: ", data["Date_of_birth"])
167        st.write("Student ID: ", data["Student_id"])
168        st.write("Total_score: ", str(data["Total_score"]))
169        st.write("Result: ", data["Result"])
170
171    if st.button("Come back"):
172        st.session_state.page = "menu"
173        st.rerun()
174
175
176
177
178
179
180
181