Skip to content

Commit

Permalink
Merge pull request #202 from ezDecode/EnhanceCode
Browse files Browse the repository at this point in the history
Added some projects and enhances some code and improved the documenta…
  • Loading branch information
UTSAVS26 authored Oct 7, 2024
2 parents ac13396 + 313165f commit 28db389
Show file tree
Hide file tree
Showing 8 changed files with 616 additions and 211 deletions.
138 changes: 138 additions & 0 deletions Advanced_Projects/GUI Based TaskManager/mang.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import tkinter as tk
from tkinter import messagebox
import sqlite3
from datetime import datetime

# Database setup
conn = sqlite3.connect('tasks.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS tasks
(id INTEGER PRIMARY KEY, task TEXT, priority INTEGER, deadline TEXT, completed INTEGER)''')
conn.commit()

class TaskManager:
def __init__(self, root):
self.root = root
self.root.title("Task Manager")

self.create_widgets()
self.load_tasks()

def create_widgets(self):
# Task input
self.create_label_entry("Task", 0)
self.create_label_entry("Priority", 1)
self.create_label_entry("Deadline (YYYY-MM-DD)", 2)

# Buttons
self.create_button("Add Task", self.add_task, 3)
self.create_button("Update Task", self.update_task, 4)
self.create_button("Delete Task", self.delete_task, 5)
self.create_button("Mark as Completed", self.complete_task, 6)
self.create_button("Sort Tasks", self.sort_tasks, 7)

# Task list
self.task_listbox = tk.Listbox(self.root)
self.task_listbox.grid(row=8, column=0, columnspan=2)

def create_label_entry(self, text, row):
label = tk.Label(self.root, text=text)
label.grid(row=row, column=0)
entry = tk.Entry(self.root)
entry.grid(row=row, column=1)
setattr(self, f"{text.lower().split()[0]}_entry", entry)

def create_button(self, text, command, row):
button = tk.Button(self.root, text=text, command=command)
button.grid(row=row, column=0, columnspan=2)

def add_task(self):
task, priority, deadline = self.get_task_details()
if not task or not priority or not deadline:
return

c.execute("INSERT INTO tasks (task, priority, deadline, completed) VALUES (?, ?, ?, ?)",
(task, priority, deadline, 0))
conn.commit()
self.load_tasks()

def update_task(self):
selected_task = self.get_selected_task()
if not selected_task:
return

task_id = selected_task.split()[0]
task, priority, deadline = self.get_task_details()
if not task or not priority or not deadline:
return

c.execute("UPDATE tasks SET task = ?, priority = ?, deadline = ? WHERE id = ?",
(task, priority, deadline, task_id))
conn.commit()
self.load_tasks()

def delete_task(self):
selected_task = self.get_selected_task()
if not selected_task:
return

task_id = selected_task.split()[0]
c.execute("DELETE FROM tasks WHERE id = ?", (task_id,))
conn.commit()
self.load_tasks()

def complete_task(self):
selected_task = self.get_selected_task()
if not selected_task:
return

task_id = selected_task.split()[0]
c.execute("UPDATE tasks SET completed = 1 WHERE id = ?", (task_id,))
conn.commit()
self.load_tasks()

def sort_tasks(self):
c.execute("SELECT * FROM tasks ORDER BY priority, deadline")
tasks = c.fetchall()
self.update_task_listbox(tasks)

def load_tasks(self):
c.execute("SELECT * FROM tasks")
tasks = c.fetchall()
self.update_task_listbox(tasks)

def get_task_details(self):
task = self.task_entry.get()
priority = self.priority_entry.get()
deadline = self.deadline_entry.get()

if not task or not priority or not deadline:
messagebox.showwarning("Input Error", "All fields are required")
return None, None, None

try:
priority = int(priority)
datetime.strptime(deadline, '%Y-%m-%d')
except ValueError:
messagebox.showwarning("Input Error", "Invalid priority or deadline format")
return None, None, None

return task, priority, deadline

def get_selected_task(self):
selected_task = self.task_listbox.curselection()
if not selected_task:
messagebox.showwarning("Selection Error", "No task selected")
return None
return self.task_listbox.get(selected_task)

def update_task_listbox(self, tasks):
self.task_listbox.delete(0, tk.END)
for task in tasks:
self.task_listbox.insert(tk.END, f"{task[0]} {task[1]} (Priority: {task[2]}, Deadline: {task[3]}, Completed: {'Yes' if task[4] else 'No'})")

if __name__ == "__main__":
root = tk.Tk()
app = TaskManager(root)
root.mainloop()
conn.close()
90 changes: 90 additions & 0 deletions Advanced_Projects/GUI Based TaskManager/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Task Manager Application

This is a simple GUI-based Task Manager application built using Python's `tkinter` library and `sqlite3` for database management. The application allows users to add, update, delete, and mark tasks as completed. Tasks can also be sorted based on priority and deadline.

## Key Features

- **Add Task**: Add a new task with a description, priority, and deadline.
- **Update Task**: Update the details of an existing task.
- **Delete Task**: Remove a task from the list.
- **Mark as Completed**: Mark a task as completed.
- **Sort Tasks**: Sort tasks based on priority and deadline.
- **Persistent Storage**: Tasks are stored in a SQLite database, ensuring data persistence.

## Description

The application consists of a main window with input fields for task details, buttons for various actions, and a listbox to display the tasks. The tasks are stored in a SQLite database (`tasks.db`) with the following schema:

```sql
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY,
task TEXT,
priority INTEGER,
deadline TEXT,
completed INTEGER
);
```

## How to Use

1. **Setup**: Ensure you have Python installed on your system. Install the required libraries if not already available:
```bash
pip install tk
```

2. **Run the Application**: Save the provided code in a file (e.g., `task_manager.py`) and run it using Python:
```bash
python task_manager.py
```

3. **Add a Task**: Enter the task details (description, priority, deadline) in the respective fields and click "Add Task".

4. **Update a Task**: Select a task from the list, modify the details in the input fields, and click "Update Task".

5. **Delete a Task**: Select a task from the list and click "Delete Task".

6. **Mark as Completed**: Select a task from the list and click "Mark as Completed".

7. **Sort Tasks**: Click "Sort Tasks" to sort the tasks based on priority and deadline.

## Code Overview

The main components of the application are:

- **Database Setup**: Initializes the SQLite database and creates the `tasks` table if it doesn't exist.
- **TaskManager Class**: Manages the GUI and interactions with the database.
- `__init__`: Initializes the main window and loads tasks.
- `create_widgets`: Creates the input fields, buttons, and task listbox.
- `add_task`, `update_task`, `delete_task`, `complete_task`, `sort_tasks`: Methods to handle respective actions.
- `load_tasks`: Loads tasks from the database and displays them in the listbox.
- `get_task_details`: Retrieves task details from input fields and validates them.
- `get_selected_task`: Gets the currently selected task from the listbox.
- `update_task_listbox`: Updates the listbox with the provided tasks.
## Example
Here is an example of how the tasks are displayed in the listbox:
```
1 Buy groceries (Priority: 1, Deadline: 2023-10-01, Completed: No)
2 Finish project report (Priority: 2, Deadline: 2023-10-05, Completed: Yes)
```
## Closing the Application
When you close the application, the database connection is also closed to ensure data integrity.
```python
if __name__ == "__main__":
root = tk.Tk()
app = TaskManager(root)
root.mainloop()
conn.close()
```
This ensures that all changes are saved and the application exits gracefully.
## Author
`Akash Choudhury`
[GitHub Profile](https://github.com/ezDecode)
21 changes: 10 additions & 11 deletions Beginner_Projects/Bar-Code-Generator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,19 @@ The goal of this project is to create a barcode generator using Streamlit. The a
### 🧾 Description
This project is a barcode generator built with Streamlit, providing an easy-to-use interface for generating barcodes. Users can select from multiple barcode formats (EAN-13, EAN-8, UPCA), input the appropriate numeric code, and generate a barcode image. The generated barcode is displayed and can be downloaded as a PNG file.

### 🧮 What I had done!
Developed a Streamlit interface for selecting barcode types and entering barcode numbers.
Validated the input based on the selected barcode format.
Generated and displayed barcodes using the python-barcode library.
Added functionality for users to download the generated barcode image.
### 🧮 Features Implemented
- Developed a Streamlit interface for selecting barcode types and entering barcode numbers.
- Validated the input based on the selected barcode format.
- Generated and displayed barcodes using the `python-barcode` library.
- Added functionality for users to download the generated barcode image.

### 📚 Libraries Needed
Streamlit - For building the user interface.
python-barcode - To generate the barcodes.
base64 - For encoding the barcode image to display and download in the Streamlit app.
- **Streamlit**: For building the user interface.
- **python-barcode**: To generate the barcodes.
- **base64**: For encoding the barcode image to display and download in the Streamlit app.

### 📢 Conclusion
The barcode generator offers a simple and effective way for users to generate and download barcodes in various formats. The app handles input validation and provides a clean interface for creating barcodes, making it a useful tool for generating barcodes on demand.


**Akarsh Ghildyal**
[GitHub](https://github.com/AkarshGhildyal) | [LinkedIn](https://www.linkedin.com/in/akarsh-ghildyal/)


70 changes: 41 additions & 29 deletions Beginner_Projects/Bar-Code-Generator/barCodeGenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,62 +3,73 @@
import streamlit as st
import base64
import os
from io import BytesIO

# Set barcode type
# Dictionary to map barcode types to their respective lengths and classes
BARCODE_TYPE = {"EAN-13": [13, EAN13], "EAN-8": [8, EAN8], "UPCA": [12, UPCA]}

def barCodeGenerator():
st.markdown(
"""
<h1 style='text-align: center; color: #FF4B4B; font-family: Verdana;'>
BAR CODE GENERATOR📊
</h1>
""",
unsafe_allow_html=True,
Main function to render the Streamlit interface for barcode generation.
"""
# Display the title of the app
st.markdown(
"""
<h1 style='text-align: center; color: #FF4B4B; font-family: Verdana;'>
BAR CODE GENERATOR📊
</h1>
""",
unsafe_allow_html=True,
)

box = st.container() # To keep everything inside one container
# Create a container to hold all the elements
box = st.container()
with box:
# Radio buttons to select the type of barcode
option = st.radio(
"Select type of Barcode", ["EAN-13", "EAN-8", "UPCA"], horizontal=True
)
# Text input to enter the barcode number
num = st.text_input(
"Enter barcode number",
value="",
max_chars=BARCODE_TYPE[option][0],
placeholder=f"Enter {BARCODE_TYPE[option][0]} digits long barcode number",
)
button_div = st.empty() # So that when Generate Barcode is pressed, it will be replaced by Reset button

# Placeholder for the button
button_div = st.empty()

with button_div:
if st.button("Generate barcode"):
# Button to generate the barcode
if st.button("Generate barcode"):
generate(num, box, option)
st.button("Reset barcode") # Resets everything

# Button to reset the barcode
st.button("Reset barcode")

def generate(num, box, option):
"""
Function to generate and display the barcode.
Parameters:
num (str): The barcode number entered by the user.
box (streamlit.container): The container to hold the elements.
option (str): The type of barcode selected by the user.
"""
with box:
# Validate the barcode number
if len(num) != BARCODE_TYPE[option][0] or not num.isnumeric():
st.warning(
f"Please enter a valid {option} barcode of {BARCODE_TYPE[option][0]} digits!!"
)
else:
# Path for the image
image_path = "assets/barcode"

# Create the 'assets' directory if it doesn't exist
if not os.path.exists('assets'):
os.makedirs('assets')

# Generate the barcode and save it
# Generate the barcode and save it to a BytesIO stream
my_code = BARCODE_TYPE[option][1](num, writer=ImageWriter())
my_code.save(image_path)

# Open the saved image and encode it for display
with open(f"{image_path}.png", "rb") as file:
image_data = file.read()
image_stream = BytesIO()
my_code.write(image_stream)
image_stream.seek(0)

encoded_image = base64.b64encode(image_data).decode()
# Encode the image for display
encoded_image = base64.b64encode(image_stream.read()).decode()

# Display the barcode image and download button
st.markdown(
Expand Down Expand Up @@ -89,8 +100,9 @@ def generate(num, box, option):
<button class="styled-button">Download Image</button>
</a>
</div>
""",
""",
unsafe_allow_html=True,
)

barCodeGenerator()
# Run the main function to start the Streamlit app
barCodeGenerator()
Loading

0 comments on commit 28db389

Please sign in to comment.