File size: 6,488 Bytes
948f7c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184

import streamlit as st
import os
import pandas as pd
from PIL import Image
import io
import datetime
from huggingface_hub import HfApi, hf_hub_download, upload_file
from attendance_system import AttendanceSystem
from record_attendance import record_attendance_new
from huggingface_hub import create_repo  

# Function to create a new Hugging Face repository  
def create_new_hf_repo(repo_id, repo_type="model", private=True):  
    try:  
        create_repo(repo_id, repo_type=repo_type, private=private)  
        st.success(f"New Hugging Face repository created: {repo_id}")  
        return repo_id  
    except Exception as e:  
        st.error(f"Failed to create Hugging Face repository: {e}")  
        return None  

# Add a new section in your Streamlit app  
st.header("Create New Hugging Face Repository")  

# Set the repository details  
new_repo_id = "PRIYANSHUDHAKED/attendance-embeddings"  
repo_type = "model"  
is_private = True  

# Create the new repository  
new_repo_id = create_new_hf_repo(new_repo_id, repo_type=repo_type, private=is_private)  
if new_repo_id:  
    # Update the HF_REPO_ID variable with the new repository ID  
    HF_REPO_ID = new_repo_id  


# Set up AttendanceSystem
DATABASE_DIR = "database"
os.makedirs(DATABASE_DIR, exist_ok=True)
attendance_system = AttendanceSystem(DATABASE_DIR)

# Function to save embeddings to Hugging Face
def save_embeddings_to_hf(roll_number, embedding):
    filename = f"{roll_number}_embedding.npy"
    with io.BytesIO() as buffer:
        np.save(buffer, embedding)
        buffer.seek(0)
        upload_file(
            path_or_fileobj=buffer,
            path_in_repo=f"embeddings/{filename}",
            repo_id=HF_REPO_ID,
            repo_type=HF_REPO_TYPE,
        )

# Function to load embeddings from Hugging Face
def load_embeddings_from_hf():
    embeddings = {}
    files = hf_api.list_repo_files(repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE)
    for file in files:
        if file.startswith("embeddings/") and file.endswith("_embedding.npy"):
            roll_number = file.split("/")[-1].split("_")[0]
            file_content = hf_hub_download(repo_id=HF_REPO_ID, filename=file, repo_type=HF_REPO_TYPE)
            embedding = np.load(file_content)
            embeddings[roll_number] = embedding
    return embeddings

# Function to save CSV to Hugging Face
def save_csv_to_hf(subject):
    filename = f"{subject}.csv"
    upload_file(
        path_or_fileobj=filename,
        path_in_repo=f"attendance/{filename}",
        repo_id=HF_REPO_ID,
        repo_type=HF_REPO_TYPE,
    )

# Function to load CSV from Hugging Face
def load_csv_from_hf(subject):
    filename = f"{subject}.csv"
    try:
        file_content = hf_hub_download(repo_id=HF_REPO_ID, filename=f"attendance/{filename}", repo_type=HF_REPO_TYPE)
        return pd.read_csv(file_content)
    except:
        return None

# Load embeddings from Hugging Face
attendance_system.database = load_embeddings_from_hf()

st.title("Attendance System")

# Sidebar for navigation
page = st.sidebar.selectbox("Choose a page", ["Take Attendance", "Add to Database", "View Attendance"])

if page == "Take Attendance":
    st.header("Take Attendance")

    # Course selection
    courses = [f.split('.')[0] for f in hf_api.list_repo_files(repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE) if f.endswith('.csv')]
    course = st.selectbox("Select Course", courses)

    # Date selection
    date = st.date_input("Select Date", datetime.date.today())

    # Image upload
    uploaded_file = st.file_uploader("Upload Classroom Image", type=["jpg", "jpeg", "png"])

    if st.button("Take Attendance"):
        if uploaded_file is not None:
            # Save the uploaded image temporarily
            image = Image.open(uploaded_file)
            img_path = "temp_classroom.jpg"
            image.save(img_path)

            # Process attendance
            present_students = attendance_system.record_attendance(course, str(date), img_path)

            # Display results
            st.subheader("Present Students:")
            st.write(", ".join(present_students))

            # Option to mark attendance in sheet
            if st.button("Mark Attendance in Sheet"):
                record_attendance_new(present_students, course)
                save_csv_to_hf(course)
                st.success("Attendance marked successfully!")

            # Clean up temporary file
            os.remove(img_path)
        else:
            st.error("Please upload an image.")

elif page == "Add to Database":
    st.header("Add to Database")

    roll_number = st.text_input("Enter Roll Number")
    uploaded_file = st.file_uploader("Upload Student Image", type=["jpg", "jpeg", "png"])

    if st.button("Add to Database"):
        if uploaded_file is not None and roll_number:
            # Save the uploaded image temporarily
            image = Image.open(uploaded_file)
            img_path = f"temp_{roll_number}.jpg"
            image.save(img_path)

            # Add to database
            if attendance_system.add_to_database(roll_number, img_path):
                # Save embeddings to Hugging Face
                embedding = attendance_system.database[roll_number]
                save_embeddings_to_hf(roll_number, embedding)
                st.success("Student added to database successfully!")
            else:
                st.error("Failed to add student to database.")

            # Clean up temporary file
            os.remove(img_path)
        else:
            st.error("Please enter a roll number and upload an image.")

elif page == "View Attendance":
    st.header("View Attendance")

    # Course selection for viewing attendance
    courses = [f.split('.')[0] for f in hf_api.list_repo_files(repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE) if f.endswith('.csv')]
    selected_course = st.selectbox("Select Course to View Attendance", courses)

    if selected_course:
        # Read the CSV file from Hugging Face
        df = load_csv_from_hf(selected_course)
        
        if df is not None:
            # Display the attendance data
            st.dataframe(df)

            # Option to download the CSV
            csv = df.to_csv(index=False)
            st.download_button(
                label="Download CSV",
                data=csv,
                file_name=f"{selected_course}_attendance.csv",
                mime="text/csv",
            )
        else:
            st.error("Failed to load attendance data.")