DataWizard9742 commited on
Commit
ec478de
Β·
verified Β·
1 Parent(s): 386acb3

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +123 -71
src/streamlit_app.py CHANGED
@@ -1,81 +1,133 @@
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import pandas as pd
3
- import re
4
  import io
5
 
6
- st.set_page_config(page_title="Excel to Cleaned CSV", layout="centered")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- st.title("πŸ“Š Clean Admission Excel Data")
9
- st.write("Upload the Excel file and download the cleaned CSV file.")
10
 
11
- uploaded_file = st.file_uploader("Upload your Excel file", type=["xlsx"])
 
 
12
 
13
- if uploaded_file is not None:
 
 
 
14
  try:
15
- # Read and clean data
16
- df_raw = pd.read_excel(uploaded_file, skiprows=4)
17
-
18
- df_raw.columns = [
19
- 'S.No', 'District', 'Institution Name',
20
- 'V Minorities Sanctioned', 'V Minorities Admitted',
21
- 'V NonMinorities Sanctioned', 'V NonMinorities Admitted',
22
- 'Course',
23
- 'Inter Minorities Sanctioned', 'Inter Minorities Admitted',
24
- 'Inter NonMinorities Sanctioned', 'Inter NonMinorities Admitted'
25
- ]
26
-
27
- # Remove last row
28
- df_raw = df_raw.iloc[:-1]
29
-
30
- # Clean Institution Name
31
- df_raw['Institution Name'] = df_raw['Institution Name'].astype(str).apply(
32
- lambda x: re.sub(r'\([^)]*\)', '', x).replace('Boys', 'B').replace('Girls', 'G').strip()
33
- )
34
-
35
- # Convert numeric cols
36
- numeric_cols = [
37
- 'V Minorities Sanctioned', 'V Minorities Admitted',
38
- 'V NonMinorities Sanctioned', 'V NonMinorities Admitted',
39
- 'Inter Minorities Sanctioned', 'Inter Minorities Admitted',
40
- 'Inter NonMinorities Sanctioned', 'Inter NonMinorities Admitted'
41
- ]
42
- for col in numeric_cols:
43
- df_raw[col] = pd.to_numeric(df_raw[col], errors='coerce').fillna(0).astype(int)
44
-
45
- # Process Class V
46
- df_v = df_raw[['S.No', 'District', 'Institution Name',
47
- 'V Minorities Sanctioned', 'V Minorities Admitted',
48
- 'V NonMinorities Sanctioned', 'V NonMinorities Admitted']].copy()
49
- df_v['Class'] = 'V'
50
- df_v['Sanctioned'] = df_v['V Minorities Sanctioned'] + df_v['V NonMinorities Sanctioned']
51
- df_v['Admitted'] = df_v['V Minorities Admitted'] + df_v['V NonMinorities Admitted']
52
-
53
- # Process Inter
54
- df_inter = df_raw[['S.No', 'District', 'Institution Name',
55
- 'Inter Minorities Sanctioned', 'Inter Minorities Admitted',
56
- 'Inter NonMinorities Sanctioned', 'Inter NonMinorities Admitted']].copy()
57
- df_inter['Class'] = 'Inter 1st Year'
58
- df_inter['Sanctioned'] = df_inter['Inter Minorities Sanctioned'] + df_inter['Inter NonMinorities Sanctioned']
59
- df_inter['Admitted'] = df_inter['Inter Minorities Admitted'] + df_inter['Inter NonMinorities Admitted']
60
-
61
- # Combine and calculate
62
- df_final = pd.concat([df_v, df_inter], ignore_index=True)
63
- df_final['Vacancies'] = df_final['Sanctioned'] - df_final['Admitted']
64
- df_final = df_final[['S.No', 'District', 'Institution Name', 'Class', 'Sanctioned', 'Admitted', 'Vacancies']]
65
-
66
- # Download CSV
67
- csv_buffer = io.StringIO()
68
- df_final.to_csv(csv_buffer, index=False)
69
- csv_data = csv_buffer.getvalue()
70
-
71
- st.success("βœ… File processed successfully!")
72
-
73
- st.download_button(
74
- label="πŸ“₯ Download Cleaned CSV",
75
- data=csv_data,
76
- file_name="cleaned_admission_data.csv",
77
- mime="text/csv"
78
- )
79
 
80
  except Exception as e:
81
- st.error(f"❌ Error processing file: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyngrok import ngrok
2
+ import threading
3
+ import time
4
+ import os
5
+
6
+ # ----------------- Streamlit Dashboard Code ------------------
7
+ dashboard_code = """
8
  import streamlit as st
9
  import pandas as pd
 
10
  import io
11
 
12
+ # Helper to normalize college name
13
+ def normalize_name(name):
14
+ if pd.isna(name):
15
+ return ""
16
+ return name.replace("(B)", "B").strip().lower()
17
+
18
+ # Transformation Logic
19
+ def transform_file(main_df, attendance_df):
20
+ # Normalize college names in both DataFrames
21
+ main_df['normalized_name'] = main_df.iloc[:, 2].apply(normalize_name)
22
+ attendance_df['normalized_name'] = attendance_df.iloc[:, 2].apply(lambda x: str(x).strip().lower())
23
+
24
+ # Create attendance lookup dictionary
25
+ attendance_lookup = attendance_df.set_index('normalized_name')
26
+
27
+ school_attendance_list = []
28
+ inter_attendance_list = []
29
+
30
+ for name in main_df['normalized_name']:
31
+ if name in attendance_lookup.index:
32
+ row = attendance_lookup.loc[name]
33
+ school_attendance_list.append(row.iloc[6]) # 7th column
34
+ inter_attendance_list.append(row.iloc[10]) # 11th column
35
+ else:
36
+ school_attendance_list.append(None)
37
+ inter_attendance_list.append(None)
38
+
39
+ # Construct final dataframe
40
+ new_df = pd.DataFrame({
41
+ 'serial_no': main_df.iloc[:, 0],
42
+ 'district': main_df.iloc[:, 1],
43
+ 'college_name': main_df.iloc[:, 2],
44
+ 'class': 'School',
45
+ 'school_minority_sanction': main_df.iloc[:, 3],
46
+ 'school_minority_admitted': main_df.iloc[:, 4],
47
+ 'school_minority_vacancies': main_df.iloc[:, 3] - main_df.iloc[:, 4],
48
+ 'school_non_minority_sanction': main_df.iloc[:, 5],
49
+ 'school_non_minority_admitted': main_df.iloc[:, 6],
50
+ 'school_non_minority_vacancies': main_df.iloc[:, 5] - main_df.iloc[:, 6],
51
+ 'school_attendance': school_attendance_list,
52
+ 'school_attendance_percentage': '', # Placeholder
53
+ 'class_grade': 'Intermediate',
54
+ 'inter_minority_sanction': main_df.iloc[:, 8],
55
+ 'inter_minority_admitted': main_df.iloc[:, 9],
56
+ 'inter_minority_vacancies': main_df.iloc[:, 8] - main_df.iloc[:, 9],
57
+ 'inter_non_minority_sanction': main_df.iloc[:, 10],
58
+ 'inter_non_minority_admitted': main_df.iloc[:, 11],
59
+ 'inter_non_minority_vacancies': main_df.iloc[:, 10] - main_df.iloc[:, 11],
60
+ 'inter_attendance': inter_attendance_list,
61
+ 'inter_attendance_percentage': '' # Placeholder
62
+ })
63
 
64
+ return new_df
 
65
 
66
+ # Streamlit App
67
+ st.set_page_config(layout="wide", page_title="πŸ“ File Format Converter")
68
+ st.title("πŸ“€ Upload Two Files to Convert Format")
69
 
70
+ uploaded_main = st.file_uploader("Upload Main File (Sanctions, Admissions)", type=["csv", "xlsx"], key="main")
71
+ uploaded_attendance = st.file_uploader("Upload Attendance File", type=["csv", "xlsx"], key="att")
72
+
73
+ if uploaded_main and uploaded_attendance:
74
  try:
75
+ # Determine extension and read both files
76
+ ext1 = uploaded_main.name.split('.')[-1].lower()
77
+ ext2 = uploaded_attendance.name.split('.')[-1].lower()
78
+
79
+ if ext1 == 'csv':
80
+ main_df = pd.read_csv(uploaded_main, skiprows=4)
81
+ else:
82
+ main_df = pd.read_excel(uploaded_main, skiprows=4)
83
+
84
+ if ext2 == 'csv':
85
+ attendance_df = pd.read_csv(uploaded_attendance)
86
+ else:
87
+ attendance_df = pd.read_excel(uploaded_attendance)
88
+
89
+ st.success("βœ… Both files uploaded and read successfully!")
90
+
91
+ new_df = transform_file(main_df, attendance_df)
92
+ st.dataframe(new_df.head())
93
+
94
+ output = io.BytesIO()
95
+ with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
96
+ new_df.to_excel(writer, index=False, sheet_name='Sheet1')
97
+ worksheet = writer.sheets['Sheet1']
98
+
99
+ # Set wider column widths (20 characters)
100
+ for i, col in enumerate(new_df.columns):
101
+ worksheet.set_column(i, i, 20)
102
+
103
+ st.download_button("πŸ“₯ Download Converted Excel File", output.getvalue(), file_name="converted_output.xlsx")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
  except Exception as e:
106
+ st.error(f"❌ Error while processing files: {e}")
107
+ """
108
+
109
+ # ----------------- Save Streamlit Code -----------------------
110
+ with open("app_file_filter.py", "w") as f:
111
+ f.write(dashboard_code)
112
+
113
+ # ----------------- Ngrok Setup & Streamlit Launch ------------------
114
+ ngrok.set_auth_token("30VAe4T9qTjFG7urJrdYiwizPYO_3BVhHNvCaLGXkWDVAtnmu")
115
+
116
+ # Function to run Streamlit
117
+ def run():
118
+ os.system("streamlit run app_file_filter.py")
119
+
120
+ # Start Streamlit in background thread
121
+ thread = threading.Thread(target=run)
122
+ thread.start()
123
+
124
+ # Give Streamlit time to boot
125
+ time.sleep(5)
126
+
127
+ # Close existing tunnels if any
128
+ for tunnel in ngrok.get_tunnels():
129
+ ngrok.disconnect(tunnel.public_url)
130
+
131
+ # Open a new ngrok tunnel
132
+ public_url = ngrok.connect(addr=8501)
133
+ print("πŸ”— Public URL:", public_url)