Spaces:
Sleeping
Sleeping
Update app.py
Browse files65 unmodified lines6667686970717273747576777879808182838485867 unmodified lines9495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084091 unmodified line4114124134144154164174184192 unmodified lines42242342442542642742842943043143243343443565 unmodified lines# 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 semester# Ensure all data points are included, considering the structure varies by model# For 'full' model, semester_data has 9 values per semester * 6 semesters = 54 values# For 'important' model, semester_data has 3 values per semester * 6 semesters = 18 values# We need to handle both cases for saving. Pad with empty strings if using the simple model data for the full sheet structure.semester_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_flat7 unmodified lines# 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 sheet name (model type)if sheet_name == "Trang tính1": # Full model sheetexpected_cols = 5 + (9 * 6) # 5 personal + 9 features per semester * 6 semestersheaders = ["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)] + [f"Số tín chỉ nợ - HK{i+1}" for i in range(6)] + [f"Số môn không đạt - HK{i+1}" for i in range(6)] + [f"Tổng tín chỉ học kỳ - HK{i+1}" for i in range(6)] + [f"Số môn học kỳ - HK{i+1}" for i in range(6)] + [f"Số môn đạt - HK{i+1}" for i in range(6)] + [f"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 model sheetexpected_cols = 5 + (3 * 6) # 5 personal + 3 features per semester * 6 semestersheaders = ["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)]else: # Fallback or other sheetsexpected_cols = 5 + len(semester_data_flat)headers = ["Họ và tên", "MSV", "Khoa", "Dự báo", "Thời gian"] + [f"Data Col {i+1}" for i in range(len(semester_data_flat))]# If the sheet is empty or if headers are missing or mismatched column count, insert headersif not all_values or len(all_values[0]) != expected_cols:# Clear existing content if columns don't match to prevent misalignmentif all_values:sheet.clear()sheet.append_row(headers) # Create headers if missing or mismatch# Pad data_row with empty strings if it doesn't match the expected columns (e.g., saving simple data to full sheet)# Or truncate if somehow too long (less likely)if len(data_row) < expected_cols:data_row.extend([''] * (expected_cols - len(data_row)))elif len(data_row) > expected_cols:data_row = data_row[:expected_cols]# 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 namessheet_names = [worksheet.title for worksheet in sheet.worksheets()]return sheet_names# ===== HEADER =====st.markdown("🎓 DỰ ĐOÁN KHẢ NĂNG TỐT NGHIỆP ĐÚNG HẠN", unsafe_allow_html=True)st.markdown("Áp dụng cho sinh viên năm 3", unsafe_allow_html=True)st.write("---")# ===== SIDEBAR: chọn mô hình =====model_type = st.sidebar.selectbox("🧠 Chọn mô hình dự báo:", ["Dùng toàn bộ đặc trưng", "Dùng đặc trưng quan trọng"])# ===== Giao diện nhập ví dụ và thông tin cá nhân (using columns) =====st.subheader("🔢 Chọn ví dụ mẫu hoặc nhập thông tin cá nhân")# Define example datasample_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, # HK10, 0, 0, 0, 17, 7, 7, 8.19, 0, # HK20, 0, 0, 0, 17, 7, 7, 7.90, 0, # HK30, 0, 0, 0, 17, 7, 7, 8.19, 0, # HK40, 0, 0, 0, 19, 7, 6, 8.18, 0, # HK50, 0, 5, 2, 19, 7, 5, 7.10, 1 # HK6]}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, # HK10, 0, 0, 0, 18, 7, 7, 8.20, 1, # HK20, 0, 0, 0, 17, 7, 7, 7.80, 1, # HK30, 0, 0, 0, 17, 7, 6, 7.90, 1, # HK40, 0, 0, 0, 19, 8, 5, 8.10, 0, # HK50, 0, 8, 2, 19, 7, 6, 7.30, 1 # HK6]}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, # HK1: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 8.10, # HK2: Số tín chỉ đạt, Số tín chỉ nợ, GPA18, 7, 7.90, # HK3: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 7.80, # HK4: Số tín chỉ đạt, Số tín chỉ nợ, GPA19, 8, 8.30, # HK5: Số tín chỉ đạt, Số tín chỉ nợ, GPA19, 7, 7.20 # HK6: Số tín chỉ đạt, Số tín chỉ nợ, GPA]}sample_kinhte_example_simple = {"name": "Trần Thị B","student_id": "11418092","major": "Kinh tế","semester_data": [17, 7, 7.64, # HK1: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 7.19, # HK2: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 6.94, # HK3: Số tín chỉ đạt, Số tín chỉ nợ, GPA17, 7, 7.19, # HK4: Số tín chỉ đạt, Số tín chỉ nợ, GPA19, 7, 7.65, # HK5: Số tín chỉ đạt, Số tín chỉ nợ, GPA19, 7, 7.49 # HK6: Số tín chỉ đạt, Số tín chỉ nợ, GPA]}# Use columns for layoutcol_sample, col_name, col_id, col_major = st.columns([0.3, 0.3, 0.2, 0.2]) # Adjust column widths as neededwith col_sample:sample_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ế"])# Determine default values based on sample_option BEFORE creating text_inputs and selectboxdefault_name = ""default_student_id = ""default_major_index = 0 # Default to CNTTif sample_option == "Dùng ví dụ mẫu ngành Công nghệ thông tin":if model_type == "Dùng toàn bộ đặc trưng":default_name = sample_cntt_example_full["name"]default_student_id = sample_cntt_example_full["student_id"]# default_major_index is already 0 for CNTTelse: # Dùng đặc trưng quan trọngdefault_name = sample_cntt_example_simple["name"]default_student_id = sample_cntt_example_simple["student_id"]# default_major_index is already 0 for CNTTelif sample_option == "Dùng ví dụ mẫu ngành Kinh tế":if model_type == "Dùng toàn bộ đặc trưng":default_name = sample_kinhte_example_full["name"]default_student_id = sample_kinhte_example_full["student_id"]default_major_index = 1 # Index for Kinh tếelse: # Dùng đặc trưng quan trọngdefault_name = sample_kinhte_example_simple["name"]default_student_id = sample_kinhte_example_simple["student_id"]default_major_index = 1 # Index for Kinh tế# Place inputs in columns using determined default valueswith col_name:name = st.text_input("👤 Họ và tên", value=default_name)with col_id:student_id = st.text_input("🎓 Mã sinh viên", value=default_student_id)with col_major:major = st.selectbox("📚 Ngành học", ["Công nghệ thông tin", "Kinh tế"], index=default_major_index)st.write("---")# ===== Nhập thông tin học kỳ =====def input_semester(semester_label, default_values=None):# Ensure default_values is a list of the correct length (9) or Noneif default_values is None or len(default_values) != 9:default_values = [0] * 9 # Provide default zeros if not provided or length mismatchwith 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], key=f"sm0_{semester_label}")sotc0thi = st.number_input("Số tín chỉ không thi", 0, value=default_values[1], key=f"tc0_{semester_label}")sotcno = st.number_input("Số tín chỉ nợ", 0, value=default_values[2], key=f"tcno_{semester_label}")mhno = st.number_input("Số môn không đạt", 0, value=default_values[3], key=f"mhno_{semester_label}")# Calculate default_tc_qua from TCHK (index 4) and Sotcno (index 2) if availabletry:# The original code calculated default_tc_qua from TCHK and Sotcno, but the example data# structure doesn't align with this directly. Let's stick to the example data's structure (which includes sotc_qua implicitly in some sense?)# Reverting to original logic based on example data structure indicesdefault_tc_qua_val = default_values[4] - default_values[2] # Assuming TCHK - Sotcnoexcept (IndexError, TypeError):default_tc_qua_val = 0 # Fallback# Re-evaluating based on the example data structure: the example data for full model# has 9 elements per semester, ordered as:# somon0thi, sotc0thi, sotcno, mhno, TCHK, smhk, mhpass, TBCHK, xep_loai_selected# sotc_qua (số tín chỉ qua môn) is NOT explicitly in the example data structure of 9 elements.# It seems like sotc_qua was intended to be calculated or is a different feature.# The original code calculates default_tc_qua = default_values[4] - default_values[2] (TCHK - Sotcno)# Let's keep this calculation for default value, but the returned list will contain 10 elements.# The saved GSheet headers suggest 10 features per semester. Let's align the input and saving.# The input fields are 9. Let's assume sotc_qua is derived or implicitly part of the 9 for the model input.# However, the GSheet saving code expects 10 values *per semester* for the full model!# It expects: somon0thi, sotc0thi, sotcno, mhno, TCHK, smhk, mhpass, TBCHK, xep_loai, sotc_qua# The input only has 9. Let's add an input for sotc_qua and return 10 values.# Let's fix the input and return value to have 10 features per semester for the full model# The example data only has 9 values. This means the example data is missing 'sotc_qua'.# We need to adjust the input_semester function and the example data handling.# Assuming sotc_qua = TCHK - sotcno is the intended feature.# Let's add it as an input field for clarity and consistency with GSheet saving.# The example data will need a placeholder for sotc_qua.# Let's recalculate the example data structures to include a 10th value (sotc_qua).# For existing examples: sotc_qua = TCHK - sotcno# Re-calculating example data to have 10 features per semester for 'full' model:# original: somon0thi, sotc0thi, sotcno, mhno, TCHK, smhk, mhpass, TBCHK, xep_loai (9 features)# new: somon0thi, sotc0thi, sotcno, mhno, TCHK, smhk, mhpass, TBCHK, xep_loai, sotc_qua (10 features)# where sotc_qua = TCHK - sotcnorecalculated_cntt_full_data = []for i in range(6):sem_slice = sample_cntt_example_full["semester_data"][i*9:(i+1)*9]somon0thi, sotc0thi, sotcno, mhno, TCHK, smhk, mhpass, TBCHK, xep_loai = sem_slicesotc_qua_val = TCHK - sotcnorecalculated_cntt_full_data.extend([somon0thi, sotc0thi, sotcno, mhno, TCHK, smhk, mhpass, TBCHK, xep_loai, sotc_qua_val])recalculated_kinhte_full_data = []for i in range(6):sem_slice = sample_kinhte_example_full["semester_data"][i*9:(i+1)*9]somon0thi, sotc0thi, sotcno, mhno, TCHK, smhk, mhpass, TBCHK, xep_loai = sem_slicesotc_qua_val = TCHK - sotcnorecalculated_kinhte_full_data.extend([somon0thi, sotc0thi, sotcno, mhno, TCHK, smhk, mhpass, TBCHK, xep_loai, sotc_qua_val])# Update the input function to use the 10th value as default for sotc_qua# Ensure default_values has 10 elementsif default_values is None or len(default_values) != 10:default_values = [0] * 10 # Provide default zeros if not provided or length mismatchsomon0thi = st.number_input("Số môn không thi", 0, value=default_values[0], key=f"sm0_{semester_label}")sotc0thi = st.number_input("Số tín chỉ không thi", 0, value=default_values[1], key=f"tc0_{semester_label}")sotcno = st.number_input("Số tín chỉ nợ", 0, value=default_values[2], key=f"tcno_{semester_label}")mhno = st.number_input("Số môn không đạt", 0, value=default_values[3], key=f"mhno_{semester_label}")# sotc_qua input fieldsotc_qua = st.number_input("Số tín chỉ qua môn", 0, value=default_values[9], key=f"tcqua_{semester_label}") # Use index 9 for sotc_quawith col2:TCHK = st.number_input("Tổng tín chỉ học kỳ", 0, value=default_values[4], key=f"tchk_{semester_label}")smhk = st.number_input("Số môn học kỳ", 0, value=default_values[5], key=f"smhk_{semester_label}")mhpass = st.number_input("Số môn đạt", 0, value=default_values[6], key=f"mhpass_{semester_label}")TBCHK = st.number_input("GPA", 0.0, 10.0, value=float(default_values[7]), step=0.01, key=f"gpa_{semester_label}")xep_loai_selected = st.selectbox("Xếp loại", list(range(7)), index=int(default_values[8]), key=f"xeploai_{semester_label}")# Return 10 values in the correct order for GSheet saving and model inputreturn [somon0thi, sotc0thi, sotcno, mhno, TCHK, smhk, mhpass, TBCHK, xep_loai_selected, sotc_qua]def input_important_features(semester_label, default_values=None):# Ensure default_values is a list of the correct length (3) or Noneif default_values is None or len(default_values) != 3:default_values = [0] * 3 # Provide default zeros if not provided or length mismatchwith st.expander(f"📘 {semester_label}", expanded=True):col1, col2 = st.columns(2)with col1:# Assuming the order in example_simple is: Số tín chỉ đạt, Số tín chỉ nợ, GPAsotc_qua = st.number_input("Số tín chỉ đạt", 0, value=default_values[0], key=f"tcqua_imp_{semester_label}")sotcno = st.number_input("Số tín chỉ nợ", 0, value=default_values[1], key=f"tcno_imp_{semester_label}")with col2:TBCHK = st.number_input("Điểm trung bình", 0.0, 10.0, value=float(default_values[2]), step=0.01, key=f"gpa_imp_{semester_label}")return [sotc_qua, sotcno, TBCHK]# ===== Giao diện theo mô hình =====data = []semesters = ["HỌC KỲ I", "HỌC KỲ II", "HỌC KỲ III", "HỌC KỲ IV", "HỌC KỲ V", "HỌC KỲ VI"]# Mô hình 1: "Dùng toàn bộ đặc trưng"if model_type == "Dùng toàn bộ đặc trưng":st.subheader("🔢 Nhập thông tin học kỳ chi tiết (10 đặc trưng/học kỳ)")for idx, sem in enumerate(semesters):# Select example data based on sample_option and model_typeif sample_option == "Dùng ví dụ mẫu ngành Công nghệ thông tin":example_data_sem = recalculated_cntt_full_data # Use recalculated data with 10 featureselif sample_option == "Dùng ví dụ mẫu ngành Kinh tế":example_data_sem = recalculated_kinhte_full_data # Use recalculated data with 10 featureselse:example_data_sem = None # No example# Get default values for the current semester (10 values)default_values = example_data_sem[idx*10:(idx+1)*10] if example_data_sem else Nonedata += input_semester(sem, default_values)# The 'nganh' feature (0 for CNTT, 1 for Kinh tế) is needed for the full modelnganh = 0 if major == "Công nghệ thông tin" else 1# The model expects [semester1_features..., semester6_features..., nganh]final_features = np.array(data + [nganh]).reshape(1, -1)# Mô hình 2: "Dùng đặc trưng quan trọng"else:st.subheader("✨ Nhập thông tin rút gọn (3 đặc trưng/học kỳ)")for idx, sem in enumerate(semesters):# Select example data based on sample_option and model_typeif sample_option == "Dùng ví dụ mẫu ngành Công nghệ thông tin":example_data_sem = sample_cntt_example_simple["semester_data"]elif sample_option == "Dùng ví dụ mẫu ngành Kinh tế":example_data_sem = sample_kinhte_example_simple["semester_data"]else:example_data_sem = None # No example# Get default values for the current semester (3 values)default_values = example_data_sem[idx*3:(idx+1)*3] if example_data_sem else Nonedata += input_important_features(sem, default_values)# The simple model likely does not use the 'nganh' feature, based on the original code's final_features constructionfinal_features = np.array(data).reshape(1, -1)# ===== Predict =====1 unmodified lineif 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: # Dùng đặc trưng quan trọngprediction = model_important.predict(final_features)sheet_name = "Trang tính2" # For important features 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!")2 unmodified linesst.error(f"⚠️ Bạn {name} - {major} cần cố gắng hơn! Có nguy cơ trễ hạn.")st.snow()# Ghi log lên Google Sheets# Pass the relevant data based on the selected model for savingif model_type == "Dùng toàn bộ đặc trưng":# Need to pass the 10 features per semester + nganh (total 61 features)# The 'data' list currently holds 60 features (10*6). Add 'nganh' to the data list for saving.data_to_save = data + [nganh]else: # Dùng đặc trưng quan trọng# The 'data' list holds 18 features (3*6).data_to_save = datasave_to_gsheet(name, student_id, major, prediction, data_to_save, sheet_name) # Pass data_to_save65 unmodified lines66676869707172737475767778798081827 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742751 unmodified line2772782792802812822832842852862872 unmodified lines29029129229329429529629729829965 unmodified lines# 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_flat7 unmodified lines# 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()# If the sheet is empty or if headers are missing, insert headersif not all_values or len(all_values[0]) != (len(semester_data_flat) + 5): # Ensure number of columns matchesheaders = ["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)] + [f"Số tín chỉ nợ - HK{i+1}" for i in range(6)] + [f"Số môn không đạt - HK{i+1}" for i in range(6)] + [f"Số tín chỉ qua môn - HK{i+1}" for i in range(6)] + [f"Tổng tín chỉ học kỳ - HK{i+1}" for i in range(6)] + [f"Số môn học kỳ - HK{i+1}" for i in range(6)] + [f"Số môn đạt - HK{i+1}" for i in range(6)] + [f"GPA - HK{i+1}" for i in range(6)] + [f"Xếp loại - HK{i+1}" for i in range(6)]sheet.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)st.markdown("<h4 style='text-align: center; color: #666;'>Áp dụng cho sinh viên năm 3</h4>", unsafe_allow_html=True)st.write("---")# ===== SIDEBAR: chọn mô hình =====model_type = st.sidebar.selectbox("🧠 Chọn mô hình dự báo:", ["Dùng toàn bộ đặc trưng", "Dùng đặc trưng quan trọng"])# ===== Giao diện nhập ví dụ =====st.subheader("🔢 Chọn ví dụ mẫu hoặc nhập thông tin cá nhân")sample_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":name = st.text_input("👤 Họ và tên", value=sample_cntt_example_full["name"])student_id = st.text_input("🎓 Mã sinh viên", value=sample_cntt_example_full["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ế":name = st.text_input("👤 Họ và tên", value=sample_kinhte_example_simple["name"])student_id = st.text_input("🎓 Mã sinh viên", value=sample_kinhte_example_simple["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 0except:default_tc_qua = 0sotc_qua = st.number_input("Số tín chỉ qua môn", 0, value=default_tc_qua, 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 = st.columns(2)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_{semester_label}")sotcno = st.number_input("Số tín chỉ nợ", 0, value=default_values[1] if default_values else 0, key=f"tcno_imp_{semester_label}")with col2:TBCHK = st.number_input("Điểm trung bình", 0.0, 10.0, value=default_values[2] if default_values 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 = []semesters = ["HỌC KỲ I", "HỌC KỲ II", "HỌC KỲ III", "HỌC KỲ IV", "HỌC KỲ V", "HỌC KỲ VI"]# 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*9:(idx+1)*9] if example_data else Nonedata += input_semester(sem, default_values)nganh = 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 mô hình đơn giản"else:# Ensure the example defaults to "Không ví dụ" when model type is 2st.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 Nonedefault_values = example_data["semester_data"][idx*3:(idx+1)*3] if example_data else None # Fix this line to slice 3 values per semester (Số tín chỉ đạt, Số tín chỉ nợ, GPA)data += input_important_features(sem, default_values)final_features = np.array(data).reshape(1, -1)# ===== Predict =====1 unmodified lineif 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:prediction = model_important.predict(final_features)sheet_name = "Trang tính2" # For full data model, save to Trang tính1if 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!")2 unmodified linesst.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 function
app.py+115-251