PRIYANSHUDHAKED's picture
Create app.py
948f7c1 verified
raw
history blame
6.49 kB
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.")