Spaces:
Sleeping
Sleeping
Update app.py
Browse files14 unmodified lines15161718192021222324252627282930313233343536376 unmodified lines44454647484950515253545556575859606162636465666768697071727374757677786 unmodified lines8586878889909192939495969798991001011021031041051061071081091101111121131148 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562571 unmodified line25926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042114 unmodified lines# ===== Custom CSS =====st.markdown("""<style>html, body, [class*="css"] {font-family: 'Poppins', sans-serif;}.block-container {padding: 2rem 2rem 2rem 2rem;}.stButton button {background: linear-gradient(90deg, #4F8BF9 0%, #8E2DE2 100%);border: none;padding: 0.75em 1.5em;border-radius: 8px;color: white;font-size: 18px;font-weight: bold;}</style>""", unsafe_allow_html=True)# ===== GSheet integration =====6 unmodified lines# ===== Save to Google Sheets =====def save_to_gsheet(name, student_id, major, prediction, semester_data, sheet_name="Trang tính1"):# Get the current date and timenow = datetime.now()current_time = now.strftime("%Y-%m-%d %H:%M:%S")# Ensure prediction is in the expected format (0 or 1)if isinstance(prediction, np.ndarray):prediction = int(prediction[0]) # Convert to int if it's ndarrayelif isinstance(prediction, np.int64):prediction = int(prediction) # Convert np.int64 to int# Flatten semester data to individual columns for each semestersemester_data_flat = [str(val) for val in semester_data] # Convert all semester data values to strings# Create a data row to insert into the sheetdata_row = [name, student_id, major, prediction, current_time] + semester_data_flat# Connect to Google Sheetsclient = get_gsheet_client()# Use the Spreadsheet ID (replace with your actual ID)sheet_id = "1i7bDNvLVLXN93_e-FN0JLzpg1jb64Z_aEuyPjIfwbdQ" # Use your actual ID heresheet = client.open_by_key(sheet_id).worksheet(sheet_name)# Get all values from the sheet to check if the first row is empty (i.e., headers not created yet)all_values = sheet.get_all_values()# Define headers based on the model type for accurate sheet savingif sheet_name == "Trang tính1": # Full features modelheaders = ["Họ và tên", "MSV", "Khoa", "Dự báo", "Thời gian"] + [f"Số môn không thi - HK{i+1}" for i in range(6)] + [f"Số tín chỉ không thi - HK{i+1}" for i in range(6)] + [6 unmodified linesf"GPA - HK{i+1}" for i in range(6)] + [f"Xếp loại - HK{i+1}" for i in range(6)]elif sheet_name == "Trang tính2": # Important features modelheaders = ["Họ và tên", "MSV", "Khoa", "Dự báo", "Thời gian"] + [f"Số tín chỉ đạt - HK{i+1}" for i in range(6)] + [f"Số tín chỉ nợ - HK{i+1}" for i in range(6)] + [f"Điểm trung bình - HK{i+1}" for i in range(6)]# If the sheet is empty or if headers are missing, insert headersif not all_values or len(all_values[0]) != len(headers): # Ensure number of columns matches expected headerssheet.append_row(headers) # Create headers if missing# Append data to the sheetsheet.append_row(data_row)# ===== List all sheet names =====# def list_sheet_names(sheet_id):# client = get_gsheet_client()# sheet = client.open_by_key(sheet_id)# # List all sheet names# sheet_names = [worksheet.title for worksheet in sheet.worksheets()]# return sheet_names# ===== HEADER =====st.markdown("<h1 style='text-align: center; color: #003366;'>🎓 DỰ ĐOÁN KHẢ NĂNG TỐT NGHIỆP ĐÚNG HẠN</h1>", unsafe_allow_html=True)8 unmodified linessample_option = st.selectbox("📝 Chọn ví dụ:", ["Không ví dụ", "Dùng ví dụ mẫu ngành Công nghệ thông tin", "Dùng ví dụ mẫu ngành Kinh tế"])# ===== Ví dụ mẫu cho mô hình "Dùng toàn bộ dữ liệu" =====sample_cntt_example_full = {"name": "Nguyễn Văn A","student_id": "10117367","major": "Công nghệ thông tin","semester_data": [0, 0, 0, 0, 17, 7, 7, 8.73, 0,0, 0, 0, 0, 17, 7, 7, 8.19, 0,0, 0, 0, 0, 17, 7, 7, 7.90, 0,0, 0, 0, 0, 17, 7, 7, 8.19, 0,0, 0, 0, 0, 19, 7, 6, 8.18, 0,0, 0, 5, 2, 19, 7, 5, 7.10, 1]}# ===== Ví dụ mẫu cho mô hình "Dùng mô hình đơn giản" =====# ===== Ví dụ cho mô hình "Dùng mô hình đơn giản" cho Kinh tế =====sample_kinhte_example_simple = {"name": "Trần Thị B","student_id": "11418092","major": "Kinh tế","semester_data": [17, 7, 7.64, # Học kỳ 1: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 7.19, # Học kỳ 2: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 6.94, # Học kỳ 3: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 7.19, # Học kỳ 4: Số tín chỉ đạt, Số tín chỉ nợ, GPA19, 7, 7.65, # Học kỳ 5: Số tín chỉ đạt, Số tín chỉ nợ, GPA19, 7, 7.49 # Học kỳ 6: Số tín chỉ đạt, Số tín chỉ nợ, GPA]}# ===== Ví dụ cho mô hình "Dùng mô hình đơn giản" cho CNTT =====# ===== Ví dụ cho mô hình "Dùng mô hình đơn giản" cho CNTT =====sample_cntt_example_simple = {"name": "Nguyễn Văn B","student_id": "10117368","major": "Công nghệ thông tin","semester_data": [15, 8, 7.50, # Học kỳ 1: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 8.10, # Học kỳ 2: Số tín chỉ đạt, Số tín chỉ nợ, GPA18, 7, 7.90, # Học kỳ 3: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 7.80, # Học kỳ 4: Số tín chỉ đạt, Số tín chỉ nợ, GPA19, 8, 8.30, # Học kỳ 5: Số tín chỉ đạt, Số tín chỉ nợ, GPA19, 7, 7.20 # Học kỳ 6: Số tín chỉ đạt, Số tín chỉ nợ, GPA]}# ===== Ví dụ cho mô hình "Dùng mô hình đơn giản" cho Kinh tế =====sample_kinhte_example_full = {"name": "Trần Thị C","student_id": "11418093","major": "Kinh tế","semester_data": [0, 0, 0, 0, 16, 6, 6, 7.00, 1,0, 0, 0, 0, 18, 7, 7, 8.20, 1,0, 0, 0, 0, 17, 7, 7, 7.80, 1,0, 0, 0, 0, 17, 7, 6, 7.90, 1,0, 0, 0, 0, 19, 8, 5, 8.10, 0,0, 0, 8, 2, 19, 7, 6, 7.30, 1]}# ===== Thông tin cá nhân =====if sample_option == "Dùng ví dụ mẫu ngành Công nghệ thông tin":# Check model type to load appropriate example dataif model_type == "Dùng toàn bộ đặc trưng":sample_data_personal = sample_cntt_example_fullelse: # Dùng đặc trưng quan trọngsample_data_personal = sample_cntt_example_simplename = st.text_input("👤 Họ và tên", value=sample_data_personal["name"])student_id = st.text_input("🎓 Mã sinh viên", value=sample_data_personal["student_id"])major = st.selectbox("📚 Ngành học", ["Công nghệ thông tin", "Kinh tế"], index=0)elif sample_option == "Dùng ví dụ mẫu ngành Kinh tế":# Check model type to load appropriate example dataif model_type == "Dùng toàn bộ đặc trưng":sample_data_personal = sample_kinhte_example_fullelse: # Dùng đặc trưng quan trọngsample_data_personal = sample_kinhte_example_simplename = st.text_input("👤 Họ và tên", value=sample_data_personal["name"])student_id = st.text_input("🎓 Mã sinh viên", value=sample_data_personal["student_id"])major = st.selectbox("📚 Ngành học", ["Công nghệ thông tin", "Kinh tế"], index=1)else:name = st.text_input("👤 Họ và tên")student_id = st.text_input("🎓 Mã sinh viên")major = st.selectbox("📚 Ngành học", ["Công nghệ thông tin", "Kinh tế"])st.write("---")# ===== Nhập thông tin học kỳ =====def input_semester(semester_label, default_values=None):with st.expander(f"📖 {semester_label}", expanded=True):col1, col2 = st.columns(2)with col1:somon0thi = st.number_input("Số môn không thi", 0, value=default_values[0] if default_values else 0, key=f"sm0_{semester_label}")sotc0thi = st.number_input("Số tín chỉ không thi", 0, value=default_values[1] if default_values else 0, key=f"tc0_{semester_label}")sotcno = st.number_input("Số tín chỉ nợ", 0, value=default_values[2] if default_values else 0, key=f"tcno_{semester_label}")mhno = st.number_input("Số môn không đạt", 0, value=default_values[3] if default_values else 0, key=f"mhno_{semester_label}")try:default_tc_qua = default_values[4] - default_values[2] if default_values and len(default_values) >= 5 else 0 # This calculation seems incorrect for "Số tín chỉ qua môn" if default_values[4] is Total Creditexcept:default_tc_qua = 0# Correcting default value logic for "Số tín chỉ qua môn" based on sample data structure# If default_values has 9 elements (full model data), default_tc_qua is at index 4if default_values and len(default_values) == 9:default_tc_qua_input = default_values[4]else:default_tc_qua_input = 0 # Or some defaultsotc_qua = st.number_input("Số tín chỉ qua môn", 0, value=default_tc_qua_input, key=f"tcqua_{semester_label}")with col2:TCHK = st.number_input("Tổng tín chỉ học kỳ", 0, value=default_values[4] if default_values else 0, key=f"tchk_{semester_label}")smhk = st.number_input("Số môn học kỳ", 0, value=default_values[5] if default_values else 0, key=f"smhk_{semester_label}")mhpass = st.number_input("Số môn đạt", 0, value=default_values[6] if default_values else 0, key=f"mhpass_{semester_label}")TBCHK = st.number_input("GPA", 0.0, 10.0, value=default_values[7] if default_values else 0.0, step=0.01, key=f"gpa_{semester_label}")xep_loai_selected = st.selectbox("Xếp loại", list(range(7)), index=default_values[8] if default_values else 0, key=f"xeploai_{semester_label}")return [somon0thi, sotc0thi, sotcno, mhno, TCHK, smhk, mhpass, TBCHK, xep_loai_selected, sotc_qua]def input_important_features(semester_label, default_values=None):with st.expander(f"📘 {semester_label}", expanded=True):col1, col2, col3 = st.columns(3) # Use 3 columns for important features layoutwith col1:# Use consistent keys for input fieldssotc_qua = st.number_input("Số tín chỉ đạt", 0, value=default_values[0] if default_values and len(default_values) > 0 else 0, key=f"tcqua_imp_{semester_label}")with col2:sotcno = st.number_input("Số tín chỉ nợ", 0, value=default_values[1] if default_values and len(default_values) > 1 else 0, key=f"tcno_imp_{semester_label}")with col3:TBCHK = st.number_input("Điểm trung bình", 0.0, 10.0, value=default_values[2] if default_values and len(default_values) > 2 else 0.0, step=0.01, key=f"gpa_imp_{semester_label}")return [sotc_qua, sotcno, TBCHK]# ===== Giao diện theo mô hình =====data = []1 unmodified line# Mô hình 1: "Dùng toàn bộ dữ liệu"if model_type == "Dùng toàn bộ đặc trưng":st.subheader("🔢 Nhập thông tin học kỳ chi tiết")for idx, sem in enumerate(semesters):example_data = sample_cntt_example_full if sample_option == "Dùng ví dụ mẫu ngành Công nghệ thông tin" else sample_kinhte_example_full if sample_option == "Dùng ví dụ mẫu ngành Kinh tế" else None# Full model data has 9 features per semester + 1 extra (sotc_qua, which was calculated) = 10 features.# Update: based on the data structure, there are 9 features per semester in the full model example.# The input_semester function returns 10 values. Let's check the save_to_gsheet function's headers for full model.# Headers for full model have 9 semester specific columns per semester.# Let's correct input_semester to return 9 values matching the headers/example data.# The example data has 9 values per semester for the full model.# Let's fix the input_semester function to match the example data and headers (9 features).# The example data has [0, 0, 0, 0, 17, 7, 7, 8.73, 0] -> 9 values.# The input_semester returns [somon0thi, sotc0thi, sotcno, mhno, TCHK, smhk, mhpass, TBCHK, xep_loai_selected, sotc_qua] -> 10 values.# The save_to_gsheet headers for full model list 9 columns per semester.# Let's align input_semester to return the 9 values that correspond to the headers.# Headers: Số môn không thi, Số tín chỉ không thi, Số tín chỉ nợ, Số môn không đạt, Số tín chỉ qua môn, Tổng tín chỉ học kỳ, Số môn học kỳ, Số môn đạt, GPA, Xếp loại# This is 10 headers per semester. The example data has 9. Let's fix the example data structure to match headers or vice versa.# Assuming headers are correct: Número môn không thi, Số tín chỉ không thi, Số tín chỉ nợ, Số môn không đạt, Số tín chỉ qua môn, Tổng tín chỉ học kỳ, Số môn học kỳ, Số môn đạt, GPA, Xếp loại (10 features)# Let's update the example data for the full model to include all 10 features if possible or remove headers that don't match the example data.# Given the original code's save_to_gsheet headers for the full model list 10 items per semester type, and the example data for full model has 9 items per semester type, there's a mismatch.# Let's assume the `input_semester` function's return values are correct based on the intended model features, and the `sample_cntt_example_full` and `sample_kinhte_example_full` are slightly off or need adjustment to match the 10 inputs.# The `input_semester` returns: somon0thi, sotc0thi, sotcno, mhno, TCHK, smhk, mhpass, TBCHK, xep_loai_selected, sotc_qua. This is 10 values.# The `save_to_gsheet` headers for 'Trang tính1' list 10 headers per semester type. This matches.# The `sample_cntt_example_full` and `sample_kinhte_example_full` have 9 values per semester. This is where the discrepancy is.# To make the examples work correctly with the full model inputs, the example data structure should match the 10 features collected by `input_semester`.# The missing feature in the example data seems to be `sotc_qua`.# Let's adjust the example data to include a value for `sotc_qua` for each semester, or adjust the `input_semester` default value logic.# A simpler fix for now is to adjust the `input_semester` default value logic to handle the case where example data might be shorter.# The `default_tc_qua_input` line within `input_semester` was calculating it, let's remove that and rely solely on the example data if available.# And if example data for `sotc_qua` is missing, default to 0.# Corrected input_semester default value handling:def input_semester_corrected(semester_label, default_values=None):with st.expander(f"📖 {semester_label}", expanded=True):col1, col2 = st.columns(2)with col1:somon0thi = st.number_input("Số môn không thi", 0, value=default_values[0] if default_values and len(default_values) > 0 else 0, key=f"sm0_{semester_label}")sotc0thi = st.number_input("Số tín chỉ không thi", 0, value=default_values[1] if default_values and len(default_values) > 1 else 0, key=f"tc0_{semester_label}")sotcno = st.number_input("Số tín chỉ nợ", 0, value=default_values[2] if default_values and len(default_values) > 2 else 0, key=f"tcno_{semester_label}")mhno = st.number_input("Số môn không đạt", 0, value=default_values[3] if default_values and len(default_values) > 3 else 0, key=f"mhno_{semester_label}")# Assuming sotc_qua is the 5th value in the example data if 9 values existsotc_qua_default = default_values[4] if default_values and len(default_values) > 4 else 0sotc_qua = st.number_input("Số tín chỉ qua môn", 0, value=sotc_qua_default, key=f"tcqua_{semester_label}")with col2:TCHK = st.number_input("Tổng tín chỉ học kỳ", 0, value=default_values[5] if default_values and len(default_values) > 5 else 0, key=f"tchk_{semester_label}")smhk = st.number_input("Số môn học kỳ", 0, value=default_values[6] if default_values and len(default_values) > 6 else 0, key=f"smhk_{semester_label}")mhpass = st.number_input("Số môn đạt", 0, value=default_values[7] if default_values and len(default_values) > 7 else 0, key=f"mhpass_{semester_label}")TBCHK = st.number_input("GPA", 0.0, 10.0, value=default_values[8] if default_values and len(default_values) > 8 else 0.0, step=0.01, key=f"gpa_{semester_label}")xep_loai_selected = st.selectbox("Xếp loại", list(range(7)), index=default_values[9] if default_values and len(default_values) > 9 else 0, key=f"xeploai_{semester_label}") # Assuming Xếp loại is the 10th valuereturn [somon0thi, sotc0thi, sotcno, mhno, sotc_qua, TCHK, smhk, mhpass, TBCHK, xep_loai_selected] # Return 10 values# Let's update the example data structure to have 10 values per semester for consistency# Based on the headers, the order should be: Số môn không thi, Số tín chỉ không thi, Số tín chỉ nợ, Số môn không đạt, Số tín chỉ qua môn, Tổng tín chỉ học kỳ, Số môn học kỳ, Số môn đạt, GPA, Xếp loại# The original example data was [somon0thi, sotc0thi, sotcno, mhno, TCHK, smhk, mhpass, TBCHK, xep_loai_selected] -> 9 values# It seems "Số tín chỉ qua môn" was missing or intended to be calculated.# Let's assume "Số tín chỉ qua môn" is implicitly TCHK - sotcno.# However, the headers list "Số tín chỉ qua môn" as a separate column.# Let's assume the headers are correct and the example data needs to match the headers.# Let's restructure example data to have 10 values, adding a plausible value for "Số tín chỉ qua môn" (TCHK - sotcno).sample_cntt_example_full = {"name": "Nguyễn Văn A","student_id": "10117367","major": "Công nghệ thông tin","semester_data": [# HK1: sm0, tc0, tcno, mhno, tc_qua (calculated: TCHK-tcno), TCHK, smhk, mhpass, GPA, xeploai0, 0, 0, 0, 17-0, 17, 7, 7, 8.73, 0,# HK2:0, 0, 0, 0, 17-0, 17, 7, 7, 8.19, 0,# HK3:0, 0, 0, 0, 17-0, 17, 7, 7, 7.90, 0,# HK4:0, 0, 0, 0, 17-0, 17, 7, 7, 8.19, 0,# HK5:0, 0, 0, 0, 19-0, 19, 7, 6, 8.18, 0,# HK6: tcno=5, mhno=2, TCHK=19, mhpass=6, xeploai=1. Assuming tc_qua = TCHK - tcno = 19-5 = 140, 0, 5, 2, 19-5, 19, 7, 6, 7.10, 1]}sample_kinhte_example_full = {"name": "Trần Thị C","student_id": "11418093","major": "Kinh tế","semester_data": [# HK1:0, 0, 0, 0, 16-0, 16, 6, 6, 7.00, 1,# HK2:0, 0, 0, 0, 18-0, 18, 7, 7, 8.20, 1,# HK3:0, 0, 0, 0, 17-0, 17, 7, 7, 7.80, 1,# HK4:0, 0, 0, 0, 17-0, 17, 7, 6, 7.90, 1,# HK5:0, 0, 0, 0, 19-0, 19, 8, 5, 8.10, 0,# HK6: tcno=8, mhno=2, TCHK=19, mhpass=6, xeploai=1. Assuming tc_qua = TCHK - tcno = 19-8 = 110, 0, 8, 2, 19-8, 19, 7, 6, 7.30, 1]}# Now the example data for the full model should match the 10 inputs per semester.example_data = sample_cntt_example_full if sample_option == "Dùng ví dụ mẫu ngành Công nghệ thông tin" else sample_kinhte_example_full if sample_option == "Dùng ví dụ mẫu ngành Kinh tế" else Nonedefault_values = example_data["semester_data"][idx*10:(idx+1)*10] if example_data else None # Slice 10 valuesdata += input_semester_corrected(sem, default_values) # Use the corrected functionnganh = 0 if major == "Công nghệ thông tin" else 1final_features = np.array(data + [nganh]).reshape(1, -1)# Mô hình 2: "Dùng đặc trưng quan trọng"else: # model_type == "Dùng đặc trưng quan trọng"st.subheader("✨ Nhập thông tin rút gọn")# Allow selecting an examplefor idx, sem in enumerate(semesters):example_data = sample_cntt_example_simple if sample_option == "Dùng ví dụ mẫu ngành Công nghệ thông tin" else sample_kinhte_example_simple if sample_option == "Dùng ví dụ mẫu ngành Kinh tế" else None# Slice 3 values per semester for the simple model example datadefault_values = example_data["semester_data"][idx*3:(idx+1)*3] if example_data else None# Use expander to group each semester's fieldswith st.expander(f"📘 {sem}", expanded=True):# Use 3 columns to align with the image layout for all semesterscol1, col2, col3 = st.columns(3)with col1:# Use consistent keys for input fieldssotc_qua = st.number_input("Số tín chỉ đạt", 0, value=default_values[0] if default_values and len(default_values) > 0 else 0, key=f"tcqua_imp_{sem}")with col2:sotcno = st.number_input("Số tín chỉ nợ", 0, value=default_values[1] if default_values and len(default_values) > 1 else 0, key=f"tcno_imp_{sem}")with col3:# Adjusted label to match the image: "Điểm trung bình hệ 10"TBCHK = st.number_input("Điểm trung bình hệ 10", 0.0, 10.0, value=default_values[2] if default_values and len(default_values) > 2 else 0.0, step=0.01, key=f"gpa_imp_{sem}")# Collect semester data (3 values per semester)data += [sotc_qua, sotcno, TBCHK]final_features = np.array(data).reshape(1, -1) # Should be 6 semesters * 3 features = 18 features# ===== Predict =====if st.button("🎯 DỰ BÁO"):if model_type == "Dùng toàn bộ đặc trưng":prediction = model_full.predict(final_features)sheet_name = "Trang tính1" # For full data model, save to Trang tính1else: # model_type == "Dùng đặc trưng quan trọng"prediction = model_important.predict(final_features)sheet_name = "Trang tính2" # For important data model, save to Trang tính2if prediction[0] == 1:st.success(f"🎉 Chúc mừng bạn {name} - {major}! Bạn có khả năng tốt nghiệp đúng hạn!")st.balloons()else:st.error(f"⚠️ Bạn {name} - {major} cần cố gắng hơn! Có nguy cơ trễ hạn.")st.snow()# # Debugging: List all sheet names# sheet_id = "1i7bDNvLVLXN93_e-FN0JLzpg1jb64Z_aEuyPjIfwbdQ" # Use your actual Spreadsheet ID# sheet_names = list_sheet_names(sheet_id)# st.write("Available sheet names:", sheet_names)# Ghi log lên Google Sheetssave_to_gsheet(name, student_id, major, prediction, data,sheet_name) # Pass data to save function14 unmodified lines15161718192021222324252627282930313233343536376 unmodified lines44454647484950515253545556575859606162636465666768697071727374757677786 unmodified lines8586878889909192939495969798991001011028 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192201 unmodified line22222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626714 unmodified lines# ===== Custom CSS =====st.markdown("""<style>html, body, [class*="css"] {font-family: 'Poppins', sans-serif;}.block-container {padding: 2rem 2rem 2rem 2rem;}.stButton button {background: linear-gradient(90deg, #4F8BF9 0%, #8E2DE2 100%);border: none;padding: 0.75em 1.5em;border-radius: 8px;color: white;font-size: 18px;font-weight: bold;}</style>""", unsafe_allow_html=True)# ===== GSheet integration =====6 unmodified lines# ===== Save to Google Sheets =====def save_to_gsheet(name, student_id, major, prediction, semester_data, sheet_name="Trang tính1"):# Get the current date and timenow = datetime.now()current_time = now.strftime("%Y-%m-%d %H:%M:%S")# Ensure prediction is in the expected format (0 or 1)if isinstance(prediction, np.ndarray):prediction = int(prediction[0]) # Convert to int if it's ndarrayelif isinstance(prediction, np.int64):prediction = int(prediction) # Convert np.int64 to int# Flatten semester data to individual columns for each semestersemester_data_flat = [str(val) for val in semester_data] # Convert all semester data values to strings# Create a data row to insert into the sheetdata_row = [name, student_id, major, prediction, current_time] + semester_data_flat# Connect to Google Sheetsclient = get_gsheet_client()# Use the Spreadsheet ID (replace with your actual ID)sheet_id = "1i7bDNvLVLXN93_e-FN0JLzpg1jb64Z_aEuyPjIfwbdQ" # Use your actual ID heresheet = client.open_by_key(sheet_id).worksheet(sheet_name)# Get all values from the sheet to check if the first row is empty (i.e., headers not created yet)all_values = sheet.get_all_values()# Define headers based on the model type for accurate sheet savingif sheet_name == "Trang tính1": # Full features modelheaders = ["Họ và tên", "MSV", "Khoa", "Dự báo", "Thời gian"] + [f"Số môn không thi - HK{i+1}" for i in range(6)] + [f"Số tín chỉ không thi - HK{i+1}" for i in range(6)] + [6 unmodified linesf"GPA - HK{i+1}" for i in range(6)] + [f"Xếp loại - HK{i+1}" for i in range(6)]elif sheet_name == "Trang tính2": # Important features modelheaders = ["Họ và tên", "MSV", "Khoa", "Dự báo", "Thời gian"] + [f"Số tín chỉ đạt - HK{i+1}" for i in range(6)] + [f"Số tín chỉ nợ - HK{i+1}" for i in range(6)] + [f"Điểm trung bình - HK{i+1}" for i in range(6)]# If the sheet is empty or if headers are missing, insert headersif not all_values or len(all_values[0]) != len(headers): # Ensure number of columns matches expected headerssheet.append_row(headers) # Create headers if missing# Append data to the sheetsheet.append_row(data_row)# ===== HEADER =====st.markdown("<h1 style='text-align: center; color: #003366;'>🎓 DỰ ĐOÁN KHẢ NĂNG TỐT NGHIỆP ĐÚNG HẠN</h1>", unsafe_allow_html=True)8 unmodified linessample_option = st.selectbox("📝 Chọn ví dụ:", ["Không ví dụ", "Dùng ví dụ mẫu ngành Công nghệ thông tin", "Dùng ví dụ mẫu ngành Kinh tế"])# Ví dụ mẫu cho mô hình "Dùng toàn bộ dữ liệu"sample_cntt_example_full = {"name": "Nguyễn Văn A","student_id": "10117367","major": "Công nghệ thông tin","semester_data": [0, 0, 0, 0, 17, 7, 7, 8.73, 0,0, 0, 0, 0, 17, 7, 7, 8.19, 0,0, 0, 0, 0, 17, 7, 7, 7.90, 0,0, 0, 0, 0, 17, 7, 7, 8.19, 0,0, 0, 0, 0, 19, 7, 6, 8.18, 0,0, 0, 5, 2, 19, 7, 5, 7.10, 1]}# Ví dụ mẫu cho mô hình "Dùng mô hình đơn giản"sample_kinhte_example_simple = {"name": "Trần Thị B","student_id": "11418092","major": "Kinh tế","semester_data": [17, 7, 7.64, # Học kỳ 1: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 7.19, # Học kỳ 2: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 6.94, # Học kỳ 3: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 7.19, # Học kỳ 4: Số tín chỉ đạt, Số tín chỉ nợ, GPA19, 7, 7.65, # Học kỳ 5: Số tín chỉ đạt, Số tín chỉ nợ, GPA19, 7, 7.49 # Học kỳ 6: Số tín chỉ đạt, Số tín chỉ nợ, GPA]}# ===== Ví dụ cho mô hình "Dùng mô hình đơn giản" cho CNTT =====sample_cntt_example_simple = {"name": "Nguyễn Văn B","student_id": "10117368","major": "Công nghệ thông tin","semester_data": [15, 8, 7.50, # Học kỳ 1: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 8.10, # Học kỳ 2: Số tín chỉ đạt, Số tín chỉ nợ, GPA18, 7, 7.90, # Học kỳ 3: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 7.80, # Học kỳ 4: Số tín chỉ đạt, Số tín chỉ nợ, GPA19, 8, 8.30, # Học kỳ 5: Số tín chỉ đạt, Số tín chỉ nợ, GPA19, 7, 7.20 # Học kỳ 6: Số tín chỉ đạt, Số tín chỉ nợ, GPA]}# ===== Ví dụ cho mô hình "Dùng mô hình đơn giản" cho Kinh tế =====sample_kinhte_example_full = {"name": "Trần Thị C","student_id": "11418093","major": "Kinh tế","semester_data": [0, 0, 0, 0, 16, 6, 6, 7.00, 1,0, 0, 0, 0, 18, 7, 7, 8.20, 1,0, 0, 0, 0, 17, 7, 7, 7.80, 1,0, 0, 0, 0, 17, 7, 6, 7.90, 1,0, 0, 0, 0, 19, 8, 5, 8.10, 0,0, 0, 8, 2, 19, 7, 6, 7.30, 1]}# ===== Thông tin cá nhân =====if sample_option == "Dùng ví dụ mẫu ngành Công nghệ thông tin":# Check model type to load appropriate example dataif model_type == "Dùng toàn bộ đặc trưng":sample_data_personal = sample_cntt_example_fullelse: # Dùng đặc trưng quan trọngsample_data_personal = sample_cntt_example_simplename = st.text_input("👤 Họ và tên", value=sample_data_personal["name"])student_id = st.text_input("🎓 Mã sinh viên", value=sample_data_personal["student_id"])major = st.selectbox("📚 Ngành học", ["Công nghệ thông tin", "Kinh tế"], index=0)elif sample_option == "Dùng ví dụ mẫu ngành Kinh tế":# Check model type to load appropriate example dataif model_type == "Dùng toàn bộ đặc trưng":sample_data_personal = sample_kinhte_example_fullelse: # Dùng đặc trưng quan trọngsample_data_personal = sample_kinhte_example_simplename = st.text_input("👤 Họ và tên", value=sample_data_personal["name"])student_id = st.text_input("🎓 Mã sinh viên", value=sample_data_personal["student_id"])major = st.selectbox("📚 Ngành học", ["Công nghệ thông tin", "Kinh tế"], index=1)else:name = st.text_input("👤 Họ và tên")student_id = st.text_input("🎓 Mã sinh viên")major = st.selectbox("📚 Ngành học", ["Công nghệ thông tin", "Kinh tế"])st.write("---")# ===== Nhập thông tin học kỳ =====def input_semester(semester_label, default_values=None):with st.expander(f"📖 {semester_label}", expanded=True):col1, col2 = st.columns(2)with col1:somon0thi = st.number_input("Số môn không thi", 0, value=default_values[0] if default_values else 0, key=f"sm0_{semester_label}")sotc0thi = st.number_input("Số tín chỉ không thi", 0, value=default_values[1] if default_values else 0, key=f"tc0_{semester_label}")sotcno = st.number_input("Số tín chỉ nợ", 0, value=default_values[2] if default_values else 0, key=f"tcno_{semester_label}")mhno = st.number_input("Số môn không đạt", 0, value=default_values[3] if default_values else 0, key=f"mhno_{semester_label}")sotc_qua = st.number_input("Số tín chỉ qua môn", 0, value=default_values[4] if default_values else 0, key=f"tcqua_{semester_label}")with col2:TCHK = st.number_input("Tổng tín chỉ học kỳ", 0, value=default_values[5] if default_values else 0, key=f"tchk_{semester_label}")smhk = st.number_input("Số môn học kỳ", 0, value=default_values[6] if default_values else 0, key=f"smhk_{semester_label}")mhpass = st.number_input("Số môn đạt", 0, value=default_values[7] if default_values else 0, key=f"mhpass_{semester_label}")TBCHK = st.number_input("GPA", 0.0, 10.0, value=default_values[8] if default_values else 0.0, step=0.01, key=f"gpa_{semester_label}")xep_loai_selected = st.selectbox("Xếp loại", list(range(7)), index=default_values[9] if default_values else 0, key=f"xeploai_{semester_label}")return [somon0thi, sotc0thi, sotcno, mhno, sotc_qua, TCHK, smhk, mhpass, TBCHK, xep_loai_selected]# ===== Giao diện theo mô hình =====data = []1 unmodified line# Mô hình 1: "Dùng toàn bộ dữ liệu"if model_type == "Dùng toàn bộ đặc trưng":st.subheader("🔢 Nhập thông tin học kỳ chi tiết")for idx, sem in enumerate(semesters):example_data = sample_cntt_example_full if sample_option == "Dùng ví dụ mẫu ngành Công nghệ thông tin" else sample_kinhte_example_full if sample_option == "Dùng ví dụ mẫu ngành Kinh tế" else Nonedefault_values = example_data["semester_data"][idx*10:(idx+1)*10] if example_data else Nonedata += input_semester(sem, default_values) # Use the corrected functionnganh = 0 if major == "Công nghệ thông tin" else 1final_features = np.array(data + [nganh]).reshape(1, -1)# Mô hình 2: "Dùng đặc trưng quan trọng"else: # model_type == "Dùng đặc trưng quan trọng"st.subheader("✨ Nhập thông tin rút gọn")for idx, sem in enumerate(semesters):example_data = sample_cntt_example_simple if sample_option == "Dùng ví dụ mẫu ngành Công nghệ thông tin" else sample_kinhte_example_simple if sample_option == "Dùng ví dụ mẫu ngành Kinh tế" else Nonedefault_values = example_data["semester_data"][idx*3:(idx+1)*3] if example_data else Nonewith st.expander(f"📘 {sem}", expanded=True):col1, col2, col3 = st.columns(3)with col1:sotc_qua = st.number_input("Số tín chỉ đạt", 0, value=default_values[0] if default_values else 0, key=f"tcqua_imp_{sem}")with col2:sotcno = st.number_input("Số tín chỉ nợ", 0, value=default_values[1] if default_values else 0, key=f"tcno_imp_{sem}")with col3:TBCHK = st.number_input("Điểm trung bình hệ 10", 0.0, 10.0, value=default_values[2] if default_values else 0.0, step=0.01, key=f"gpa_imp_{sem}")data += [sotc_qua, sotcno, TBCHK]final_features = np.array(data).reshape(1, -1)# ===== Predict =====if st.button("🎯 DỰ BÁO"):if model_type == "Dùng toàn bộ đặc trưng":prediction = model_full.predict(final_features)sheet_name = "Trang tính1" # For full data model, save to Trang tính1else: # model_type == "Dùng đặc trưng quan trọng"prediction = model_important.predict(final_features)sheet_name = "Trang tính2" # For important data model, save to Trang tính2if prediction[0] == 1:st.success(f"🎉 Chúc mừng bạn {name} - {major}! Bạn có khả năng tốt nghiệp đúng hạn!")st.balloons()else:st.error(f"⚠️ Bạn {name} - {major} cần cố gắng hơn! Có nguy cơ trễ hạn.")st.snow()save_to_gsheet(name, student_id, major, prediction, data, sheet_name) # Pass data to save function
app.py+149-303