Jayabalambika commited on
Commit
f81a39c
·
verified ·
1 Parent(s): 3931be8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -75
app.py CHANGED
@@ -1,102 +1,109 @@
1
  import gradio as gr
2
  import pandas as pd
3
- import os
4
  from datetime import datetime
5
 
6
- # Attendance Tracker Setup
7
- try:
8
- if not os.path.exists("attendance_records"):
9
- os.makedirs("attendance_records")
10
- except error:
11
- print(error)
12
-
13
-
14
 
15
- # Helper Functions
16
- def log_attendance(name, day, date, status):
17
- month = datetime.strptime(date, "%Y-%m-%d").strftime("%Y-%m")
18
- file_path = f"attendance_records/{month}.csv"
19
-
20
- # Load or create attendance sheet for the month
21
- if os.path.exists(file_path):
22
- df = pd.read_csv(file_path)
23
- else:
24
- df = pd.DataFrame(columns=["Name", "Day", "Date", "Status"])
25
 
26
- # Add new attendance record
27
- new_entry = {"Name": name, "Day": day, "Date": date, "Status": status}
28
- df = pd.concat([df, pd.DataFrame([new_entry])], ignore_index=True)
 
 
 
 
 
 
 
 
29
 
30
- # Save back to the file
31
- df.to_csv(file_path, index=False)
 
 
 
 
 
32
  return "Attendance logged successfully!"
33
 
34
  def calculate_fees():
35
- attendance_summaries = []
36
-
37
- for file in os.listdir("attendance_records"):
38
- if file.endswith(".csv"):
39
- file_path = os.path.join("attendance_records", file)
40
- df = pd.read_csv(file_path)
41
-
42
- # Calculate fees for each candidate
43
- fees_summary = df[df["Status"] == "Present"].groupby("Name").size() * (1000 / 12) # Example: Monthly fees divided by 12
44
- fees_summary.name = "Fees"
45
-
46
- # Merge fees into the attendance sheet
47
- df = df.merge(fees_summary, on="Name", how="left")
48
-
49
- # Save updated file
50
- df.to_csv(file_path, index=False)
51
-
52
- # Summarize for all candidates
53
- attendance_summaries.append(df[["Name", "Fees"]].drop_duplicates())
54
-
55
- if attendance_summaries:
56
- summary_df = pd.concat(attendance_summaries).drop_duplicates()
57
- summary_df.to_csv("attendance_records/fees_summary.csv", index=False)
58
- return "Fees calculated and updated successfully!"
59
-
60
- return "No attendance records found for fees calculation."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- # Gradio Interface
63
  def submit_attendance(name, day, date, status):
64
  return log_attendance(name, day, date, status)
65
 
66
- def generate_fees():
67
- return calculate_fees()
68
-
69
  def is_month_end():
70
  today = datetime.now()
71
- return (today.day == (pd.Period(today.strftime("%Y-%m")).days_in_month))
72
 
73
- # Function to extract data from Excel
 
74
  def get_dropdown_options(file_path, column_name):
75
- # Read the Excel file
76
  df = pd.read_excel(file_path)
77
- # Extract the unique values from the specified column
78
  options = df["Name"].dropna().unique().tolist()
79
  options.sort()
80
  return options
81
 
82
 
83
-
84
  with gr.Blocks() as app:
85
  gr.Markdown("# Attendance Tracker")
86
 
87
  with gr.Row():
88
- # name = gr.Textbox(label="Name")
89
  file_path = "participants_form.xlsx"
90
  column_name = "Name"
91
  options = get_dropdown_options(file_path, column_name)
92
- name = gr.Dropdown(choices=options, label="Select an Option", show_label=True)
93
- # output = gr.Textbox(label="You Selected")
94
-
95
- # def show_selection(choice):
96
- # return f"You selected: {choice}"
97
-
98
- # name.change(show_selection, inputs=[name], outputs=[output])
99
-
100
  day = gr.Textbox(label="Day")
101
  date = gr.Textbox(label="Date (YYYY-MM-DD)")
102
  status = gr.Radio(["Present", "Absent"], label="Status")
@@ -104,15 +111,11 @@ with gr.Blocks() as app:
104
  submit_button = gr.Button("Submit Attendance")
105
  submit_message = gr.Textbox(label="Message", interactive=False)
106
 
107
- calculate_button = gr.Button("Calculate Fees", interactive=is_month_end())
108
- calculate_message = gr.Textbox(label="Fees Calculation Message", interactive=False)
109
-
110
  submit_button.click(submit_attendance, inputs=[name, day, date, status], outputs=[submit_message])
111
- calculate_button.click(generate_fees, outputs=[calculate_message])
112
 
113
- def update_calculate_button():
114
- return gr.update(interactive=is_month_end())
115
 
116
- app.load(update_calculate_button, None, [calculate_button])
117
 
118
  app.launch()
 
1
  import gradio as gr
2
  import pandas as pd
3
+ import sqlite3
4
  from datetime import datetime
5
 
6
+ # Database Setup
7
+ db_file = "attendance_records.db"
 
 
 
 
 
 
8
 
9
+ conn = sqlite3.connect(db_file)
10
+ cursor = conn.cursor()
 
 
 
 
 
 
 
 
11
 
12
+ # Create attendance table if not exists
13
+ cursor.execute("""
14
+ CREATE TABLE IF NOT EXISTS attendance (
15
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
16
+ name TEXT,
17
+ day TEXT,
18
+ date TEXT,
19
+ status TEXT
20
+ )
21
+ """)
22
+ conn.commit()
23
 
24
+ # Helper Functions
25
+ def log_attendance(name, day, date, status):
26
+ cursor.execute("""
27
+ INSERT INTO attendance (name, day, date, status)
28
+ VALUES (?, ?, ?, ?)
29
+ """, (name, day, date, status))
30
+ conn.commit()
31
  return "Attendance logged successfully!"
32
 
33
  def calculate_fees():
34
+ # Calculate attendance fees
35
+ cursor.execute("""
36
+ SELECT name, COUNT(*) * (1000 / 12) AS fees
37
+ FROM attendance
38
+ WHERE status = 'Present'
39
+ GROUP BY name
40
+ """)
41
+ fees_data = cursor.fetchall()
42
+ fees_dict = {row[0]: row[1] for row in fees_data}
43
+ return fees_dict
44
+
45
+ def create_end_of_month_table():
46
+ today = datetime.now()
47
+ if today.day != pd.Period(today.strftime("%Y-%m")).days_in_month:
48
+ return "It's not the end of the month yet."
49
+
50
+ # Create end-of-month table
51
+ month = today.strftime("%Y-%m")
52
+ table_name = f"fees_{month.replace('-', '_')}"
53
+ cursor.execute(f"""
54
+ CREATE TABLE IF NOT EXISTS {table_name} (
55
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
56
+ name TEXT,
57
+ email TEXT,
58
+ fees REAL
59
+ )
60
+ """)
61
+
62
+ # Load participant data
63
+ participant_file = "participants_form.xlsx"
64
+ participants = pd.read_excel(participant_file)
65
+
66
+ # Calculate fees
67
+ fees_dict = calculate_fees()
68
+
69
+ # Populate table
70
+ for _, row in participants.iterrows():
71
+ name = row["Name"]
72
+ email = row["Email"]
73
+ fees = fees_dict.get(name, 0)
74
+
75
+ cursor.execute(f"""
76
+ INSERT INTO {table_name} (name, email, fees)
77
+ VALUES (?, ?, ?)
78
+ """, (name, email, fees))
79
+
80
+ conn.commit()
81
+ return f"End-of-month table '{table_name}' created successfully!"
82
 
 
83
  def submit_attendance(name, day, date, status):
84
  return log_attendance(name, day, date, status)
85
 
 
 
 
86
  def is_month_end():
87
  today = datetime.now()
88
+ return today.day == pd.Period(today.strftime("%Y-%m")).days_in_month
89
 
90
+
91
+ # Gradio Interface
92
  def get_dropdown_options(file_path, column_name):
 
93
  df = pd.read_excel(file_path)
 
94
  options = df["Name"].dropna().unique().tolist()
95
  options.sort()
96
  return options
97
 
98
 
 
99
  with gr.Blocks() as app:
100
  gr.Markdown("# Attendance Tracker")
101
 
102
  with gr.Row():
 
103
  file_path = "participants_form.xlsx"
104
  column_name = "Name"
105
  options = get_dropdown_options(file_path, column_name)
106
+ name = gr.Dropdown(choices=options, label="Select an Option")
 
 
 
 
 
 
 
107
  day = gr.Textbox(label="Day")
108
  date = gr.Textbox(label="Date (YYYY-MM-DD)")
109
  status = gr.Radio(["Present", "Absent"], label="Status")
 
111
  submit_button = gr.Button("Submit Attendance")
112
  submit_message = gr.Textbox(label="Message", interactive=False)
113
 
 
 
 
114
  submit_button.click(submit_attendance, inputs=[name, day, date, status], outputs=[submit_message])
 
115
 
116
+ def update_end_of_month():
117
+ return create_end_of_month_table()
118
 
119
+ app.load(update_end_of_month)
120
 
121
  app.launch()